Skip to content

Truly independent web browser

LibWasm: Share spill slots across phi webs, and pick merge registers

Andreas Kling842132e48c38
diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
index d9da5c51c68..6c7d0554c57 100644
--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs
+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
@@ -13,10 +13,13 @@
//! - Spilling happens at the definition: a value that ever needs a stack slot gets one for its whole life, and code
//! generation stores it there right after defining it, so a slot always holds its value once it has one. Values
//! live across a call get one, since calls clobber every register.
-//! - A block with one predecessor starts with that predecessor's registers. A merge starts with those of its last
-//! predecessor, and a loop header with those of the block entering the loop, without the values the loop only
-//! carries through that have a slot already. Their phis get registers that are free there, preferably those of
-//! the inputs from that predecessor. Every other edge into them moves its values into place, as parallel moves.
+//! - A phi and its inputs (its web) share slots where their intervals do not overlap, so that the moves into a phi's
+//! slot on its edges are no moves at all. A loop's back edge then leaves the values it carries where they are.
+//! - A block with one predecessor starts with that predecessor's registers. A merge starts with those of the
+//! predecessor that keeps the most of its values in registers, and a loop header with those of the block entering
+//! the loop, without the values the loop only carries through that have a slot already. Their phis get registers
+//! that are free there, preferably those of the inputs from that predecessor. Every other edge into them moves its
+//! values into place, as parallel moves.
//! Edges from blocks with several successors that need moves get a stub of their own in code generation.
#[cfg(target_arch = "aarch64")]
@@ -385,6 +388,13 @@ pub struct Allocator {
/// The registers values may get of each class, in order of preference.
gprs: &'static [Register],
fprs: &'static [Register],
+ /// The webs of phis and their inputs, as a union-find forest: each value's parent, or NONE for values in none.
+ web_parents: Vec<Value>,
+ /// The spill slots of each web, by its root: indices into `slot_values`.
+ web_slots: std::collections::HashMap<Value, Vec<u32>>,
+ /// The fp offset and the values of each spill slot a web has.
+ slot_offsets: Vec<i32>,
+ slot_values: Vec<Vec<Value>>,
}
use convention::{STRESS_FPRS, STRESS_GPRS};
@@ -433,6 +443,7 @@ impl Allocator {
self.end_states.resize(func.blocks.len(), [NONE; REGISTER_COUNT]);
self.header_states.clear();
self.header_states.resize(func.loops.len(), [NONE; REGISTER_COUNT]);
+ self.find_webs(func, liveliness);
for block in 0..func.blocks.len() as BlockId {
self.current_block = block;
@@ -495,7 +506,7 @@ impl Allocator {
}
}
- fn ensure_slot(func: &Func, allocation: &mut Allocation, value: Value) -> i32 {
+ fn ensure_slot(&mut self, func: &Func, allocation: &mut Allocation, value: Value) -> i32 {
let slot = allocation.slots[value as usize];
if slot != NO_SLOT {
return slot;
@@ -504,16 +515,109 @@ impl Allocator {
let slot = match node.op {
Op::Param => convention::home_slot_offset(convention::home_slot(&func.params, node.args[0] as usize)),
Op::Instance => convention::FRAME_INSTANCE,
- _ => {
- // NB: A v128 takes two slots, the lower of which has its address.
- allocation.slot_count += node.ty.slots();
- convention::spill_slot_offset(allocation.slot_count - 1)
- }
+ _ if self.web_parents[value as usize] != NONE => self.web_slot(func, allocation, value),
+ _ => Self::new_slot(func, allocation, value),
};
allocation.slots[value as usize] = slot;
slot
}
+ fn new_slot(func: &Func, allocation: &mut Allocation, value: Value) -> i32 {
+ // NB: A v128 takes two slots, the lower of which has its address.
+ allocation.slot_count += func.node(value).ty.slots();
+ convention::spill_slot_offset(allocation.slot_count - 1)
+ }
+
+ // Webs.
+
+ /// Puts each phi and its inputs in one web.
+ fn find_webs(&mut self, func: &Func, liveliness: &Liveliness) {
+ self.web_parents.clear();
+ self.web_parents.resize(func.nodes.len(), NONE);
+ self.web_slots.clear();
+ self.slot_offsets.clear();
+ self.slot_values.clear();
+ let in_web = |value: Value| {
+ let op = func.node(value).op;
+ liveness::is_allocated(func, liveliness, value) && op != Op::Forward && !op.is_entry_value()
+ };
+ for block in 0..func.blocks.len() as BlockId {
+ for phi in func.phis(block) {
+ if !in_web(phi) {
+ continue;
+ }
+ for &input in func.inputs(phi) {
+ if in_web(input) && func.node(input).ty.slots() == func.node(phi).ty.slots() {
+ self.union(phi, input);
+ }
+ }
+ }
+ }
+ }
+
+ fn web_root(&mut self, value: Value) -> Value {
+ let mut root = value;
+ while self.web_parents[root as usize] != root {
+ root = self.web_parents[root as usize];
+ }
+ let mut current = value;
+ while current != root {
+ let parent = self.web_parents[current as usize];
+ self.web_parents[current as usize] = root;
+ current = parent;
+ }
+ root
+ }
+
+ fn union(&mut self, first: Value, second: Value) {
+ for value in [first, second] {
+ if self.web_parents[value as usize] == NONE {
+ self.web_parents[value as usize] = value;
+ }
+ }
+ let first = self.web_root(first);
+ let second = self.web_root(second);
+ if first != second {
+ self.web_parents[second as usize] = first;
+ }
+ }
+
+ /// Whether the intervals of two values overlap, so that they cannot share a slot. A value whose interval ends where
+ /// another is defined does not overlap it: the node reads the one before it writes the other.
+ fn overlap(&self, first: Value, second: Value) -> bool {
+ let definitions = (
+ self.liveness.definition[first as usize],
+ self.liveness.definition[second as usize],
+ );
+ if definitions.0 == NONE || definitions.1 == NONE {
+ return true;
+ }
+ definitions.0 < self.liveness.end[second as usize] && definitions.1 < self.liveness.end[first as usize]
+ }
+
+ /// A slot of `value`'s web that no value overlapping it has, or a new one for the web.
+ fn web_slot(&mut self, func: &Func, allocation: &mut Allocation, value: Value) -> i32 {
+ let root = self.web_root(value);
+ let slots = self.web_slots.remove(&root).unwrap_or_default();
+ let shared = slots.iter().copied().find(|&index| {
+ self.slot_values[index as usize]
+ .iter()
+ .all(|&other| !self.overlap(value, other))
+ });
+ let index = shared.unwrap_or_else(|| {
+ self.slot_offsets.push(Self::new_slot(func, allocation, value));
+ self.slot_values.push(Vec::new());
+ self.slot_offsets.len() as u32 - 1
+ });
+ let mut slots = slots;
+ if shared.is_none() {
+ slots.push(index);
+ }
+ self.web_slots.insert(root, slots);
+ self.slot_values[index as usize].push(value);
+ self.slot_offsets[index as usize]
+ }
+
/// Frees `register`, keeping its value in its slot if it is still needed.
fn evict(&mut self, func: &Func, allocation: &mut Allocation, register: Register) {
let value = self.contents[register as usize];
@@ -521,7 +625,7 @@ impl Allocator {
return;
}
if self.liveness.is_live_after(value, self.position) {
- Self::ensure_slot(func, allocation, value);
+ self.ensure_slot(func, allocation, value);
}
self.free(register);
}
@@ -674,8 +778,18 @@ impl Allocator {
self.set_contents(state);
return;
}
- let state_predecessor = *predecessors.iter().max().expect("merges have predecessors");
- let mut state = self.filtered(func, &self.end_states[state_predecessor as usize], block);
+ // NB: The merge starts with the registers of the predecessor that keeps the most of its values in them, so that
+ // a path that called a function, which leaves none in registers, does not make the others give them up.
+ let (state_predecessor, mut state) = predecessors
+ .iter()
+ .map(|&predecessor| {
+ (
+ predecessor,
+ self.filtered(func, &self.end_states[predecessor as usize], block),
+ )
+ })
+ .max_by_key(|(predecessor, state)| (state.iter().filter(|value| **value != NONE).count(), *predecessor))
+ .expect("merges have predecessors");
self.place_phis(func, allocation, block, state_predecessor, &mut state);
for index in 0..func.predecessors(block).len() {
let predecessor = func.predecessors(block)[index];
@@ -725,7 +839,7 @@ impl Allocator {
state: &mut [u32; REGISTER_COUNT],
) {
let index = predecessor_index(func, block, predecessor);
- let end = &self.end_states[predecessor as usize];
+ let end = self.end_states[predecessor as usize];
for phi in func.phis(block) {
let float = is_float(func.node(phi).ty);
let input = func.inputs(phi)[index];
@@ -746,7 +860,7 @@ impl Allocator {
}
}
if register == NO_REGISTER {
- Self::ensure_slot(func, allocation, phi);
+ self.ensure_slot(func, allocation, phi);
} else {
state[register as usize] = phi;
}
@@ -1016,7 +1130,7 @@ impl Allocator {
self.assign(free, occupant);
}
None => {
- Self::ensure_slot(func, allocation, occupant);
+ self.ensure_slot(func, allocation, occupant);
self.free(register);
}
}
diff --git a/Libraries/LibWasm/JIT/src/regalloc/verify.rs b/Libraries/LibWasm/JIT/src/regalloc/verify.rs
index 7336de755d9..69442652906 100644
--- a/Libraries/LibWasm/JIT/src/regalloc/verify.rs
+++ b/Libraries/LibWasm/JIT/src/regalloc/verify.rs
@@ -7,23 +7,26 @@
//! The register allocation verifier. It simulates what every register holds through each block, from the state the
//! allocator says the block starts with, and checks that every input is where the allocation says, and that every
//! edge's moves turn the state at the end of its source into the state its target starts with (with phis replaced
-//! by their inputs). Slots belong to one value each and are written where it is defined, so reading a value from
-//! its own slot is always right.
+//! by their inputs). A value's slot is written where it is defined (a phi's where its block starts, or by the moves
+//! of its edges), and values that share a slot must have intervals that do not overlap, so that a slot that the
+//! block has not written holds the one of its values that is live there.
use super::{Allocation, CONSTANT_INPUT, Location, NO_REGISTER, REGISTER_COUNT, SLOT_INPUT, call_result_types};
use crate::convention::{self, Place};
use crate::ir::{BlockId, Func, NONE, Op, Shape, Value};
use crate::passes::cleanup::Liveliness;
-use crate::regalloc::liveness::predecessor_index;
+use crate::regalloc::liveness::{Liveness, block_start_position, edge_position, node_position, predecessor_index};
use std::collections::HashMap;
struct Simulation<'a> {
- allocation: &'a Allocation,
+ liveness: &'a Liveness,
registers: [u32; REGISTER_COUNT],
- /// What moves wrote to slots other than the values' own: phi slots and the cycle slot.
+ /// What the block wrote to slots so far.
slots: HashMap<i32, Value>,
- /// The value each slot belongs to.
- owners: HashMap<i32, Value>,
+ /// The values of each slot.
+ owners: HashMap<i32, Vec<Value>>,
+ /// The position the simulation is at.
+ position: u32,
errors: Vec<String>,
}
@@ -38,12 +41,24 @@ impl Simulation<'_> {
fn read(&self, location: Location) -> Option<Value> {
match location {
Location::Register(register) => Some(self.registers[register as usize]).filter(|value| *value != NONE),
- Location::Slot(slot) => self.slots.get(&slot).or_else(|| self.owners.get(&slot)).copied(),
+ Location::Slot(slot) => self.slots.get(&slot).copied().or_else(|| self.owner_at(slot)),
Location::Constant(value) => Some(value),
Location::Outgoing(_) | Location::ResultArea(_) => None,
}
}
+ /// The value of `slot` that is live at the current position, which a slot that the block did not write holds.
+ fn owner_at(&self, slot: i32) -> Option<Value> {
+ let owners = self.owners.get(&slot)?;
+ if let [owner] = owners.as_slice() {
+ return Some(*owner);
+ }
+ owners.iter().copied().find(|owner| {
+ self.liveness.definition[*owner as usize] < self.position
+ && self.liveness.end[*owner as usize] >= self.position
+ })
+ }
+
fn apply(&mut self, moves: &[super::Move]) {
for item in moves {
let value = self.read(item.from).unwrap_or(NONE);
@@ -60,9 +75,7 @@ impl Simulation<'_> {
fn check_holds(&mut self, location: Location, value: Value, what: &str) {
let ok = match location {
Location::Register(register) => self.registers[register as usize] == value,
- Location::Slot(slot) => {
- self.slots.get(&slot) == Some(&value) || self.allocation.slots[value as usize] == slot
- }
+ Location::Slot(slot) => self.read(Location::Slot(slot)) == Some(value),
Location::Constant(constant) => constant == value,
_ => true,
};
@@ -73,22 +86,48 @@ impl Simulation<'_> {
}
pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) -> Result<(), String> {
+ let mut liveness = Liveness::default();
+ liveness.compute(func, liveliness);
let mut simulation = Simulation {
- allocation,
+ liveness: &liveness,
registers: [NONE; REGISTER_COUNT],
slots: HashMap::new(),
owners: HashMap::new(),
+ position: 0,
errors: Vec::new(),
};
for (value, &slot) in allocation.slots.iter().enumerate() {
if slot != super::NO_SLOT {
- simulation.owners.insert(slot, value as Value);
+ simulation.owners.entry(slot).or_default().push(value as Value);
+ }
+ }
+ // The values of a slot follow each other: none is defined while another one is live.
+ let mut overlaps = Vec::new();
+ for (slot, owners) in &mut simulation.owners {
+ owners.sort_by_key(|owner| liveness.definition[*owner as usize]);
+ for pair in owners.windows(2) {
+ if liveness.end[pair[0] as usize] > liveness.definition[pair[1] as usize] {
+ overlaps.push(format!(
+ "v{} and v{} share [fp{slot:+}] while both are live",
+ pair[0], pair[1]
+ ));
+ }
}
}
+ for overlap in overlaps {
+ simulation.error(overlap);
+ }
let mut places = Vec::new();
for block in 0..func.blocks.len() as BlockId {
simulation.registers = allocation.block_states[block as usize];
simulation.slots.clear();
+ simulation.position = block_start_position(func, block);
+ for phi in func.phis(block) {
+ let slot = allocation.slots[phi as usize];
+ if slot != super::NO_SLOT {
+ simulation.slots.insert(slot, phi);
+ }
+ }
let data = func.blocks[block as usize];
for value in data.start..data.end {
let node = *func.node(value);
@@ -96,6 +135,7 @@ pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) ->
continue;
}
let record = *allocation.node(value);
+ simulation.position = node_position(value);
simulation.apply(allocation.node_moves(value));
let inputs = func.inputs(value);
match node.op {
@@ -179,8 +219,13 @@ pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) ->
if record.output != NO_REGISTER {
simulation.registers[record.output as usize] = value;
}
+ let slot = allocation.slots[value as usize];
+ if slot != super::NO_SLOT {
+ simulation.slots.insert(slot, value);
+ }
}
// The edges.
+ simulation.position = edge_position(func, block);
let end_registers = simulation.registers;
let end_slots = simulation.slots.clone();
let successors_start = data.successors_start;
@@ -212,7 +257,7 @@ pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) ->
}
let input = func.inputs(phi)[predecessor];
let slot = allocation.slots[phi as usize];
- if simulation.slots.get(&slot) != Some(&input) && allocation.slots[input as usize] != slot {
+ if simulation.read(Location::Slot(slot)) != Some(input) {
simulation.error(format!(
"edge b{block} -> b{successor}: the slot of phi v{phi} lacks v{input}"
));