Truly independent web browser
LibJS/JIT: Keep the data of six passes in the work zone
Andreas Klingbff0b5b0921e
diff --git a/Libraries/LibJS/JIT/Rust/src/bitset.rs b/Libraries/LibJS/JIT/Rust/src/bitset.rsindex 9e173e284aa..20ec55ee4bf 100644--- a/Libraries/LibJS/JIT/Rust/src/bitset.rs+++ b/Libraries/LibJS/JIT/Rust/src/bitset.rs@@ -137,6 +137,33 @@ impl BitSet {}}+/// A set of small integers that is fixed in size: a `BitSet` or a `ZoneBitSet`.+pub trait IndexSet {+ /// The exclusive upper bound of the integers this set can hold.+ fn capacity(&self) -> usize;+ fn contains(&self, index: usize) -> bool;+}++impl IndexSet for BitSet {+ fn capacity(&self) -> usize {+ BitSet::capacity(self)+ }++ fn contains(&self, index: usize) -> bool {+ BitSet::contains(self, index)+ }+}++impl IndexSet for ZoneBitSet<'_> {+ fn capacity(&self) -> usize {+ ZoneBitSet::capacity(self)+ }++ fn contains(&self, index: usize) -> bool {+ ZoneBitSet::contains(self, index)+ }+}+impl std::fmt::Debug for BitSet {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {formatter.debug_set().entries(self.iter()).finish()diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rsindex b3cc02d13ed..6c3dd4c53f3 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs@@ -576,8 +576,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {|| self.graph.frame_state_chain(parent)- .iter()- .any(|id| !self.graph.frame_state(*id).legacy_arguments.is_empty());+ .any(|id| !self.graph.frame_state(id).legacy_arguments.is_empty());if !has_legacy_arguments {return;}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rsindex 5ee1633a311..efe36c21f65 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs@@ -55,6 +55,7 @@ pub(crate) fn build_with_layout(program: &Program, layout: FrameLayout, never_ratrue,&mut Dominators::new(),&mut crate::test_work(),+ &mut crate::test_steps(),).unwrap();graph@@ -69,6 +70,7 @@ pub(crate) fn optimized_graph(snapshot: &Snapshot) -> Graph<'static> {true,&mut Dominators::new(),&mut crate::test_work(),+ &mut crate::test_steps(),).unwrap();graphdiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rsindex 2eeb0731ee5..0f60b726524 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs@@ -898,7 +898,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {_ => return None,};let frame_state = self.graph.node(node).frame_state.expect("calls have a frame state");- let chain = self.graph.frame_state_chain(frame_state);+ let chain = self.graph.frame_state_chain(frame_state).collect::<Vec<_>>();let outer = *chain.last().expect("a frame state chain has a frame state");let index = u32::try_from(self.sites.len()).expect("site count fits in u32");self.sites.push((node, SiteKind::Call));diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 687ce3bf9cb..c10f1b06903 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -1972,7 +1972,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {.map(|frame_state| {// NB: Only the compiled function's own frame, the outermost// one, keeps an arguments object virtual.- let root = *self+ let root = self.graph.frame_state_chain(frame_state).last()@@ -3385,7 +3385,7 @@ impl<'a, M: PortableMacroAssembler> Codegen<'a, M> {/// in, and the pc and block of its catch entry, if it has one.fn catch_entry_of(&self, node: NodeId) -> Result<Option<(u32, u32, u32, BlockId)>, CompileFailure> {let frame_state = self.graph.node(node).frame_state.expect("leaves have a frame state");- let root = *self+ let root = self.graph.frame_state_chain(frame_state).last()diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rsindex 17062e8cf6b..b7ac02196a8 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs@@ -88,7 +88,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.node(node).frame_state.expect("publishing nodes have a frame state");- let chain = self.graph.frame_state_chain(frame_state);+ let chain = self.graph.frame_state_chain(frame_state).collect::<Vec<_>>();let pushed = chain.len() - 1;// NB: Compiled code writes the headers itself, unless a value they// need is one it cannot write (a virtual object).@@ -268,7 +268,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.frame_state.expect("fast paths have a frame state");// NB: Frame state values are listed innermost frame first.- let chain = self.graph.frame_state_chain(frame_state);+ let chain = self.graph.frame_state_chain(frame_state).collect::<Vec<_>>();let mut locations = self.allocation.node(node).exit_values.iter().copied();let mut frames = Vec::new();for id in &chain {diff --git a/Libraries/LibJS/JIT/Rust/src/coverage.rs b/Libraries/LibJS/JIT/Rust/src/coverage.rsindex 0343d24b2a1..5e158a44112 100644--- a/Libraries/LibJS/JIT/Rust/src/coverage.rs+++ b/Libraries/LibJS/JIT/Rust/src/coverage.rs@@ -36,7 +36,7 @@ pub fn coverage_keys(graph: &Graph) -> Vec<String> {.frame_states.iter().enumerate()- .map(|(index, _)| graph.frame_state_chain(crate::ir::FrameStateId(index as u32)).len())+ .map(|(index, _)| graph.frame_state_chain(crate::ir::FrameStateId(index as u32)).count()).max().unwrap_or(0);if inlined_depth > 1 {diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex f4d1f58e0a4..995a2893891 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -1628,7 +1628,7 @@ pub struct FrameState<'z> {/// The memory of all the lists of a graph is in one zone (see `ak::Zone`): a graph makes no block of the heap, and/// all of it goes away when its zone is reset.-#[derive(Debug, Clone)]+#[derive(Debug)]pub struct Graph<'z> {/// Where the lists of the graph are, and where its nodes, blocks and frame states get their lists.pub zone: &'z Zone,@@ -1725,6 +1725,98 @@ impl<'z> Graph<'z> {}}+ /// A copy of the graph, whose lists are in `zone`.+ pub fn clone_in<'c>(&self, zone: &'c Zone) -> Graph<'c>+ where+ 'z: 'c,+ {+ let Graph {+ zone: _,+ nodes,+ blocks,+ frame_states,+ embedded_cells,+ dependencies,+ stable_shapes,+ typed_array_constants,+ direct_call_targets,+ materialized_frame_bytes,+ osr_entries,+ osr_loop_back_edges,+ osr_outer_loop_back_edges,+ uncaught_handlers,+ slow_paths_initializing_frame,+ exit_sites,+ speculatively_hoisted,+ legacy_arguments,+ legacy_arguments_guards,+ unwritten_slots,+ } = self;+ let list = |values: &[NodeId]| ZoneVec::from_slice_in(values, zone);+ let mut unwritten = crate::bitset::ZoneBitSet::new_in(unwritten_slots.capacity(), zone);+ unwritten.union_with(unwritten_slots);+ Graph {+ zone,+ nodes: ZoneVec::from_iter_in(+ nodes.iter().map(|node| Node {+ op: node.op.clone(),+ inputs: list(&node.inputs),+ repr: node.repr,+ frame_state: node.frame_state,+ pc: node.pc,+ }),+ zone,+ ),+ blocks: ZoneVec::from_iter_in(+ blocks.iter().map(|block| Block {+ predecessors: ZoneVec::from_slice_in(&block.predecessors, zone),+ phis: list(&block.phis),+ body: list(&block.body),+ control: block.control,+ bytecode_start: block.bytecode_start,+ is_loop_header: block.is_loop_header,+ is_cold: block.is_cold,+ start_frame_state: block.start_frame_state,+ }),+ zone,+ ),+ frame_states: ZoneVec::from_iter_in(+ frame_states.iter().map(|frame_state| FrameState {+ executable: frame_state.executable,+ pc: frame_state.pc,+ mode: frame_state.mode,+ values: ZoneVec::from_slice_in(&frame_state.values, zone),+ in_frame: ZoneVec::from_slice_in(&frame_state.in_frame, zone),+ parent: frame_state.parent,+ passed_argument_count: frame_state.passed_argument_count,+ legacy_arguments: frame_state.legacy_arguments.clone(),+ }),+ zone,+ ),+ embedded_cells: ZoneVec::from_slice_in(embedded_cells, zone),+ dependencies: ZoneVec::from_slice_in(dependencies, zone),+ stable_shapes: ZoneVec::from_slice_in(stable_shapes, zone),+ typed_array_constants: ZoneVec::from_slice_in(typed_array_constants, zone),+ direct_call_targets: ZoneVec::from_slice_in(direct_call_targets, zone),+ materialized_frame_bytes: *materialized_frame_bytes,+ osr_entries: ZoneVec::from_slice_in(osr_entries, zone),+ osr_loop_back_edges: ZoneVec::from_slice_in(osr_loop_back_edges, zone),+ osr_outer_loop_back_edges: ZoneVec::from_slice_in(osr_outer_loop_back_edges, zone),+ uncaught_handlers: ZoneVec::from_slice_in(uncaught_handlers, zone),+ slow_paths_initializing_frame: list(slow_paths_initializing_frame),+ exit_sites: ZoneVec::from_slice_in(exit_sites, zone),+ speculatively_hoisted: list(speculatively_hoisted),+ legacy_arguments: legacy_arguments.clone(),+ legacy_arguments_guards: ZoneVec::from_iter_in(+ legacy_arguments_guards+ .iter()+ .map(|(guard, nodes)| (*guard, list(nodes))),+ zone,+ ),+ unwritten_slots: unwritten,+ }+ }+/// A list of `values` in the memory of the graph.pub fn list<T: Clone>(&self, values: &[T]) -> ZoneVec<'z, T> {ZoneVec::from_slice_in(values, self.zone)@@ -1787,12 +1879,8 @@ impl<'z> Graph<'z> {}/// A frame state and its callers' frame states, innermost first.- pub fn frame_state_chain(&self, id: FrameStateId) -> Vec<FrameStateId> {- let mut chain = vec![id];- while let Some(parent) = self.frame_state(*chain.last().expect("the chain is not empty")).parent {- chain.push(parent);- }- chain+ pub fn frame_state_chain(&self, id: FrameStateId) -> impl Iterator<Item = FrameStateId> + Clone + '_ {+ std::iter::successors(Some(id), |id| self.frame_state(*id).parent)}/// The values `node` uses: its inputs, then the values of its frame@@ -1813,24 +1901,21 @@ impl<'z> Graph<'z> {&self,node: NodeId,frames: impl Fn(&FrameState<'z>) -> bool,- ) -> Vec<NodeId> {+ ) -> impl Iterator<Item = NodeId> {let data = self.node(node);- let Some(frame_state) = data.frame_state.filter(|_| data.op.properties().runs_code) else {- return Vec::new();- };- let mut values = Vec::new();- for id in self.frame_state_chain(frame_state) {- let frame_state = self.frame_state(id);- if !frames(frame_state) {- continue;- }- for (slot, value) in &frame_state.values {- if frame_state.legacy_arguments.contains(slot) {- values.push(*value);- }- }- }- values+ let frame_state = data.frame_state.filter(|_| data.op.properties().runs_code);+ frame_state+ .into_iter()+ .flat_map(|frame_state| self.frame_state_chain(frame_state))+ .map(|id| self.frame_state(id))+ .filter(move |frame_state| frames(frame_state))+ .flat_map(|frame_state| {+ frame_state+ .values+ .iter()+ .filter(|(slot, _)| frame_state.legacy_arguments.contains(slot))+ .map(|(_, value)| *value)+ })}/// Whether code that `node` runs may read objects the code never@@ -1839,7 +1924,6 @@ impl<'z> Graph<'z> {/// node's site (see `Op::AssumeLegacyArgumentsUnread`).pub fn defers_legacy_argument_objects(&self, node: NodeId) -> bool {self.legacy_argument_values_read_by(node, |_| true)- .into_iter().any(|value| matches!(self.node(value).op, Op::VirtualObject { .. }))}@@ -1884,7 +1968,7 @@ impl<'z> Graph<'z> {}fn chain_values(&self, id: FrameStateId) -> impl Iterator<Item = (u32, NodeId)> + '_ {- std::iter::successors(Some(id), |id| self.frame_state(*id).parent)+ self.frame_state_chain(id).flat_map(|id| self.frame_state(id).values.iter().copied())}diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex 06b88d5623d..a184403351c 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -103,6 +103,12 @@ pub(crate) fn test_work() -> ak::Zone {ak::Zone::new(1 << 30, c"test")}+/// The zones for the steps of the passes that a test runs (see `Scratch::steps`).+#[cfg(test)]+pub(crate) fn test_steps() -> [ak::Zone; 2] {+ [test_work(), test_work()]+}+/// Compiles `snapshot.executables[0]` for the host architecture with the memory of `scratch`, into `compiled` in/// place of what it holds. After a failure, `compiled` holds no complete code.pub fn compile(snapshot: &Snapshot, scratch: &mut Scratch, compiled: &mut CompiledCode) -> Result<(), CompileFailure> {@@ -161,7 +167,12 @@ fn run_stages<M: asm::PortableMacroAssembler>(if !snapshot.is_complete() {return Err(CompileFailure::TooLarge);}- let Scratch { zone, work, tables } = scratch;+ let Scratch {+ zone,+ work,+ steps,+ tables,+ } = scratch;// NB: Nothing of the compile before this one is in use (see `Scratch`).work.reset();let mut graph = {@@ -184,6 +195,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(snapshot.options.verify_ir,&mut tables.dominators,work,+ steps,)?)} else {passes::optimize(@@ -192,6 +204,7 @@ fn run_stages<M: asm::PortableMacroAssembler>(snapshot.options.verify_ir,&mut tables.dominators,work,+ steps,)?;None};diff --git a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rsindex 1d30c0a2204..39105abb184 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/bounds_check_elimination.rs@@ -515,7 +515,7 @@ fn entering_counters(entering}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Result<(), ColumnFull> {+pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {let mut phi_blocks = HashMap::default();let mut checks = Vec::new();let mut shifts = Vec::new();@@ -672,13 +672,13 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Resu.map(|(value, range)| (*value, range.max + 1)).collect::<Vec<_>>();- let mut replacements = Replacements::new(graph);+ let mut replacements = Replacements::new(graph, work);let mut removed = BitSet::new(graph.nodes.len());for check in passing {replacements.replace(check, graph.node(check).inputs[0]);removed.insert(check.index());}- let mut constants = Constants::new(graph);+ let mut constants = Constants::new(graph, work);let mut guard_nodes = Vec::new();for (value, bound) in guards {let count = constants.get_typed(graph, u64::from((bound as i32).cast_unsigned()), Repr::Int32);diff --git a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rsindex 45bc1c94048..d2849e79677 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs@@ -192,9 +192,9 @@ fn frame_state_sides(.values.iter().any(|(_, value)| phis.contains(value.index()));- let chain_holds = graph.frame_state_chain(frame_state)[1..].iter().any(|id| {+ let chain_holds = graph.frame_state_chain(frame_state).skip(1).any(|id| {graph- .frame_state(*id)+ .frame_state(id).values.iter().any(|(_, value)| phis.contains(value.index()))@@ -202,8 +202,7 @@ fn frame_state_sides(let all_count = graph.frame_state_values(frame_state).count();let chain_count: usize = graph.frame_state_chain(frame_state)- .iter()- .map(|id| graph.frame_state(*id).values.len())+ .map(|id| graph.frame_state(id).values.len()).sum();// NB: Virtual objects add values past those of the chain's frames.let virtual_holds = all_count != chain_count@@ -235,7 +234,7 @@ fn renamed(renames: &[(NodeId, NodeId)], value: NodeId) -> NodeId {/// Splits one block, if any has the shape of `Split` and all uses of its/// phis are on one side of its branch. Returns whether it split one.-fn split_one(graph: &mut Graph, dominators: &mut Dominators) -> Result<bool, ColumnFull> {+fn split_one(graph: &mut Graph, dominators: &mut Dominators, step: &Zone) -> Result<bool, ColumnFull> {dominators.compute(graph)?;let dominators = &*dominators;for index in 0..graph.blocks.len() {@@ -364,15 +363,22 @@ fn split_one(graph: &mut Graph, dominators: &mut Dominators) -> Result<bool, Colfor phi in block_phis {graph.nodes[phi.index()].inputs.clear();}- super::edit::clean_up_control_flow(graph);+ super::edit::clean_up_control_flow(graph, step);return Ok(true);}Ok(false)}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Result<(), ColumnFull> {+pub fn run(+ graph: &mut Graph,+ dominators: &mut Dominators,+ _work: &Zone,+ steps: &mut [Zone; 2],+) -> Result<(), ColumnFull> {+ let [step, _] = steps;for _ in 0..graph.blocks.len() {- if !split_one(graph, dominators)? {+ // NB: Each split cleans up the control flow, with data as large as the graph, which goes when the split ends.+ if !step.scope(|step| split_one(graph, dominators, step))? {break;}}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rsindex 9e54446eb70..0285f16df61 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs@@ -41,12 +41,12 @@ use super::facts::BranchKey;use super::facts::ElementCount;use super::facts::Facts;use super::facts::Location;+use super::facts::Moved;use super::facts::ValueKind;use super::facts::elements_kind_implies;-use crate::bitset::BitSet;+use crate::bitset::ZoneBitSet;use crate::bytecode::OpCode;use crate::code::Dependency;-use crate::inline_vec::InlineVec;use crate::ir::BlockId;use crate::ir::BranchCondition;use crate::ir::ElementsKind;@@ -57,31 +57,48 @@ use crate::ir::ShapeCheck;use crate::ir::value;use crate::snapshot::CellId;use ak::Zone;+use ak::ZoneVec;/// What the analysis decided for the nodes of one visit of the graph.-struct Decisions {- replacements: Replacements,- removed: BitSet,+struct Decisions<'w> {+ replacements: Replacements<'w>,+ removed: ZoneBitSet<'w>,/// Control nodes to replace, with what.- controls: Vec<(NodeId, NewControl)>,+ controls: ZoneVec<'w, (NodeId, NewControl<'w>)>,/// Shape checks that become `AssumeValid` nodes.- assumptions: Vec<NodeId>,+ assumptions: ZoneVec<'w, NodeId>,/// The stable shapes the code relies on staying stable.- stable_shapes: Vec<CellId>,+ stable_shapes: ZoneVec<'w, CellId>,+ /// The inputs of the node being visited, as the analysis knows them.+ inputs: ZoneVec<'w, NodeId>,+ /// The cases of the shape switch being visited that can match.+ possible: ZoneVec<'w, (ShapeCheck, BlockId)>,}+/// Facts flowing along edges, each with the block the edge leads to.+type Edges<'w> = ZoneVec<'w, (BlockId, Facts<'w>)>;+/// What a control node is replaced with.-enum NewControl {+enum NewControl<'w> {Jump {target: BlockId,},/// A shape switch with fewer cases, each a shape and its target.ShapeSwitch {- cases: Vec<(ShapeCheck, BlockId)>,+ cases: &'w [(ShapeCheck, BlockId)],},}-impl Decisions {+impl Decisions<'_> {+ /// Forgets the decisions of the last visit.+ fn clear(&mut self) {+ self.replacements.clear();+ self.removed.clear();+ self.controls.clear();+ self.assumptions.clear();+ self.stable_shapes.clear();+ }+/// The value the analysis knows `value` as: what it is replaced by, and/// the value it refines (facts are about values, whatever refines them).fn value(&self, graph: &Graph, value: NodeId) -> NodeId {@@ -97,78 +114,127 @@ impl Decisions {}}-pub fn run(graph: &mut Graph, _work: &Zone) {- let mut constants = Constants::new(graph);- let block_count = graph.blocks.len();- // The facts flowing along each edge, from the latest visit of its source.- let mut edge_facts: Vec<Vec<(BlockId, Facts)>> = vec![Vec::new(); block_count];- // NB: Only blocks with predecessors later in the order can see other- // facts in another visit: they decide when the visits are done.- let mut entry_facts: Vec<Option<Facts>> = vec![None; block_count];- let revisited = (0..block_count)- .map(|block| {- graph.blocks[block]- .predecessors+/// The edges out of a block, each with the slot of the facts along it in the `Store`.+type EdgeSlots<'w> = ZoneVec<'w, (BlockId, u32)>;++/// The facts that the visits of blocks hand on to later ones, in a step zone. Each is in a slot, which the tables of+/// `Round` name, so that a move of the facts in use copies those and nothing else.+struct Store<'f> {+ zone: &'f Zone,+ /// The facts of each slot, or none for a slot that is free.+ facts: ZoneVec<'f, Option<Facts<'f>>>,+ /// The facts along the edges into the block being visited, which is empty between visits.+ incoming: Edges<'f>,+ /// The facts along the edges out of the block being visited, which is empty between visits.+ outgoing: Edges<'f>,+}++impl<'f> Store<'f> {+ fn new_in(zone: &'f Zone) -> Self {+ Self {+ zone,+ facts: ZoneVec::new_in(zone),+ incoming: ZoneVec::new_in(zone),+ outgoing: ZoneVec::new_in(zone),+ }+ }++ /// Puts `facts` in a slot that `free` lists, or in a new one, and returns the slot.+ fn put(&mut self, facts: Facts<'f>, free: &mut ZoneVec<u32>) -> u32 {+ if let Some(slot) = free.pop() {+ self.facts[slot as usize] = Some(facts);+ return slot;+ }+ self.facts.push(Some(facts));+ u32::try_from(self.facts.len() - 1).expect("the facts in use fit in 2^32 slots")+ }++ /// Takes the facts of `slot`, which becomes free.+ fn take(&mut self, slot: u32, free: &mut ZoneVec<u32>) -> Facts<'f> {+ free.push(slot);+ self.facts[slot as usize].take().expect("a slot in use holds facts")+ }++ fn get(&self, slot: u32) -> &Facts<'f> {+ self.facts[slot as usize].as_ref().expect("a slot in use holds facts")+ }++ fn get_mut(&mut self, slot: u32) -> &mut Facts<'f> {+ self.facts[slot as usize].as_mut().expect("a slot in use holds facts")+ }++ /// The same facts in the same slots, in `zone`, with lists that are shared where they are here.+ fn move_to(self, zone: &Zone) -> Store<'_> {+ debug_assert!(self.incoming.is_empty() && self.outgoing.is_empty());+ let mut moved = Moved::new_in(zone);+ let facts = ZoneVec::from_iter_in(+ self.facts.iter()- .any(|predecessor| predecessor.index() >= block)- })- .collect::<Vec<_>>();- let decisions = loop {- let mut decisions = Decisions {- replacements: Replacements::new(graph),- removed: BitSet::new(graph.nodes.len()),- controls: Vec::new(),- assumptions: Vec::new(),- stable_shapes: Vec::new(),- };- let mut changed = false;- let mut visited = vec![false; block_count];- let mut skipped = Vec::new();- for block in 0..block_count {- let block_id = BlockId::from_index(block);- let Some(facts) = facts_at_entry(graph, block_id, &mut edge_facts, &visited, &revisited, &decisions) else {- // No visited predecessor reaches this block.- edge_facts[block].clear();- skipped.push(block_id);- continue;- };- visited[block] = true;- if revisited[block] && entry_facts[block].as_ref() != Some(&facts) {- changed = true;- entry_facts[block] = Some(facts.clone());- }- edge_facts[block] = visit_block(graph, &mut constants, block_id, facts, &mut decisions);- }- // NB: A block that only back edges lead to (code after an entry that- // comes later in the order, such as an on-stack replacement- // entry) is skipped until they bring facts, which they did if a- // predecessor visited later has facts along its edge. What can- // be reached from it then saw other facts along the other paths- // in this round.- changed |= skipped.iter().any(|block| {- graph.block(*block).predecessors.iter().any(|predecessor| {- edge_facts[predecessor.index()]- .iter()- .any(|(target, _)| target == block)- })- });- if !changed {- break decisions;+ .map(|facts| facts.as_ref().map(|facts| facts.move_to(&mut moved))),+ zone,+ );+ Store {+ zone,+ facts,+ incoming: ZoneVec::new_in(zone),+ outgoing: ZoneVec::new_in(zone),}+ }+}++/// How many bytes a step zone of the pass may hold before the facts still in use move to the other one: twice what+/// they took right after the last move, and at least 1 MiB, so that the zone holds at most about three times the facts+/// in use, and the facts of small functions never move.+fn move_limit(kept: usize) -> usize {+ (2 * kept).max(1 << 20)+}++pub fn run(graph: &mut Graph, work: &Zone, steps: &mut [Zone; 2]) {+ let mut constants = Constants::new(graph, work);+ // NB: The visits add no nodes to blocks, only constants.+ let mut decisions = Decisions {+ replacements: Replacements::new(graph, work),+ removed: ZoneBitSet::new_in(graph.nodes.len(), work),+ controls: ZoneVec::new_in(work),+ assumptions: ZoneVec::new_in(work),+ stable_shapes: ZoneVec::new_in(work),+ inputs: ZoneVec::new_in(work),+ possible: ZoneVec::new_in(work),};+ let mut round = Round::new(graph, &mut constants, &mut decisions, work);+ // NB: The facts of each block copy lists of the facts before it, which a zone takes back only all at once. So+ // the visits stop when the store of the facts holds much more than after the last move, the facts in use+ // move to the other step zone, and the zone they leave is reset.+ let [zone, other] = steps;+ let mut store = Store::new_in(zone);+ let mut kept = 0;+ loop {+ if round.run(&mut store, move_limit(kept)) {+ break;+ }+ let mut moved = store.move_to(other);+ kept = other.used();+ zone.reset();+ if round.run(&mut moved, move_limit(kept)) {+ break;+ }+ store = moved.move_to(zone);+ kept = zone.used();+ other.reset();+ }decisions.replacements.apply(graph);edit::remove_nodes(graph, &decisions.removed);- for node in decisions.assumptions {+ for node in decisions.assumptions.drain_all() {graph.nodes[node.index()].op = Op::AssumeValid;graph.nodes[node.index()].inputs.clear();graph.nodes[node.index()].repr = None;}- for shape in decisions.stable_shapes {+ for shape in decisions.stable_shapes.drain_all() {graph.depend_on(Dependency::StableShape(shape));}let changed_control_flow = !decisions.controls.is_empty();- for (node, control) in decisions.controls {+ for (node, control) in decisions.controls.drain_all() {match control {NewControl::Jump { target } => edit::make_jump(graph, node, target),NewControl::ShapeSwitch { cases } => {@@ -181,7 +247,164 @@ pub fn run(graph: &mut Graph, _work: &Zone) {}}if changed_control_flow {- edit::clean_up_control_flow(graph);+ edit::clean_up_control_flow(graph, work);+ }+}++/// The rounds of visits of the blocks, until the facts stop changing, with what lasts from one visit to the next+/// apart from the facts themselves: the slots of the facts in the `Store`, which can move to another zone between+/// two visits.+struct Round<'a, 'g, 'w> {+ graph: &'a mut Graph<'g>,+ constants: &'a mut Constants<'w>,+ decisions: &'a mut Decisions<'w>,+ /// Whether each block has predecessors later in the order. Only those can see other facts in another round:+ /// they decide when the rounds are done.+ revisited: ZoneVec<'w, bool>,+ visited: ZoneVec<'w, bool>,+ skipped: ZoneVec<'w, BlockId>,+ /// For each block, the edges out of it from its latest visit that no block took the facts of yet.+ edges: ZoneVec<'w, EdgeSlots<'w>>,+ /// For each block that `revisited` holds for, the slot of its facts at entry from its latest visit, if any.+ entry_facts: ZoneVec<'w, Option<u32>>,+ /// The slots of the store that are free.+ free: ZoneVec<'w, u32>,+ /// Whether the facts changed in this round.+ changed: bool,+ /// The block to visit next in this round.+ next: usize,+}++impl<'a, 'g, 'w> Round<'a, 'g, 'w> {+ fn new(+ graph: &'a mut Graph<'g>,+ constants: &'a mut Constants<'w>,+ decisions: &'a mut Decisions<'w>,+ work: &'w Zone,+ ) -> Self {+ let block_count = graph.blocks.len();+ let revisited = ZoneVec::from_iter_in(+ (0..block_count).map(|block| {+ graph.blocks[block]+ .predecessors+ .iter()+ .any(|predecessor| predecessor.index() >= block)+ }),+ work,+ );+ let mut round = Self {+ graph,+ constants,+ decisions,+ revisited,+ visited: ZoneVec::from_elem_in(false, block_count, work),+ skipped: ZoneVec::new_in(work),+ edges: ZoneVec::from_iter_in((0..block_count).map(|_| ZoneVec::new_in(work)), work),+ entry_facts: ZoneVec::from_elem_in(None, block_count, work),+ free: ZoneVec::new_in(work),+ changed: false,+ next: 0,+ };+ round.start();+ round+ }++ /// Starts a round.+ fn start(&mut self) {+ self.decisions.clear();+ self.changed = false;+ self.visited.fill(false);+ self.skipped.clear();+ self.next = 0;+ }++ /// Visits blocks until the facts stop changing, and returns true, or until `store` holds more than `limit` bytes+ /// before a visit, and returns false. It goes on where it stopped when it is called again.+ fn run(&mut self, store: &mut Store, limit: usize) -> bool {+ loop {+ if self.next == self.graph.blocks.len() {+ // NB: A block that only back edges lead to (code after an entry that comes later in the order,+ // such as an on-stack replacement entry) is skipped until they bring facts, which they did if+ // a predecessor visited later has facts along its edge. What can be reached from it then saw+ // other facts along the other paths in this round.+ let edges = &self.edges;+ let graph = &*self.graph;+ self.changed |= self.skipped.iter().any(|block| {+ graph+ .block(*block)+ .predecessors+ .iter()+ .any(|predecessor| edges[predecessor.index()].iter().any(|(target, _)| target == block))+ });+ if !self.changed {+ return true;+ }+ self.start();+ continue;+ }+ if store.zone.used() > limit {+ return false;+ }+ self.visit(store, self.next);+ self.next += 1;+ }+ }++ /// Frees the slots of the edges out of `block`.+ fn clear_edges(&mut self, store: &mut Store, block: usize) {+ for (_, slot) in self.edges[block].drain_all() {+ store.take(slot, &mut self.free);+ }+ }++ /// Visits `block`, with the facts along the edges into it, and hands on the facts along the edges out of it.+ fn visit(&mut self, store: &mut Store, block: usize) {+ let block_id = BlockId::from_index(block);+ let mut incoming = store.incoming.take();+ let facts = facts_at_entry(+ self.graph,+ block_id,+ (&mut self.edges, store, &mut self.free, &mut incoming),+ &self.visited,+ &self.revisited,+ self.decisions,+ );+ store.incoming = incoming;+ let Some(mut facts) = facts else {+ // No visited predecessor reaches this block.+ self.clear_edges(store, block);+ self.skipped.push(block_id);+ return;+ };+ self.visited[block] = true;+ if self.revisited[block] {+ match self.entry_facts[block] {+ Some(slot) if *store.get(slot) == facts => {}+ Some(slot) => {+ self.changed = true;+ *store.get_mut(slot) = facts.share();+ }+ None => {+ self.changed = true;+ self.entry_facts[block] = Some(store.put(facts.share(), &mut self.free));+ }+ }+ }+ self.clear_edges(store, block);+ let mut outgoing = store.outgoing.take();+ visit_block(+ self.graph,+ self.constants,+ block_id,+ facts,+ self.decisions,+ &mut outgoing,+ );+ for (target, facts) in outgoing.drain_all() {+ let slot = store.put(facts, &mut self.free);+ self.edges[block].push((target, slot));+ }+ store.outgoing = outgoing;}}@@ -194,32 +417,41 @@ pub fn run(graph: &mut Graph, _work: &Zone) {////// A phi of a block that no back edge leads to is of a kind one of its/// inputs is, where it comes from.-fn facts_at_entry(+///+/// It takes the facts of the edges into the block out of `store`, whose+/// slots `edges` names, and frees their slots in `free`. `incoming` is a list+/// for the facts along the edges into the block, which is empty and stays+/// empty.+fn facts_at_entry<'f>(graph: &Graph,block: BlockId,- edge_facts: &mut [Vec<(BlockId, Facts)>],+ (edges, store, free, incoming): (&mut [EdgeSlots], &mut Store<'f>, &mut ZoneVec<u32>, &mut Edges<'f>),visited: &[bool],revisited: &[bool],decisions: &Decisions,-) -> Option<Facts> {+) -> Option<Facts<'f>> {+ let zone = store.zone;let predecessors = &graph.block(block).predecessors;if predecessors.is_empty() {- let mut facts = Facts::default();+ let mut facts = Facts::new_in(zone);facts.assume_code_valid();return Some(facts);}- let mut incoming = Vec::new();for predecessor in predecessors {let is_back_edge = predecessor.index() >= block.index();if !is_back_edge && !visited[predecessor.index()] {continue;}- let edges = &mut edge_facts[predecessor.index()];- incoming.extend(- edges- .extract_if(.., |(target, _)| *target == block)- .map(|(_, facts)| (*predecessor, facts)),- );+ let edges = &mut edges[predecessor.index()];+ let mut index = 0;+ while index < edges.len() {+ if edges[index].0 == block {+ let (_, slot) = edges.remove(index);+ incoming.push((*predecessor, store.take(slot, free)));+ } else {+ index += 1;+ }+ }}let phis = &graph.block(block).phis;// NB: Each predecessor brings the facts along its one edge here.@@ -233,10 +465,10 @@ fn facts_at_entry(return match incoming.len() {0 => None,1 => incoming.pop().map(|(_, facts)| facts),- _ => Some(Facts::merge(incoming.into_iter().map(|(_, facts)| facts))),+ _ => Some(Facts::merge(zone, incoming.drain_all().map(|(_, facts)| facts))),};}- let mut facts = Facts::merge(incoming.iter().map(|(_, facts)| facts.clone()));+ let mut facts = Facts::merge(zone, incoming.iter_mut().map(|(_, facts)| facts.share()));for phi in phis {let inputs = graph.node(*phi)@@ -252,18 +484,20 @@ fn facts_at_entry(});facts.set_phi_kinds(graph, *phi, inputs);}+ incoming.clear();Some(facts)}-/// Applies the nodes of `block` to `facts`, recording decisions, and returns-/// the facts flowing along each of its outgoing edges.-fn visit_block(+/// Applies the nodes of `block` to `facts`, recording decisions, and adds+/// the facts flowing along each of its outgoing edges to `edges`.+fn visit_block<'f>(graph: &mut Graph,constants: &mut Constants,block: BlockId,- mut facts: Facts,+ mut facts: Facts<'f>,decisions: &mut Decisions,-) -> Vec<(BlockId, Facts)> {+ edges: &mut Edges<'f>,+) {// NB: A phi makes another value of the objects it merges, which anything// may see.for phi in &graph.block(block).phis {@@ -290,109 +524,134 @@ fn visit_block(if let Some(holds) = facts.decides(graph, value, condition) {let target = if holds { if_true } else { if_false };decisions.controls.push((control, NewControl::Jump { target }));- return vec![(target, facts)];+ edges.push((target, facts));+ return;}- let mut passed = facts.clone();+ let mut passed = facts.share();passed.forget_refinement(value);passed.set_passed(value, condition);facts.set_failed(value, condition);- return vec![(if_true, passed), (if_false, facts)];+ edges.push((if_true, passed));+ edges.push((if_false, facts));+ return;}// A branch on values alone goes the way a branch on the same values// went before.- if let Op::Branch {- condition,- if_true,- if_false,- } = graph.node(control).op- {- let inputs = graph- .node(control)- .inputs- .iter()- .map(|input| decisions.value(graph, *input))- .collect::<InlineVec<NodeId, 2>>();- // NB: A value of a known kind is no empty value (like a binding that- // is initialized, which a store of it checks).- if let BranchCondition::TaggedEquals { equal } = condition- && graph.constant_value(inputs[1]) == Some(value::EMPTY)- && facts.value_kind(inputs[0]).is_some()- {- let target = if equal { if_false } else { if_true };- decisions.controls.push((control, NewControl::Jump { target }));- return vec![(target, facts)];- }- if let Some(key) = BranchKey::of(graph, condition, &inputs) {- if let Some(holds) = facts.branch_outcome(&key) {- let target = if holds { if_true } else { if_false };- decisions.controls.push((control, NewControl::Jump { target }));- return vec![(target, facts)];- }- let mut passed = facts.clone();- passed.set_branch_outcome(key, true);- facts.set_branch_outcome(key, false);- // Strings that are the empty value where only the slow path makes- // them are strings where they are not.- if let BranchCondition::TaggedEquals { equal } = condition- && graph.constant_value(inputs[1]) == Some(value::EMPTY)- && matches!(- graph.node(inputs[0]).op,- Op::ConcatenateStrings { .. } | Op::IntegerToString- )- {- let not_empty = if equal { &mut facts } else { &mut passed };- not_empty.set_value_kind(inputs[0], ValueKind::String);- }- return vec![(if_true, passed), (if_false, facts)];- }+ if let Op::Branch { .. } = graph.node(control).op {+ let mut inputs = decisions.inputs.take();+ inputs.clear();+ inputs.extend(+ graph+ .node(control)+ .inputs+ .iter()+ .map(|input| decisions.value(graph, *input)),+ );+ let undecided = visit_value_branch(graph, control, &inputs, facts, decisions, edges);+ decisions.inputs = inputs;+ let Some(undecided) = undecided else {+ return;+ };+ facts = undecided;}let Op::ShapeSwitch { shapes, targets } = graph.node(control).op else {let successors = graph.successors(block);let Some((last, others)) = successors.split_last() else {- return Vec::new();+ return;};- let mut edges = others- .iter()- .map(|successor| (*successor, facts.clone()))- .collect::<Vec<_>>();+ for successor in others {+ edges.push((*successor, facts.share()));+ }edges.push((*last, facts));- return edges;+ return;};let object = decisions.value(graph, graph.node(control).inputs[0]);// NB: Shapes known only while the code is valid would need a check.- let known = facts- .shapes(object)- .filter(|_| !facts.is_unvalidated(object))- .map(<[ShapeCheck]>::to_vec);- let possible = shapes- .iter()- .copied()- .zip(targets.iter().copied())- .filter(|(shape, _)| known.as_ref().is_none_or(|known| known.contains(shape)))- .collect::<Vec<_>>();- let covers_known = known- .as_ref()- .is_some_and(|known| known.iter().all(|shape| possible.iter().any(|(case, _)| case == shape)));+ let known = facts.shapes(object).filter(|_| !facts.is_unvalidated(object));+ let mut possible = decisions.possible.take();+ possible.clear();+ possible.extend(+ shapes+ .iter()+ .copied()+ .zip(targets.iter().copied())+ .filter(|(shape, _)| known.is_none_or(|known| known.contains(shape))),+ );+ let covers_known =+ known.is_some_and(|known| known.iter().all(|shape| possible.iter().any(|(case, _)| case == shape)));match possible.as_slice() {[(_, target)] if covers_known => decisions.controls.push((control, NewControl::Jump { target: *target })),_ if possible.len() < shapes.len() && !possible.is_empty() => {- decisions.controls.push((- control,- NewControl::ShapeSwitch {- cases: possible.clone(),- },- ));+ let cases = possible.zone().alloc_slice_copy(&possible);+ decisions.controls.push((control, NewControl::ShapeSwitch { cases }));}_ => {}}- possible- .iter()- .map(|(shape, target)| {- let mut case_facts = facts.clone();- case_facts.set_shapes(object, &[*shape]);- (*target, case_facts)- })- .collect()+ for (shape, target) in &possible {+ let mut case_facts = facts.share();+ case_facts.set_shapes(object, &[*shape]);+ edges.push((*target, case_facts));+ }+ decisions.possible = possible;+}++/// The edges of the branch `control` on values alone, its `inputs` as the+/// analysis knows them: it goes the way a branch on the same values went+/// before. Gives `facts` back where it is no such branch.+fn visit_value_branch<'f>(+ graph: &Graph,+ control: NodeId,+ inputs: &[NodeId],+ mut facts: Facts<'f>,+ decisions: &mut Decisions,+ edges: &mut Edges<'f>,+) -> Option<Facts<'f>> {+ let Op::Branch {+ condition,+ if_true,+ if_false,+ } = graph.node(control).op+ else {+ return Some(facts);+ };+ // NB: A value of a known kind is no empty value (like a binding that+ // is initialized, which a store of it checks).+ if let BranchCondition::TaggedEquals { equal } = condition+ && graph.constant_value(inputs[1]) == Some(value::EMPTY)+ && facts.value_kind(inputs[0]).is_some()+ {+ let target = if equal { if_false } else { if_true };+ decisions.controls.push((control, NewControl::Jump { target }));+ edges.push((target, facts));+ return None;+ }+ let Some(key) = BranchKey::of(graph, condition, inputs) else {+ return Some(facts);+ };+ if let Some(holds) = facts.branch_outcome(&key) {+ let target = if holds { if_true } else { if_false };+ decisions.controls.push((control, NewControl::Jump { target }));+ edges.push((target, facts));+ return None;+ }+ let mut passed = facts.share();+ passed.set_branch_outcome(key, true);+ facts.set_branch_outcome(key, false);+ // Strings that are the empty value where only the slow path makes+ // them are strings where they are not.+ if let BranchCondition::TaggedEquals { equal } = condition+ && graph.constant_value(inputs[1]) == Some(value::EMPTY)+ && matches!(+ graph.node(inputs[0]).op,+ Op::ConcatenateStrings { .. } | Op::IntegerToString+ )+ {+ let not_empty = if equal { &mut facts } else { &mut passed };+ not_empty.set_value_kind(inputs[0], ValueKind::String);+ }+ edges.push((if_true, passed));+ edges.push((if_false, facts));+ None}/// Whether input `index` of a node with `op` is an object whose properties@@ -416,13 +675,30 @@ fn visit_node(node_id: NodeId,facts: &mut Facts,decisions: &mut Decisions,+) {+ let mut inputs = decisions.inputs.take();+ inputs.clear();+ inputs.extend(+ graph+ .node(node_id)+ .inputs+ .iter()+ .map(|input| decisions.value(graph, *input)),+ );+ visit_node_with_inputs(graph, constants, node_id, &inputs, facts, decisions);+ decisions.inputs = inputs;+}++/// `visit_node()`, with the inputs of the node as the analysis knows them.+fn visit_node_with_inputs(+ graph: &mut Graph,+ constants: &mut Constants,+ node_id: NodeId,+ inputs: &[NodeId],+ facts: &mut Facts,+ decisions: &mut Decisions,) {let node = graph.node(node_id);- let inputs = node- .inputs- .iter()- .map(|input| decisions.value(graph, *input))- .collect::<InlineVec<_, 4>>();let input = |index: usize| inputs[index];for (index, input) in inputs.iter().enumerate() {if facts.is_unexposed(*input) && !accesses_properties(&node.op, index) {@@ -710,11 +986,7 @@ fn new_object(facts: &mut Facts, object: NodeId) {/// The code is known to be valid from here on, which what is known about/// shapes relies on.fn validate(facts: &mut Facts, stable_shapes: &[CellId], decisions: &mut Decisions) {- for shape in facts.validate(stable_shapes) {- if !decisions.stable_shapes.contains(&shape) {- decisions.stable_shapes.push(shape);- }- }+ facts.validate(stable_shapes, &mut decisions.stable_shapes);}/// A load of `location` by `node`: replaced by what the location is knowndiff --git a/Libraries/LibJS/JIT/Rust/src/passes/dce.rs b/Libraries/LibJS/JIT/Rust/src/passes/dce.rsindex 7cda94360dc..684b4b010e2 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/dce.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/dce.rs@@ -30,11 +30,11 @@ fn is_removable(op: &Op) -> bool {&& !properties.runs_code}-pub fn run(graph: &mut Graph, _work: &Zone) {+pub fn run(graph: &mut Graph, work: &Zone) {remove_dead_nodes(graph);// NB: Branches whose edges did the same are left jumping where they go,// which leaves what only they used dead.- if edit::fold_branches_to_one_target(graph) {+ if edit::fold_branches_to_one_target(graph, work) {remove_dead_nodes(graph);}}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/edit.rs b/Libraries/LibJS/JIT/Rust/src/passes/edit.rsindex ef537e15789..4a1e1a17984 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/edit.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/edit.rs@@ -7,31 +7,39 @@//! Graph edits shared by the passes: replacing values, removing nodes, and//! cleaning up the control flow graph after control nodes lost successors.-use crate::bitset::BitSet;+use crate::bitset::IndexSet;+use crate::bitset::ZoneBitSet;use crate::code::Repr;-use crate::fast_hash::HashMap;-use crate::inline_vec::InlineVec;use crate::ir::BlockId;use crate::ir::FrameState;use crate::ir::FrameStateId;use crate::ir::Graph;use crate::ir::NodeId;use crate::ir::Op;+use crate::zone_map::ZoneMap;+use ak::Zone;+use ak::ZoneVec;/// Values to replace by other values, as a pass decides them.-pub struct Replacements {- map: Vec<Option<NodeId>>,+pub struct Replacements<'w> {+ map: ZoneVec<'w, Option<NodeId>>,initial_node_count: usize,}-impl Replacements {- pub fn new(graph: &Graph) -> Self {+impl<'w> Replacements<'w> {+ /// No replacements, which keep their table in `work`.+ pub fn new(graph: &Graph, work: &'w Zone) -> Self {Self {- map: Vec::new(),+ map: ZoneVec::new_in(work),initial_node_count: graph.nodes.len(),}}+ /// Forgets all replacements. The table keeps its memory.+ pub fn clear(&mut self) {+ self.map.clear();+ }+/// Makes every use of `value` a use of `replacement` instead.pub fn replace(&mut self, value: NodeId, replacement: NodeId) {debug_assert_ne!(value, replacement);@@ -75,10 +83,10 @@ impl Replacements {/// the value it refines, once the passes no longer move or share nodes:/// `Refine` nodes go away, and checks no longer have a value, so that/// refining costs no register.-pub fn remove_refinements(graph: &mut Graph) {- let mut replacements = Replacements::new(graph);- let mut removed = BitSet::new(graph.nodes.len());- let mut checks = Vec::new();+pub fn remove_refinements(graph: &mut Graph, work: &Zone) {+ let mut replacements = Replacements::new(graph, work);+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);+ let mut checks = ZoneVec::new_in(work);for block in &graph.blocks {for node in &block.body {let data = graph.node(*node);@@ -103,7 +111,7 @@ pub fn remove_refinements(graph: &mut Graph) {/// Removes the nodes in `removed` from the blocks they are in. Nodes added/// after `removed` was made are kept.-pub fn remove_nodes(graph: &mut Graph, removed: &BitSet) {+pub fn remove_nodes(graph: &mut Graph, removed: &impl IndexSet) {let is_removed = |node: &NodeId| node.index() < removed.capacity() && removed.contains(node.index());for block in &mut graph.blocks {block.body.retain(|node| !is_removed(node));@@ -125,21 +133,24 @@ pub fn make_wrapping(graph: &mut Graph, node: NodeId) {/// The constant nodes of a graph by their bits and representation, for/// passes that need constants: `get()` and `get_typed()` add those the/// graph does not have yet.-pub struct Constants {- nodes: HashMap<(u64, Repr), NodeId>,+pub struct Constants<'w> {+ nodes: ZoneMap<'w, (u64, Repr), NodeId>,}-impl Constants {- pub fn new(graph: &Graph) -> Self {- let nodes = graph- .nodes- .iter()- .enumerate()- .filter_map(|(index, node)| match (&node.op, node.repr) {- (Op::Constant(bits), Some(repr)) => Some(((*bits, repr), NodeId::from_index(index))),- _ => None,- })- .collect();+impl<'w> Constants<'w> {+ /// The constants of `graph`, with their table in `work`.+ pub fn new(graph: &Graph, work: &'w Zone) -> Self {+ let nodes = ZoneMap::from_iter_in(+ graph+ .nodes+ .iter()+ .enumerate()+ .filter_map(|(index, node)| match (&node.op, node.repr) {+ (Op::Constant(bits), Some(repr)) => Some(((*bits, repr), NodeId::from_index(index))),+ _ => None,+ }),+ work,+ );Self { nodes }}@@ -159,12 +170,12 @@ impl Constants {/// Whether an entry reaches each block over the edges the control nodes/// have.-fn reachable_blocks(graph: &Graph) -> Vec<bool> {+fn reachable_blocks<'w>(graph: &Graph, work: &'w Zone) -> ZoneVec<'w, bool> {let block_count = graph.blocks.len();- let mut reachable = vec![false; block_count];+ let mut reachable = ZoneVec::from_elem_in(false, block_count, work);// NB: A loop header that only its back edges would reach has no// predecessors if none of them was built, but is no entry.- let mut pending = graph.entries().map(BlockId::index).collect::<Vec<_>>();+ let mut pending = ZoneVec::from_iter_in(graph.entries().map(BlockId::index), work);while let Some(block) = pending.pop() {if std::mem::replace(&mut reachable[block], true) {continue;@@ -180,43 +191,43 @@ fn reachable_blocks(graph: &Graph) -> Vec<bool> {}/// Drops the blocks no entry reaches, if there are any.-pub fn remove_unreachable_blocks(graph: &mut Graph) {- if reachable_blocks(graph).iter().any(|reachable| !reachable) {- clean_up_control_flow(graph);+pub fn remove_unreachable_blocks(graph: &mut Graph, work: &Zone) {+ if reachable_blocks(graph, work).iter().any(|reachable| !reachable) {+ clean_up_control_flow(graph, work);}}/// Brings predecessor lists and phis in line with the control nodes after/// passes changed them to branch to fewer blocks, then drops the blocks no/// entry reaches anymore and the phis left with a single distinct input.-pub fn clean_up_control_flow(graph: &mut Graph) {+pub fn clean_up_control_flow(graph: &mut Graph, work: &Zone) {let block_count = graph.blocks.len();- let reachable = reachable_blocks(graph);+ let reachable = reachable_blocks(graph, work);// Keep the predecessor entries (and their phi inputs) of reachable// blocks that still branch here, as many times as they do.- let mut remaining_edges = (0..block_count)- .map(|block| graph.successors(BlockId::from_index(block)).to_vec())- .collect::<Vec<_>>();+ let mut remaining_edges = ZoneVec::from_iter_in(+ (0..block_count).map(|block| ZoneVec::from_slice_in(&graph.successors(BlockId::from_index(block)), work)),+ work,+ );+ let mut keep = ZoneVec::new_in(work);for block in 0..block_count {if !reachable[block] {continue;}let predecessors = &graph.blocks[block].predecessors;- let keep = predecessors- .iter()- .map(|predecessor| {- if !reachable[predecessor.index()] {- return false;- }- let successors = &mut remaining_edges[predecessor.index()];- let Some(index) = successors.iter().position(|successor| successor.index() == block) else {- return false;- };- successors.swap_remove(index);- true- })- .collect::<InlineVec<bool, 4>>();+ keep.clear();+ keep.extend(predecessors.iter().map(|predecessor| {+ if !reachable[predecessor.index()] {+ return false;+ }+ let successors = &mut remaining_edges[predecessor.index()];+ let Some(index) = successors.iter().position(|successor| successor.index() == block) else {+ return false;+ };+ successors.swap_remove(index);+ true+ }));if keep.iter().all(|keep| *keep) {continue;}@@ -236,14 +247,16 @@ pub fn clean_up_control_flow(graph: &mut Graph) {}}- let order = (0..block_count)- .filter(|block| reachable[*block])- .map(BlockId::from_index)- .collect::<Vec<_>>();+ let order = ZoneVec::from_iter_in(+ (0..block_count)+ .filter(|block| reachable[*block])+ .map(BlockId::from_index),+ work,+ );if order.len() != block_count {graph.reorder_blocks(&order);}- remove_trivial_phis(graph);+ remove_trivial_phis(graph, work);}/// Makes the control node `control` jump to `target`, without inputs and@@ -258,7 +271,7 @@ pub fn make_jump(graph: &mut Graph, control: NodeId, target: BlockId) {/// Makes branches whose edges both lead to the same place, through blocks/// that only jump on, jumps: where the target's phis get the same values/// from both. Returns whether it changed any.-pub fn fold_branches_to_one_target(graph: &mut Graph) -> bool {+pub fn fold_branches_to_one_target(graph: &mut Graph, work: &Zone) -> bool {// NB: Where an edge leads, and the block it enters that from.// NB: Blocks that only jump on can make a loop, which leads nowhere.let end_of = |graph: &Graph, mut block: BlockId, mut from: BlockId| {@@ -303,7 +316,7 @@ pub fn fold_branches_to_one_target(graph: &mut Graph) -> bool {changed = true;}if changed {- clean_up_control_flow(graph);+ clean_up_control_flow(graph, work);}changed}@@ -312,17 +325,27 @@ pub fn fold_branches_to_one_target(graph: &mut Graph) -> bool {/// start of the bytecode block `block` with the values flowing into it from/// there, if `block` has a start frame state (see/// `Block::start_frame_state`).-pub fn frame_state_entering<'z>(graph: &Graph<'z>, block: BlockId, predecessor: BlockId) -> Option<FrameState<'z>> {- let (template, values) = values_entering(graph, block, predecessor)?;- Some(frame_state_with_values(graph, template, &values))+pub fn frame_state_entering<'z>(+ graph: &Graph<'z>,+ block: BlockId,+ predecessor: BlockId,+ work: &Zone,+) -> Option<FrameState<'z>> {+ let (template, values) = values_entering(graph, block, predecessor, work)?;+ Some(frame_state_with_values(graph, template, values))}/// The values of a frame state, with the frame state it is made from (see `values_entering()`).-pub type EnteringValues = (FrameStateId, Vec<(u32, NodeId)>);+pub type EnteringValues<'w> = (FrameStateId, &'w [(u32, NodeId)]);-/// The values of the frame state of `frame_state_entering()`, with the start frame state of `block` that it is made-/// from.-pub fn values_entering(graph: &Graph, block: BlockId, predecessor: BlockId) -> Option<EnteringValues> {+/// The values of the frame state of `frame_state_entering()`, in `work`, with the start frame state of `block` that it+/// is made from.+pub fn values_entering<'w>(+ graph: &Graph,+ block: BlockId,+ predecessor: BlockId,+ work: &'w Zone,+) -> Option<EnteringValues<'w>> {let data = graph.block(block);let template = data.start_frame_state?;let entry_index = data@@ -331,15 +354,21 @@ pub fn values_entering(graph: &Graph, block: BlockId, predecessor: BlockId) -> O.position(|block| *block == predecessor).expect("the predecessor enters the block");let phis = &data.phis;- let mut values = graph.frame_state(template).values.to_vec();- for (_, value) in &mut values {+ let values = &graph.frame_state(template).values;+ // NB: Values made in the block do not exist before it.+ if values+ .iter()+ .any(|(_, value)| !phis.contains(value) && data.body.contains(value))+ {+ return None;+ }+ let values = work.alloc_slice_from_iter(values.iter().map(|(slot, value)| {if phis.contains(value) {- *value = graph.node(*value).inputs[entry_index];- } else if data.body.contains(value) {- // NB: Values made in the block do not exist before it.- return None;+ (*slot, graph.node(*value).inputs[entry_index])+ } else {+ (*slot, *value)}- }+ }));Some((template, values))}@@ -365,23 +394,26 @@ pub fn frame_state_with_values<'z>(/// Moves the cold blocks after all other blocks, keeping the order of/// each, so that the code of every other block comes first and the cold/// code is out of the way.-pub fn move_cold_blocks_last(graph: &mut Graph) {+pub fn move_cold_blocks_last(graph: &mut Graph, work: &Zone) {if !graph.blocks.iter().any(|block| block.is_cold) {return;}- let (hot, cold): (Vec<_>, Vec<_>) = (0..graph.blocks.len())- .map(BlockId::from_index)- .partition(|block| !graph.block(*block).is_cold);- let order = hot.into_iter().chain(cold).collect::<Vec<_>>();+ let blocks = || (0..graph.blocks.len()).map(BlockId::from_index);+ let hot = blocks().filter(|block| !graph.block(*block).is_cold);+ let cold = blocks().filter(|block| graph.block(*block).is_cold);+ let order = ZoneVec::from_iter_in(hot.chain(cold), work);graph.reorder_blocks(&order);}/// Replaces phis whose inputs are all one value (or the phi itself) by/// that value, until none is left.-pub fn remove_trivial_phis(graph: &mut Graph) {+pub fn remove_trivial_phis(graph: &mut Graph, work: &Zone) {+ // NB: Nothing adds nodes here.+ let mut replacements = Replacements::new(graph, work);+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);loop {- let mut replacements = Replacements::new(graph);- let mut removed = BitSet::new(graph.nodes.len());+ replacements.clear();+ removed.clear();for block in &graph.blocks {for phi in &block.phis {let mut distinct = graph.nodes[phi.index()]@@ -408,13 +440,13 @@ pub fn remove_trivial_phis(graph: &mut Graph) {/// Drops the frame states no node uses anymore (directly or as the parent/// of one it uses) and renumbers the others in their order.-pub fn remove_unused_frame_states(graph: &mut Graph) {+pub fn remove_unused_frame_states(graph: &mut Graph, work: &Zone) {// NB: No pass exits to the start of blocks anymore.for block in &mut graph.blocks {block.start_frame_state = None;}let count = graph.frame_states.len();- let mut used = vec![false; count];+ let mut used = ZoneVec::from_elem_in(false, count, work);for block in &graph.blocks {for node in block.nodes() {let mut frame_state = graph.nodes[node.index()].frame_state;@@ -429,7 +461,7 @@ pub fn remove_unused_frame_states(graph: &mut Graph) {if used.iter().all(|used| *used) {return;}- let mut new_index = vec![None; count];+ let mut new_index = ZoneVec::from_elem_in(None, count, work);let mut next = 0;for (index, used) in used.iter().enumerate() {if *used {@@ -465,7 +497,7 @@ mod tests {for _ in 0..4 {graph.add(Op::Constant(0), &[], Some(Repr::Tagged), 0);}- let mut replacements = Replacements::new(&graph);+ let mut replacements = Replacements::new(&graph, crate::test_zone());assert_eq!(replacements.map.capacity(), 0);assert!(replacements.is_empty());assert_eq!(replacements.resolve(NodeId(0)), NodeId(0));diff --git a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rsindex 1a25e6be2f4..d964d8934f6 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs@@ -47,12 +47,10 @@use super::edit;use super::edit::Constants;use super::edit::Replacements;-use crate::bitset::BitSet;+use crate::bitset::ZoneBitSet;use crate::code::ExitKind;use crate::code::Repr;use crate::codegen::lowering_info::lowering_info;-use crate::fast_hash::HashMap;-use crate::fast_hash::HashSet;use crate::ir::Block;use crate::ir::BlockId;use crate::ir::FrameState;@@ -63,40 +61,43 @@ use crate::ir::Op;use crate::ir::VirtualObjectKind;use crate::ir::value;use crate::snapshot::CellId;+use crate::zone_map::ZoneMap;+use crate::zone_map::ZoneSet;use ak::Zone;+use ak::ZoneVec;/// The shape and property count each object has at some point, which/// `AddNamed` nodes change.-type Shapes = HashMap<NodeId, (CellId, u32)>;+type Shapes<'w> = ZoneMap<'w, NodeId, (CellId, u32)>;/// The analysis of one graph.-struct Analysis {+struct Analysis<'w> {/// The allocations that may be replaced.- candidates: HashSet<NodeId>,+ candidates: ZoneSet<'w, NodeId>,/// The candidates that are closures.- closures: HashSet<NodeId>,+ closures: ZoneSet<'w, NodeId>,/// For every value that is a candidate or stands for one (a candidate/// with empty values made undefined, or its cell address): the candidate.- roots: HashMap<NodeId, NodeId>,- escaped: BitSet,+ roots: ZoneMap<'w, NodeId, NodeId>,+ escaped: ZoneBitSet<'w>,/// Whether an object that does not escape is stored into another one.has_nested_objects: bool,}-impl Analysis {+impl Analysis<'_> {fn root(&self, value: NodeId) -> Option<NodeId> {self.roots.get(&value).copied()}}-fn placed_nodes(graph: &Graph) -> Vec<NodeId> {- graph.blocks.iter().flat_map(Block::nodes).collect()+fn placed_nodes<'w>(graph: &Graph, work: &'w Zone) -> ZoneVec<'w, NodeId> {+ ZoneVec::from_iter_in(graph.blocks.iter().flat_map(Block::nodes), work)}-fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {- let mut candidates = HashSet::default();- let mut closures = HashSet::default();- let mut roots = HashMap::default();+fn analyze<'w>(graph: &Graph, work: &'w Zone, placed: &[NodeId], escaping: &[NodeId]) -> Analysis<'w> {+ let mut candidates = ZoneSet::new_in(work);+ let mut closures = ZoneSet::new_in(work);+ let mut roots = ZoneMap::new_in(work);for node in placed {match graph.node(*node).op {Op::AllocateObject { .. } => {}@@ -108,7 +109,7 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {candidates.insert(*node);roots.insert(*node, *node);}- let mut escaped = BitSet::new(graph.nodes.len());+ let mut escaped = ZoneBitSet::new_in(graph.nodes.len(), work);for object in escaping {escaped.insert(object.index());}@@ -146,17 +147,21 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {// the code never allocated then, after nodes that guard against that// (see `Op::AssumeLegacyArgumentsUnread`), except where code read// them before: there, and after other nodes, they stay allocated.- let guarded = graph- .legacy_arguments_guards- .iter()- .flat_map(|(_, nodes)| nodes.iter().copied())- .collect::<HashSet<_>>();- let read_before = graph- .exit_sites- .iter()- .filter(|(_, _, kind)| *kind == ExitKind::LegacyArgumentsRead)- .map(|(executable, pc, _)| (*executable, *pc))- .collect::<HashSet<_>>();+ let guarded = ZoneSet::from_iter_in(+ graph+ .legacy_arguments_guards+ .iter()+ .flat_map(|(_, nodes)| nodes.iter().copied()),+ work,+ );+ let read_before = ZoneSet::from_iter_in(+ graph+ .exit_sites+ .iter()+ .filter(|(_, _, kind)| *kind == ExitKind::LegacyArgumentsRead)+ .map(|(executable, pc, _)| (*executable, *pc)),+ work,+ );for node in placed {let allocated_in = |frame_state: &FrameState| {!guarded.contains(node) || read_before.contains(&(frame_state.executable, frame_state.pc))@@ -168,7 +173,7 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {}}- let shapes_before = shapes_before_uses(graph, &candidates, &roots, &mut escaped);+ let shapes_before = shapes_before_uses(graph, work, &candidates, &roots, &mut escaped);// NB: Only closures escape from frame states.for node in placed.iter().filter(|_| !closures.is_empty()) {@@ -203,7 +208,7 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {}// Values stored into candidates: (value's candidate, the candidate it is stored into).- let mut stored_into = Vec::new();+ let mut stored_into = ZoneVec::new_in(work);for node in placed {let data = graph.node(*node);for (index, input) in data.inputs.iter().enumerate() {@@ -253,13 +258,13 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {}}// Loads of properties of candidates, as (candidate, offset).- let loaded = placed- .iter()- .filter_map(|node| match graph.node(*node).op {+ let loaded = ZoneVec::from_iter_in(+ placed.iter().filter_map(|node| match graph.node(*node).op {Op::LoadNamed { offset, .. } => roots.get(&graph.node(*node).inputs[0]).map(|root| (*root, offset)),_ => None,- })- .collect::<Vec<_>>();+ }),+ work,+ );// An object stored into one that escapes escapes too. So does one stored// into a property that is loaded, which makes its value another value// standing for the object.@@ -292,20 +297,34 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {/// Merges the shapes objects have at the ends of a block's predecessors:/// objects whose shapes differ between paths escape, and objects missing on/// a path are not defined after the merge.-fn merge_shapes<'a>(mut exits: impl Iterator<Item = &'a Shapes>, escaped: &mut BitSet) -> Shapes {+fn merge_shapes<'a, 'w: 'a>(+ mut exits: impl Iterator<Item = &'a Shapes<'w>> + Clone,+ escaped: &mut ZoneBitSet,+ work: &'w Zone,+) -> Shapes<'w> {let Some(first) = exits.next() else {- return Shapes::default();+ return Shapes::new_in(work);};- let mut merged = first.clone();- for exit in exits {- merged.retain(|object, shape| match exit.get(object) {- Some(other) if other == shape => true,- Some(_) => {- escaped.insert(object.index());- false+ let mut merged = Shapes::with_capacity_in(first.len(), work);+ for (object, shape) in first.iter() {+ let mut kept = true;+ for exit in exits.clone() {+ match exit.get(object) {+ Some(other) if other == shape => {}+ Some(_) => {+ escaped.insert(object.index());+ kept = false;+ break;+ }+ None => {+ kept = false;+ break;+ }}- None => false,- });+ }+ if kept {+ merged.insert(*object, *shape);+ }}merged}@@ -313,32 +332,33 @@ fn merge_shapes<'a>(mut exits: impl Iterator<Item = &'a Shapes>, escaped: &mut B/// The shape and property count each object candidate has where each node/// uses it, or its frame state refers to it, as (node, candidate). Objects/// whose shapes differ between paths joining, or around a loop, escape.-fn shapes_before_uses(+fn shapes_before_uses<'w>(graph: &Graph,- candidates: &HashSet<NodeId>,- roots: &HashMap<NodeId, NodeId>,- escaped: &mut BitSet,-) -> HashMap<(NodeId, NodeId), (CellId, u32)> {- let mut before = HashMap::default();+ work: &'w Zone,+ candidates: &ZoneSet<NodeId>,+ roots: &ZoneMap<NodeId, NodeId>,+ escaped: &mut ZoneBitSet,+) -> ZoneMap<'w, (NodeId, NodeId), (CellId, u32)> {+ let mut before = ZoneMap::new_in(work);let block_count = graph.blocks.len();- let mut entries: Vec<Shapes> = vec![Shapes::default(); block_count];- let mut exits: Vec<Option<Shapes>> = vec![None; block_count];+ let mut entries: ZoneVec<Shapes> = ZoneVec::from_iter_in((0..block_count).map(|_| Shapes::new_in(work)), work);+ let mut exits: ZoneVec<Option<Shapes>> = ZoneVec::from_iter_in((0..block_count).map(|_| None), work);for (index, block) in graph.blocks.iter().enumerate() {let forward = block.predecessors.iter().filter(|predecessor| predecessor.index() < index).filter_map(|predecessor| exits[predecessor.index()].as_ref());- let mut shapes = merge_shapes(forward, escaped);+ let mut shapes = merge_shapes(forward, escaped, work);entries[index] = shapes.clone();for node in block.nodes() {let data = graph.node(node);let referred = data.frame_state- .map(|frame_state| frame_state_values(graph, frame_state))- .unwrap_or_default();- for value in data.inputs.iter().chain(&referred) {- if let Some(root) = roots.get(value)+ .into_iter()+ .flat_map(|frame_state| frame_state_values(graph, frame_state));+ for value in data.inputs.iter().copied().chain(referred) {+ if let Some(root) = roots.get(&value)&& let Some(shape) = shapes.get(root){before.insert((node, *root), *shape);@@ -375,7 +395,7 @@ fn shapes_before_uses(let Some(exit) = exits[predecessor.index()].as_ref() else {continue;};- for (object, shape) in &entries[index] {+ for (object, shape) in entries[index].iter() {if exit.get(object).is_some_and(|other| other != shape) {escaped.insert(object.index());}@@ -386,50 +406,61 @@ fn shapes_before_uses(}/// The values the frame states in the chain `frame_state` starts refer to.-fn frame_state_values(graph: &Graph, frame_state: FrameStateId) -> Vec<NodeId> {+fn frame_state_values<'g>(graph: &'g Graph, frame_state: FrameStateId) -> impl Iterator<Item = NodeId> + 'g {graph.frame_state_chain(frame_state)- .into_iter().flat_map(|id| graph.frame_state(id).values.iter().map(|(_, value)| *value))- .collect()}/// The value of each property of each replaced object at one point.-type Properties = HashMap<(NodeId, u32), NodeId>;+type Properties<'w> = ZoneMap<'w, (NodeId, u32), NodeId>;-pub fn run(graph: &mut Graph, _work: &Zone) {- let placed = placed_nodes(graph);- let mut escaping = Vec::new();+pub fn run(graph: &mut Graph, work: &Zone, steps: &mut [Zone; 2]) {+ let [step, _] = steps;+ let placed = placed_nodes(graph, work);+ let mut escaping = ZoneVec::new_in(work);loop {- let analysis = analyze(graph, &placed, &escaping);- // NB: Only objects stored into others can be values of phis of- // properties.- if !analysis.has_nested_objects {- replace_objects(graph, &analysis).expect("objects not stored into others merge in no phi of properties");- break;- }- let mut copy = graph.clone();- match replace_objects(&mut copy, &analysis) {- Ok(()) => {- *graph = copy;- break;+ // NB: Each trial makes an analysis and a copy of the graph, which go when it ends.+ let done = step.scope(|step| {+ let analysis = analyze(graph, step, &placed, &escaping);+ // NB: Only objects stored into others can be values of phis of+ // properties.+ if !analysis.has_nested_objects {+ replace_objects(graph, &analysis, step)+ .expect("objects not stored into others merge in no phi of properties");+ return true;+ }+ // NB: A trial leaves the graph half edited where it fails, so it edits a copy, and the graph gets the+ // same edits where it works.+ let mut copy = graph.clone_in(step);+ match replace_objects(&mut copy, &analysis, step) {+ Ok(()) => {+ replace_objects(graph, &analysis, step).expect("the edits of a copy of the graph worked");+ true+ }+ Err(objects) => {+ escaping.extend_from_slice(objects);+ false+ }}- Err(objects) => escaping.extend(objects),+ });+ if done {+ break;}}- resolve_legacy_arguments_guards(graph);+ resolve_legacy_arguments_guards(graph, work);}/// Makes the `AssumeLegacyArgumentsUnread` nodes after nodes whose code may/// read objects the code never allocated through legacy `arguments` (see/// `Graph::defers_legacy_argument_objects()`) `AssumeValid` nodes, and/// removes the others.-fn resolve_legacy_arguments_guards(graph: &mut Graph) {- let mut placed = BitSet::new(graph.nodes.len());- for node in placed_nodes(graph) {+fn resolve_legacy_arguments_guards(graph: &mut Graph, work: &Zone) {+ let mut placed = ZoneBitSet::new_in(graph.nodes.len(), work);+ for node in placed_nodes(graph, work) {placed.insert(node.index());}- let mut removed = BitSet::new(graph.nodes.len());+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);for (guard, nodes) in graph.legacy_arguments_guards.take() {let needed = nodes.iter()@@ -443,17 +474,27 @@ fn resolve_legacy_arguments_guards(graph: &mut Graph) {edit::remove_nodes(graph, &removed);}+/// Lists that `virtualize_frame_state()` uses for each frame state, which it+/// empties when it is done with them.+struct Scratch<'w> {+ /// A frame state chain, innermost frame first.+ chain: ZoneVec<'w, FrameStateId>,+ /// The virtual object of each replaced object, made once for a point.+ objects: ZoneMap<'w, NodeId, NodeId>,+ /// The virtual objects whose inputs are their properties.+ filled: ZoneVec<'w, NodeId>,+ inputs: ZoneVec<'w, NodeId>,+}+/// Replaces the objects of `analysis` that do not escape. Fails with the/// replaced objects that would be the values of phis of properties where/// paths merge, which must escape instead, leaving `graph` half edited.-fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<NodeId>> {- let replaced = analysis+fn replace_objects<'w>(graph: &mut Graph, analysis: &Analysis, work: &'w Zone) -> Result<(), &'w [NodeId]> {+ if analysis.candidates.iter()- .filter(|candidate| !analysis.escaped.contains(candidate.index()))- .copied()- .collect::<Vec<_>>();- if replaced.is_empty() {+ .all(|candidate| analysis.escaped.contains(candidate.index()))+ {return Ok(());}let is_replaced = |value: NodeId| {@@ -462,54 +503,71 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nod.is_some_and(|root| !analysis.escaped.contains(root.index()))};- let mut constants = Constants::new(graph);+ let mut constants = Constants::new(graph, work);let undefined = constants.get(graph, value::UNDEFINED);- let mut replacements = Replacements::new(graph);- let mut removed = BitSet::new(graph.nodes.len());+ let mut replacements = Replacements::new(graph, work);+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);let block_count = graph.blocks.len();- let mut exit_properties: Vec<Option<Properties>> = vec![None; block_count];- let mut exit_shapes: Vec<Option<Shapes>> = vec![None; block_count];+ let mut exit_properties: ZoneVec<Option<Properties>> = ZoneVec::from_iter_in((0..block_count).map(|_| None), work);+ let mut exit_shapes: ZoneVec<Option<Shapes>> = ZoneVec::from_iter_in((0..block_count).map(|_| None), work);// Loop header phis whose inputs along back edges are filled in last:// (phi, block, property).- let mut pending_phis: Vec<(NodeId, BlockId, (NodeId, u32))> = Vec::new();+ let mut pending_phis: ZoneVec<(NodeId, BlockId, (NodeId, u32))> = ZoneVec::new_in(work);// Replaced objects that would be values of those phis.- let mut conflicts: Vec<NodeId> = Vec::new();+ let mut conflicts: ZoneVec<NodeId> = ZoneVec::new_in(work);+ let mut predecessors = ZoneVec::new_in(work);+ let mut values = ZoneVec::new_in(work);+ let mut nodes = ZoneVec::new_in(work);+ let mut scratch = Scratch {+ chain: ZoneVec::new_in(work),+ objects: ZoneMap::new_in(work),+ filled: ZoneVec::new_in(work),+ inputs: ZoneVec::new_in(work),+ };for block_index in 0..block_count {let block = BlockId::from_index(block_index);- let predecessors = graph.block(block).predecessors.to_vec();- let forward = predecessors+ predecessors.assign(&graph.block(block).predecessors);+ let mut forward = predecessors.iter().filter(|predecessor| predecessor.index() < block_index)- .copied()- .collect::<Vec<_>>();- let mut properties = Properties::default();+ .copied();+ let first = forward.next();+ let forward_count = forward.count() + usize::from(first.is_some());+ let mut properties = Properties::new_in(work);// NB: Replaced objects have the same shape on every path.- let mut shapes = forward- .first()+ let mut shapes = first.and_then(|first| exit_shapes[first.index()].clone())- .unwrap_or_default();- if let Some(first) = forward.first() {- let has_back_edges = forward.len() < predecessors.len();- let first_properties = exit_properties[first.index()].clone().unwrap_or_default();- for (key, first_value) in first_properties {- let values = predecessors- .iter()- .map(|predecessor| {- if predecessor.index() < block_index {- exit_properties[predecessor.index()]- .as_ref()- .and_then(|exit| exit.get(&key).copied())- } else {- Some(first_value)+ .unwrap_or_else(|| Shapes::new_in(work));+ if let Some(first) = first+ && let Some(first_properties) = exit_properties[first.index()].as_ref()+ {+ let has_back_edges = forward_count < predecessors.len();+ for (key, first_value) in first_properties.iter() {+ let (key, first_value) = (*key, *first_value);+ values.clear();+ let mut defined = true;+ for predecessor in &predecessors {+ let value = if predecessor.index() < block_index {+ exit_properties[predecessor.index()]+ .as_ref()+ .and_then(|exit| exit.get(&key).copied())+ } else {+ Some(first_value)+ };+ match value {+ Some(value) => values.push(value),+ None => {+ defined = false;+ break;}- })- .collect::<Option<Vec<_>>>();+ }+ }// NB: An object missing on a path is not defined there, so// nothing after the merge uses it.- let Some(values) = values else {+ if !defined {continue;- };+ }if !has_back_edges && values.iter().all(|value| *value == first_value) {properties.insert(key, first_value);continue;@@ -530,29 +588,38 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nod}}- let nodes = graph- .block(block)- .body- .iter()- .chain(&graph.block(block).control)- .copied()- .collect::<Vec<_>>();- for node in nodes {+ nodes.clear();+ nodes.extend(+ graph+ .block(block)+ .body+ .iter()+ .chain(&graph.block(block).control)+ .copied(),+ );+ for node in &nodes {+ let node = *node;let data = graph.node(node);- let (node_op, node_inputs, node_repr, node_frame_state) =- (data.op.clone(), data.inputs.to_vec(), data.repr, data.frame_state);+ let (node_op, first_input, second_input, node_repr, node_frame_state) = (+ data.op.clone(),+ data.inputs.first().copied(),+ data.inputs.get(1).copied(),+ data.repr,+ data.frame_state,+ );+ let second_input = || second_input.expect("stores have a value");if let Some(frame_state) = node_frame_state {let new_frame_state = virtualize_frame_state(graph,analysis,- &is_replaced,- &replacements,+ (&is_replaced, &replacements),(&properties, &shapes),frame_state,+ &mut scratch,);graph.nodes[node.index()].frame_state = new_frame_state.or(node_frame_state);}- let object = node_inputs.first().copied().filter(|object| is_replaced(*object));+ let object = first_input.filter(|object| is_replaced(*object));match node_op {Op::AllocateObject {shape, property_count, ..@@ -575,7 +642,7 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nodlet root = analysis.root(object.expect("checked")).expect("replaced objects have roots");- properties.insert((root, offset), replacements.resolve(node_inputs[1]));+ properties.insert((root, offset), replacements.resolve(second_input()));shapes.insert(root, (shape, property_count));removed.insert(node.index());}@@ -583,7 +650,7 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nodlet root = analysis.root(object.expect("checked")).expect("replaced objects have roots");- properties.insert((root, offset), replacements.resolve(node_inputs[1]));+ properties.insert((root, offset), replacements.resolve(second_input()));removed.insert(node.index());}Op::LoadNamed { offset, .. } if object.is_some() => {@@ -599,7 +666,7 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nod{// NB: What a removed check refined is the object itself.if node_op.refined_input().is_some() && node_repr.is_some() {- replacements.replace(node, node_inputs[0]);+ replacements.replace(node, object.expect("checked"));}removed.insert(node.index());}@@ -610,8 +677,8 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nodexit_shapes[block_index] = Some(shapes);}- for (phi, block, key) in pending_phis {- let predecessors = graph.block(block).predecessors.to_vec();+ for (phi, block, key) in pending_phis.drain_all() {+ predecessors.assign(&graph.block(block).predecessors);for (index, predecessor) in predecessors.iter().enumerate() {if predecessor.index() < block.index() {continue;@@ -633,11 +700,11 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nodif !conflicts.is_empty() {conflicts.sort_unstable();conflicts.dedup();- return Err(conflicts);+ return Err(conflicts.into_slice());}replacements.apply(graph);edit::remove_nodes(graph, &removed);- edit::remove_trivial_phis(graph);+ edit::remove_trivial_phis(graph, work);Ok(())}@@ -647,15 +714,14 @@ fn replace_objects(graph: &mut Graph, analysis: &Analysis) -> Result<(), Vec<Nodfn virtualize_frame_state(graph: &mut Graph,analysis: &Analysis,- is_replaced: &dyn Fn(NodeId) -> bool,- replacements: &Replacements,+ (is_replaced, replacements): (&dyn Fn(NodeId) -> bool, &Replacements),(properties, shapes): (&Properties, &Shapes),frame_state: FrameStateId,+ scratch: &mut Scratch,) -> Option<FrameStateId> {- let chain = graph.frame_state_chain(frame_state);- let refers_to_replaced = chain.iter().any(|id| {+ let refers_to_replaced = graph.frame_state_chain(frame_state).any(|id| {graph- .frame_state(*id)+ .frame_state(id).values.iter().any(|(_, value)| is_replaced(replacements.resolve(*value)))@@ -663,9 +729,18 @@ fn virtualize_frame_state(if !refers_to_replaced {return None;}+ let Scratch {+ chain,+ objects,+ filled,+ inputs,+ } = scratch;+ chain.clear();+ chain.extend(graph.frame_state_chain(frame_state));+ objects.clear();+ filled.clear();// The virtual object of each replaced object, made once for this point.- let mut objects: HashMap<NodeId, NodeId> = HashMap::default();- let virtual_object = |graph: &mut Graph, objects: &mut HashMap<NodeId, NodeId>, value: NodeId| -> NodeId {+ let virtual_object = |graph: &mut Graph, objects: &mut ZoneMap<NodeId, NodeId>, value: NodeId| -> NodeId {let value = replacements.resolve(value);if !is_replaced(value) {return value;@@ -674,7 +749,7 @@ fn virtualize_frame_state(if let Some(object) = objects.get(&root) {return *object;}- let (shape, _) = shapes[&root];+ let (shape, _) = *shapes.get(&root).expect("replaced objects have shapes");let kind = if analysis.closures.contains(&root) {VirtualObjectKind::Closure { sample: shape }} else {@@ -693,42 +768,39 @@ fn virtualize_frame_state(for id in chain.iter().rev() {let mut copy = graph.frame_state(*id).clone();for (_, value) in &mut copy.values {- *value = virtual_object(graph, &mut objects, *value);+ *value = virtual_object(graph, objects, *value);}copy.parent = parent;parent = Some(graph.add_frame_state(copy));}// The properties of the virtual objects, which may be virtual objects// themselves.- let mut filled = Vec::new();- while let Some((root, object)) = objects- .iter()- .map(|(root, object)| (*root, *object))- .find(|(_, object)| !filled.contains(object))- {+ loop {+ let Some((root, object)) = objects+ .iter()+ .map(|(root, object)| (*root, *object))+ .find(|(_, object)| !filled.contains(object))+ else {+ break;+ };filled.push(object);+ inputs.clear();// NB: The environments of a closure are what its allocation had.if analysis.closures.contains(&root) {- let inputs = graph- .node(root)- .inputs- .iter()- .map(|input| replacements.resolve(*input))- .collect::<Vec<_>>();- graph.nodes[object.index()].inputs.assign(&inputs);+ inputs.extend(graph.node(root).inputs.iter().map(|input| replacements.resolve(*input)));+ graph.nodes[object.index()].inputs.assign(inputs);continue;}- let (_, property_count) = shapes[&root];- let inputs = (0..property_count)- .map(|offset| {- let property = properties- .get(&(root, offset))- .copied()- .expect("replaced objects have every property");- virtual_object(graph, &mut objects, property)- })- .collect::<Vec<_>>();- graph.nodes[object.index()].inputs.assign(&inputs);+ let (_, property_count) = *shapes.get(&root).expect("replaced objects have shapes");+ for offset in 0..property_count {+ let property = properties+ .get(&(root, offset))+ .copied()+ .expect("replaced objects have every property");+ let value = virtual_object(graph, objects, property);+ inputs.push(value);+ }+ graph.nodes[object.index()].inputs.assign(inputs);}parent}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/facts.rs b/Libraries/LibJS/JIT/Rust/src/passes/facts.rsindex 6aa5379a3dd..c1f6c5119ba 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/facts.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/facts.rs@@ -33,65 +33,298 @@ use crate::ir::NodeProperties;use crate::ir::Op;use crate::ir::ShapeCheck;use crate::snapshot::CellId;-use std::collections::BTreeSet;-use std::rc::Rc;+use crate::zone_map::ZoneMap;+use ak::Zone;+use ak::ZoneVec;++/// A list of facts in a zone, which facts at several points may share: FROZEN, a list that nothing changes anymore,+/// or OWNED, a list that only one `Facts` sees and changes in place. A change of a frozen list changes a copy of it.+#[derive(Debug)]+enum Part<'w, T> {+ Frozen(&'w [T]),+ Owned(ZoneVec<'w, T>),+}++impl<'w, T: Copy> Part<'w, T> {+ fn new() -> Self {+ Part::Frozen(&[])+ }++ fn as_slice(&self) -> &[T] {+ match self {+ Part::Frozen(values) => values,+ Part::Owned(values) => values,+ }+ }++ /// The list, to change it: a copy in `zone` if it is frozen.+ fn make_mut(&mut self, zone: &'w Zone) -> &mut ZoneVec<'w, T> {+ if let Part::Frozen(values) = *self {+ *self = Part::Owned(ZoneVec::from_slice_in(values, zone));+ }+ match self {+ Part::Owned(values) => values,+ Part::Frozen(_) => unreachable!("the list was copied"),+ }+ }++ /// Freezes the list, and returns another handle of it.+ fn share(&mut self) -> Self {+ let values: &'w [T] = match core::mem::replace(self, Part::new()) {+ Part::Frozen(values) => values,+ Part::Owned(values) => values.into_slice(),+ };+ *self = Part::Frozen(values);+ Part::Frozen(values)+ }++ /// Whether both are handles of one frozen list. Owned lists are never the same as another.+ fn is_same(&self, other: &Self) -> bool {+ match (self, other) {+ (Part::Frozen(values), Part::Frozen(other)) => core::ptr::eq(*values, *other),+ _ => false,+ }+ }++ fn take(&mut self) -> Self {+ core::mem::replace(self, Part::new())+ }++ fn clear(&mut self) {+ match self {+ Part::Owned(values) => values.clear(),+ Part::Frozen(_) => *self = Part::new(),+ }+ }++ /// A copy of the list in the zone of `moved`, with `convert` applied to each value. A frozen list that was moved+ /// before is not copied again: its copy is in `moved`, so the lists that facts share stay shared.+ fn move_to<'n, U: Copy>(&self, moved: &mut MovedLists<'n, U>, convert: impl FnMut(&T) -> U) -> Part<'n, U> {+ match self {+ Part::Frozen(values) => Part::Frozen(moved.copy(values, convert)),+ Part::Owned(values) => Part::Owned(ZoneVec::from_iter_in(values.iter().map(convert), moved.zone)),+ }+ }++ /// `move_to()` of a list whose values stay as they are, which copies them in one piece.+ fn move_copied<'n>(&self, moved: &mut MovedLists<'n, T>) -> Part<'n, T> {+ match self {+ Part::Frozen(values) => Part::Frozen(moved.copy_as_is(values)),+ Part::Owned(values) => Part::Owned(ZoneVec::from_slice_in(values, moved.zone)),+ }+ }+}++/// The copies of the frozen lists of one type that a move of facts made, by the address and the length of each list+/// they copy.+struct MovedLists<'n, U> {+ zone: &'n Zone,+ copies: ZoneMap<'n, (usize, usize), &'n [U]>,+}++impl<'n, U: Copy> MovedLists<'n, U> {+ fn new_in(zone: &'n Zone) -> Self {+ Self {+ zone,+ copies: ZoneMap::new_in(zone),+ }+ }++ /// The copy of `values` in the zone, with `convert` applied to each value: the one made before, if any.+ fn copy<T>(&mut self, values: &[T], convert: impl FnMut(&T) -> U) -> &'n [U] {+ if values.is_empty() {+ return &[];+ }+ let key = (values.as_ptr() as usize, values.len());+ if let Some(copy) = self.copies.get(&key) {+ return copy;+ }+ let copy: &'n [U] = self.zone.alloc_slice_from_iter(values.iter().map(convert));+ self.copies.insert(key, copy);+ copy+ }++ /// `copy()` of values that stay as they are.+ fn copy_as_is(&mut self, values: &[U]) -> &'n [U] {+ if values.is_empty() {+ return &[];+ }+ let key = (values.as_ptr() as usize, values.len());+ if let Some(copy) = self.copies.get(&key) {+ return copy;+ }+ let copy: &'n [U] = self.zone.alloc_slice_copy(values);+ self.copies.insert(key, copy);+ copy+ }+}-/// Sparse facts in key order. Copy-on-write clones and filtering walk one-/// contiguous allocation instead of separately allocated tree nodes.-#[derive(Debug, Clone, PartialEq, Eq)]-struct FactMap<K, V>(Vec<(K, V)>);+/// What a move of facts to another zone copied so far, so that the copies of the lists that the facts share are shared+/// too (see `Facts::move_to()`).+pub(super) struct Moved<'n> {+ zone: &'n Zone,+ kinds: MovedLists<'n, (NodeId, Kinds)>,+ checked_values: MovedLists<'n, (NodeId, u64)>,+ elements: MovedLists<'n, (NodeId, ElementsKind)>,+ shapes: MovedLists<'n, (NodeId, &'n [ShapeCheck])>,+ shape_lists: MovedLists<'n, ShapeCheck>,+ nodes: MovedLists<'n, NodeId>,+ cells: MovedLists<'n, CellId>,+ contents: MovedLists<'n, (Location, NodeId)>,+ refinements: MovedLists<'n, (NodeId, NodeId)>,+ branch_outcomes: MovedLists<'n, (BranchKey, bool)>,+}-impl<K, V> Default for FactMap<K, V> {- fn default() -> Self {- Self(Vec::new())+impl<'n> Moved<'n> {+ /// Nothing moved yet, to `zone`, which also holds what this keeps.+ pub fn new_in(zone: &'n Zone) -> Self {+ Self {+ zone,+ kinds: MovedLists::new_in(zone),+ checked_values: MovedLists::new_in(zone),+ elements: MovedLists::new_in(zone),+ shapes: MovedLists::new_in(zone),+ shape_lists: MovedLists::new_in(zone),+ nodes: MovedLists::new_in(zone),+ cells: MovedLists::new_in(zone),+ contents: MovedLists::new_in(zone),+ refinements: MovedLists::new_in(zone),+ branch_outcomes: MovedLists::new_in(zone),+ }}}-impl<K: Ord, V> FactMap<K, V> {+/// Sparse facts in key order. Copies and filtering walk one contiguous list+/// instead of separately allocated tree nodes.+#[derive(Debug)]+struct FactMap<'w, K, V>(Part<'w, (K, V)>);++impl<'w, K: Ord + Copy, V: Copy> FactMap<'w, K, V> {+ fn new() -> Self {+ Self(Part::new())+ }++ fn as_slice(&self) -> &[(K, V)] {+ self.0.as_slice()+ }++ fn find(&self, key: &K) -> Result<usize, usize> {+ self.as_slice().binary_search_by(|(known, _)| known.cmp(key))+ }+fn get(&self, key: &K) -> Option<&V> {- self.0- .binary_search_by(|(known, _)| known.cmp(key))- .ok()- .map(|index| &self.0[index].1)+ self.find(key).ok().map(|index| &self.as_slice()[index].1)}fn contains_key(&self, key: &K) -> bool {self.get(key).is_some()}- fn insert(&mut self, key: K, value: V) {+ fn insert(&mut self, zone: &'w Zone, key: K, value: V) {+ let entries = self.0.make_mut(zone);// Definitions usually arrive in increasing node order.- if self.0.last().is_none_or(|(last, _)| *last < key) {- self.0.push((key, value));+ if entries.last().is_none_or(|(last, _)| *last < key) {+ entries.push((key, value));return;}- match self.0.binary_search_by(|(known, _)| known.cmp(&key)) {- Ok(index) => self.0[index].1 = value,- Err(index) => self.0.insert(index, (key, value)),+ match entries.binary_search_by(|(known, _)| known.cmp(&key)) {+ Ok(index) => entries[index].1 = value,+ Err(index) => entries.insert(index, (key, value)),}}- fn remove(&mut self, key: &K) {- if let Ok(index) = self.0.binary_search_by(|(known, _)| known.cmp(key)) {- self.0.remove(index);+ fn remove(&mut self, zone: &'w Zone, key: &K) {+ if let Ok(index) = self.find(key) {+ self.0.make_mut(zone).remove(index);}}fn keys(&self) -> impl Iterator<Item = &K> {- self.0.iter().map(|(key, _)| key)+ self.as_slice().iter().map(|(key, _)| key)+ }++ fn retain(&mut self, zone: &'w Zone, mut keep: impl FnMut(&K, &mut V) -> bool) {+ self.0.make_mut(zone).retain_mut(|(key, value)| keep(key, value));+ }++ fn is_empty(&self) -> bool {+ self.as_slice().is_empty()+ }++ fn clear(&mut self) {+ self.0.clear();+ }++ fn share(&mut self) -> Self {+ Self(self.0.share())+ }+}++impl<K: PartialEq + Copy, V: PartialEq + Copy> PartialEq for FactMap<'_, K, V> {+ fn eq(&self, other: &Self) -> bool {+ self.0.is_same(&other.0) || self.0.as_slice() == other.0.as_slice()+ }+}++/// A sparse set of facts in key order (see `FactMap`).+#[derive(Debug)]+struct FactSet<'w, K>(Part<'w, K>);++impl<'w, K: Ord + Copy> FactSet<'w, K> {+ fn new() -> Self {+ Self(Part::new())+ }++ fn as_slice(&self) -> &[K] {+ self.0.as_slice()+ }++ fn contains(&self, key: &K) -> bool {+ self.as_slice().binary_search(key).is_ok()+ }++ fn insert(&mut self, zone: &'w Zone, key: K) {+ if let Err(index) = self.as_slice().binary_search(&key) {+ self.0.make_mut(zone).insert(index, key);+ }+ }++ fn remove(&mut self, zone: &'w Zone, key: &K) {+ if let Ok(index) = self.as_slice().binary_search(key) {+ self.0.make_mut(zone).remove(index);+ }+ }++ /// The elements, in key order.+ fn iter(&self) -> impl Iterator<Item = &K> {+ self.as_slice().iter()}- fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {- self.0.retain_mut(|(key, value)| keep(key, value));+ fn retain(&mut self, zone: &'w Zone, keep: impl FnMut(&K) -> bool) {+ self.0.make_mut(zone).retain(keep);}fn is_empty(&self) -> bool {- self.0.is_empty()+ self.as_slice().is_empty()}fn clear(&mut self) {self.0.clear();}++ fn take(&mut self) -> Self {+ Self(self.0.take())+ }++ fn share(&mut self) -> Self {+ Self(self.0.share())+ }+}++impl<K: PartialEq + Copy> PartialEq for FactSet<'_, K> {+ fn eq(&self, other: &Self) -> bool {+ self.0.is_same(&other.0) || self.0.as_slice() == other.0.as_slice()+ }}/// A branch on a condition that tests nothing but the values of its inputs,@@ -293,32 +526,35 @@ impl Location {}}-/// What is known at one point of the program.-#[derive(Debug, Clone, Default, PartialEq, Eq)]-pub(super) struct Facts {+/// What is known at one point of the program. Its lists are in a work zone, and the facts at other points may share+/// them (see `share()`).+#[derive(Debug)]+pub(super) struct Facts<'w> {+ /// Where changed lists go.+ zone: &'w Zone,/// The kinds values may be (immutable), where that is not every kind.- kinds: Rc<FactMap<NodeId, Kinds>>,+ kinds: FactMap<'w, NodeId, Kinds>,/// Values known to have passed a check against a constant, with that/// constant (immutable).- checked_values: Rc<BTreeSet<(NodeId, u64)>>,+ checked_values: FactSet<'w, (NodeId, u64)>,/// Objects known to have elements of a kind (killed by writes of element/// counts, except for typed arrays, which keep their kind).- elements: Rc<FactMap<NodeId, ElementsKind>>,+ elements: FactMap<'w, NodeId, ElementsKind>,/// For objects, the shapes they may have (killed by writes of shapes,/// except for stable shapes, which are dependency facts).- shapes: Rc<FactMap<NodeId, Vec<ShapeCheck>>>,+ shapes: FactMap<'w, NodeId, &'w [ShapeCheck]>,/// Objects whose shapes are known from before other code ran, which/// still hold only if the code is still valid (see `Op::AssumeValid`).- unvalidated: Rc<BTreeSet<NodeId>>,+ unvalidated: FactSet<'w, NodeId>,/// Prototype chains known to be valid (killed by writes of shapes).- valid_prototype_chains: Rc<BTreeSet<CellId>>,+ valid_prototype_chains: FactSet<'w, CellId>,/// The known contents of locations, killed by writes of their/// locations (see `Location::locations()`).- contents: Rc<FactMap<Location, NodeId>>,+ contents: FactMap<'w, Location, NodeId>,/// Objects compiled code allocated that nothing but accesses of their/// properties has seen yet, so nothing else that runs can change their/// shapes or properties.- unexposed: Rc<BTreeSet<NodeId>>,+ unexposed: FactSet<'w, NodeId>,/// Whether the code is known to be valid (see `Op::AssumeValid`): no/// other code ran since an `AssumeValid`.code_valid: bool,@@ -326,13 +562,128 @@ pub(super) struct Facts {/// every path here, or the value itself where it is what it is known to/// be by its definition: what replaces a check that is known to pass,/// so that the nodes using it stay behind the check that passed.- refinements: Rc<FactMap<NodeId, NodeId>>,+ refinements: FactMap<'w, NodeId, NodeId>,/// Whether branches on conditions of the values they test alone (see/// `BranchKey`) held, where they went the same way on every path here.- branch_outcomes: Rc<FactMap<BranchKey, bool>>,+ branch_outcomes: FactMap<'w, BranchKey, bool>,+}++impl PartialEq for Facts<'_> {+ fn eq(&self, other: &Self) -> bool {+ let Facts {+ zone: _,+ kinds,+ checked_values,+ elements,+ shapes,+ unvalidated,+ valid_prototype_chains,+ contents,+ unexposed,+ code_valid,+ refinements,+ branch_outcomes,+ } = self;+ *kinds == other.kinds+ && *checked_values == other.checked_values+ && *elements == other.elements+ && *shapes == other.shapes+ && *unvalidated == other.unvalidated+ && *valid_prototype_chains == other.valid_prototype_chains+ && *contents == other.contents+ && *unexposed == other.unexposed+ && *code_valid == other.code_valid+ && *refinements == other.refinements+ && *branch_outcomes == other.branch_outcomes+ }}-impl Facts {+impl<'w> Facts<'w> {+ /// Knowing nothing, with the lists that change in `zone`.+ pub fn new_in(zone: &'w Zone) -> Self {+ Self {+ zone,+ kinds: FactMap::new(),+ checked_values: FactSet::new(),+ elements: FactMap::new(),+ shapes: FactMap::new(),+ unvalidated: FactSet::new(),+ valid_prototype_chains: FactSet::new(),+ contents: FactMap::new(),+ unexposed: FactSet::new(),+ code_valid: false,+ refinements: FactMap::new(),+ branch_outcomes: FactMap::new(),+ }+ }++ /// The same facts, for another point. Both share the lists they have now, which a change of either copies first.+ pub fn share(&mut self) -> Self {+ let Facts {+ zone,+ kinds,+ checked_values,+ elements,+ shapes,+ unvalidated,+ valid_prototype_chains,+ contents,+ unexposed,+ code_valid,+ refinements,+ branch_outcomes,+ } = self;+ Self {+ zone,+ kinds: kinds.share(),+ checked_values: checked_values.share(),+ elements: elements.share(),+ shapes: shapes.share(),+ unvalidated: unvalidated.share(),+ valid_prototype_chains: valid_prototype_chains.share(),+ contents: contents.share(),+ unexposed: unexposed.share(),+ code_valid: *code_valid,+ refinements: refinements.share(),+ branch_outcomes: branch_outcomes.share(),+ }+ }++ /// The same facts, in the zone of `moved`, with lists that are shared where these are.+ pub fn move_to<'n>(&self, moved: &mut Moved<'n>) -> Facts<'n> {+ let Facts {+ zone: _,+ kinds,+ checked_values,+ elements,+ shapes,+ unvalidated,+ valid_prototype_chains,+ contents,+ unexposed,+ code_valid,+ refinements,+ branch_outcomes,+ } = self;+ let shape_lists = &mut moved.shape_lists;+ Facts {+ zone: moved.zone,+ kinds: FactMap(kinds.0.move_copied(&mut moved.kinds)),+ checked_values: FactSet(checked_values.0.move_copied(&mut moved.checked_values)),+ elements: FactMap(elements.0.move_copied(&mut moved.elements)),+ shapes: FactMap(shapes.0.move_to(&mut moved.shapes, |(value, shapes)| {+ (*value, shape_lists.copy(shapes, |shape| *shape))+ })),+ unvalidated: FactSet(unvalidated.0.move_copied(&mut moved.nodes)),+ valid_prototype_chains: FactSet(valid_prototype_chains.0.move_copied(&mut moved.cells)),+ contents: FactMap(contents.0.move_copied(&mut moved.contents)),+ unexposed: FactSet(unexposed.0.move_copied(&mut moved.nodes)),+ code_valid: *code_valid,+ refinements: FactMap(refinements.0.move_copied(&mut moved.refinements)),+ branch_outcomes: FactMap(branch_outcomes.0.move_copied(&mut moved.branch_outcomes)),+ }+ }+pub fn value_kind(&self, value: NodeId) -> Option<ValueKind> {self.kinds.get(&value)?.kind()}@@ -363,9 +714,9 @@ impl Facts {return;}if narrowed == Kinds::ALL {- Rc::make_mut(&mut self.kinds).remove(&value);+ self.kinds.remove(self.zone, &value);} else {- Rc::make_mut(&mut self.kinds).insert(value, narrowed);+ self.kinds.insert(self.zone, value, narrowed);}}@@ -384,7 +735,7 @@ impl Facts {/// Records whether a branch like the one `key` names held.pub fn set_branch_outcome(&mut self, key: BranchKey, holds: bool) {if self.branch_outcome(&key) != Some(holds) {- Rc::make_mut(&mut self.branch_outcomes).insert(key, holds);+ self.branch_outcomes.insert(self.zone, key, holds);}}@@ -395,7 +746,14 @@ impl Facts {/// Records that the phi `phi` is of a kind one of its inputs is, given/// as each input with the facts where it comes from.- pub fn set_phi_kinds<'a>(&mut self, graph: &Graph, phi: NodeId, inputs: impl Iterator<Item = (&'a Facts, NodeId)>) {+ pub fn set_phi_kinds<'a>(+ &mut self,+ graph: &Graph,+ phi: NodeId,+ inputs: impl Iterator<Item = (&'a Facts<'w>, NodeId)>,+ ) where+ 'w: 'a,+ {let kinds = inputs.fold(Kinds(0), |kinds, (facts, input)| {kinds.union(facts.kinds_in(graph, input))});@@ -456,9 +814,7 @@ impl Facts {}pub fn set_checked_value(&mut self, value: NodeId, expected: u64) {- if !self.is_checked_value(value, expected) {- Rc::make_mut(&mut self.checked_values).insert((value, expected));- }+ self.checked_values.insert(self.zone, (value, expected));}pub fn elements_kind(&self, value: NodeId) -> Option<ElementsKind> {@@ -467,12 +823,12 @@ impl Facts {pub fn set_elements_kind(&mut self, value: NodeId, kind: ElementsKind) {if self.elements_kind(value) != Some(kind) {- Rc::make_mut(&mut self.elements).insert(value, kind);+ self.elements.insert(self.zone, value, kind);}}- pub fn shapes(&self, value: NodeId) -> Option<&[ShapeCheck]> {- self.shapes.get(&value).map(Vec::as_slice)+ pub fn shapes(&self, value: NodeId) -> Option<&'w [ShapeCheck]> {+ self.shapes.get(&value).copied()}/// Whether what is known about the shapes of `value` holds only if the@@ -482,22 +838,21 @@ impl Facts {}/// The code is known to be valid: what is known about shapes holds.- /// Returns the shapes from `stable_shapes` that relies on. (A merge with- /// a path that ran no other code since it checked them can bring other- /// shapes, which need nothing.)- pub fn validate(&mut self, stable_shapes: &[CellId]) -> Vec<CellId> {+ /// Adds the shapes from `stable_shapes` that relies on to `relied`, those+ /// it does not hold yet. (A merge with a path that ran no other code+ /// since it checked them can bring other shapes, which need nothing.)+ pub fn validate(&mut self, stable_shapes: &[CellId], relied: &mut ZoneVec<'_, CellId>) {if self.unvalidated.is_empty() {- return Vec::new();+ return;}- let mut shapes = Vec::new();- for value in std::mem::take(Rc::make_mut(&mut self.unvalidated)) {- for check in self.shapes.get(&value).into_iter().flatten() {- if stable_shapes.contains(&check.shape) && !shapes.contains(&check.shape) {- shapes.push(check.shape);+ let unvalidated = self.unvalidated.take();+ for value in unvalidated.iter() {+ for check in self.shapes(*value).into_iter().flatten() {+ if stable_shapes.contains(&check.shape) && !relied.contains(&check.shape) {+ relied.push(check.shape);}}}- shapes}/// Records that `value` has one of `shapes`, narrowing what was known@@ -505,16 +860,18 @@ impl Facts {pub fn set_shapes(&mut self, value: NodeId, shapes: &[ShapeCheck]) {let unvalidated = self.unvalidated.contains(&value);if unvalidated {- Rc::make_mut(&mut self.unvalidated).remove(&value);+ self.unvalidated.remove(self.zone, &value);}if self.shapes(value) == Some(shapes) {return;}- let narrowed = match self.shapes.get(&value) {- Some(known) if !unvalidated => shapes.iter().filter(|shape| known.contains(shape)).copied().collect(),- _ => shapes.to_vec(),+ let narrowed: &'w [ShapeCheck] = match self.shapes(value) {+ Some(known) if !unvalidated => self+ .zone+ .alloc_slice_from_iter(shapes.iter().filter(|shape| known.contains(shape)).copied()),+ _ => self.zone.alloc_slice_copy(shapes),};- Rc::make_mut(&mut self.shapes).insert(value, narrowed);+ self.shapes.insert(self.zone, value, narrowed);}pub fn is_prototype_chain_valid(&self, validity: CellId) -> bool {@@ -522,9 +879,7 @@ impl Facts {}pub fn set_prototype_chain_valid(&mut self, validity: CellId) {- if !self.is_prototype_chain_valid(validity) {- Rc::make_mut(&mut self.valid_prototype_chains).insert(validity);- }+ self.valid_prototype_chains.insert(self.zone, validity);}pub fn contents(&self, location: Location) -> Option<NodeId> {@@ -533,7 +888,7 @@ impl Facts {pub fn set_contents(&mut self, location: Location, value: NodeId) {if self.contents(location) != Some(value) {- Rc::make_mut(&mut self.contents).insert(location, value);+ self.contents.insert(self.zone, location, value);}}@@ -543,11 +898,12 @@ impl Facts {if self.shapes.is_empty() {return;}- match self.shapes.get(&object).cloned() {+ match self.shapes(object) {Some(known) => {- Rc::make_mut(&mut self.shapes).retain(|_, shapes| !shapes.iter().any(|shape| known.contains(shape)));+ self.shapes+ .retain(self.zone, |_, shapes| !shapes.iter().any(|shape| known.contains(shape)));}- None => Rc::make_mut(&mut self.shapes).clear(),+ None => self.shapes.clear(),}}@@ -560,8 +916,10 @@ impl Facts {{return;}- Rc::make_mut(&mut self.contents)- .retain(|location, _| !matches!(location, Location::Named { offset: known, .. } if *known == offset));+ self.contents.retain(+ self.zone,+ |location, _| !matches!(location, Location::Named { offset: known, .. } if *known == offset),+ );}/// A store to binding `index` of some environment, which may be any@@ -570,7 +928,7 @@ impl Facts {if !self.contents.keys().any(|location| matches!(location, Location::GlobalBinding { index: known, .. } | Location::Binding { index: known, .. } if *known == index)) {return;}- Rc::make_mut(&mut self.contents).retain(|location, _| match location {+ self.contents.retain(self.zone, |location, _| match location {Location::GlobalBinding { index: known, .. } | Location::Binding { index: known, .. } => *known != index,_ => true,});@@ -581,16 +939,12 @@ impl Facts {}pub fn set_unexposed(&mut self, object: NodeId) {- if !self.unexposed.contains(&object) {- Rc::make_mut(&mut self.unexposed).insert(object);- }+ self.unexposed.insert(self.zone, object);}/// Something other than accesses of its properties sees `object`.pub fn expose(&mut self, object: NodeId) {- if self.unexposed.contains(&object) {- Rc::make_mut(&mut self.unexposed).remove(&object);- }+ self.unexposed.remove(self.zone, &object);}pub fn refinement(&self, value: NodeId) -> Option<NodeId> {@@ -599,16 +953,14 @@ impl Facts {pub fn set_refinement(&mut self, value: NodeId, refinement: NodeId) {if self.refinement(value) != Some(refinement) {- Rc::make_mut(&mut self.refinements).insert(value, refinement);+ self.refinements.insert(self.zone, value, refinement);}}/// A branch establishes facts about `value`, which only the branch's/// refinement of it can stand for.pub fn forget_refinement(&mut self, value: NodeId) {- if self.refinements.contains_key(&value) {- Rc::make_mut(&mut self.refinements).remove(&value);- }+ self.refinements.remove(self.zone, &value);}pub fn is_code_valid(&self) -> bool {@@ -631,55 +983,63 @@ impl Facts {if writes.is_empty() {return;}+ let zone = self.zone;let unexposed = &self.unexposed;let killed = |location: &Location| {location.locations().intersects(writes)&& !location.object().is_some_and(|object| unexposed.contains(&object))};if self.contents.keys().any(killed) {- Rc::make_mut(&mut self.contents).retain(|location, _| !killed(location));+ self.contents.retain(zone, |location, _| !killed(location));}if writes.intersects(Locations::ELEMENT_COUNTS) && !self.elements.is_empty() {- Rc::make_mut(&mut self.elements).retain(|_, kind| matches!(kind, ElementsKind::TypedArray(_)));+ self.elements+ .retain(zone, |_, kind| matches!(kind, ElementsKind::TypedArray(_)));}if writes.intersects(Locations::SHAPES) && !self.shapes.is_empty() {- let mut kept_stable = Vec::new();- Rc::make_mut(&mut self.shapes).retain(|value, shapes| {+ let is_stable = |shapes: &[ShapeCheck]| {+ shapes+ .iter()+ .all(|check| check.dictionary_generation.is_none() && stable_shapes.contains(&check.shape))+ };+ let mut killed_any = false;+ for (value, shapes) in self.shapes.as_slice() {if unexposed.contains(value) {- return true;+ continue;}- let stable = shapes- .iter()- .all(|check| check.dictionary_generation.is_none() && stable_shapes.contains(&check.shape));- if stable {- kept_stable.push(*value);+ if is_stable(shapes) {+ self.unvalidated.insert(zone, *value);+ } else {+ killed_any = true;}- stable- });- if !kept_stable.is_empty() {- Rc::make_mut(&mut self.unvalidated).extend(kept_stable);+ }+ if killed_any {+ self.shapes+ .retain(zone, |value, shapes| unexposed.contains(value) || is_stable(shapes));}}if writes.intersects(Locations::SHAPES) {let shapes = &self.shapes;if self.unvalidated.iter().any(|value| !shapes.contains_key(value)) {- Rc::make_mut(&mut self.unvalidated).retain(|value| shapes.contains_key(value));+ self.unvalidated.retain(zone, |value| shapes.contains_key(value));}}if writes.intersects(Locations::SHAPES) && !self.valid_prototype_chains.is_empty() {- Rc::make_mut(&mut self.valid_prototype_chains).clear();+ self.valid_prototype_chains.clear();}}- /// What holds at a merge of paths where `facts` hold.- pub fn merge(mut facts: impl Iterator<Item = Facts>) -> Facts {+ /// What holds at a merge of paths where `facts` hold. Facts that know+ /// nothing, in `zone`, if there are none.+ pub fn merge(zone: &'w Zone, mut facts: impl Iterator<Item = Facts<'w>>) -> Facts<'w> {let Some(first) = facts.next() else {- return Facts::default();+ return Facts::new_in(zone);};let mut merged = first;+ let zone = merged.zone;for other in facts {- narrow_unless_shared(&mut merged.kinds, &other.kinds, |kinds| {- kinds.retain(|value, kinds| {+ narrow_unless_shared(&mut merged.kinds.0, &other.kinds.0, zone, |kinds| {+ kinds.retain_mut(|(value, kinds)| {let Some(other) = other.kinds.get(value) else {return false;};@@ -687,44 +1047,56 @@ impl Facts {true});});- narrow_unless_shared(&mut merged.checked_values, &other.checked_values, |values| {+ narrow_unless_shared(&mut merged.checked_values.0, &other.checked_values.0, zone, |values| {values.retain(|value| other.checked_values.contains(value));});- narrow_unless_shared(&mut merged.elements, &other.elements, |elements| {- elements.retain(|value, kind| other.elements.get(value) == Some(kind));+ narrow_unless_shared(&mut merged.elements.0, &other.elements.0, zone, |elements| {+ elements.retain(|(value, kind)| other.elements.get(value) == Some(kind));});narrow_unless_shared(- &mut merged.valid_prototype_chains,- &other.valid_prototype_chains,+ &mut merged.valid_prototype_chains.0,+ &other.valid_prototype_chains.0,+ zone,|chains| {chains.retain(|cell| other.valid_prototype_chains.contains(cell));},);- narrow_unless_shared(&mut merged.contents, &other.contents, |contents| {- contents.retain(|location, value| other.contents.get(location) == Some(value));+ narrow_unless_shared(&mut merged.contents.0, &other.contents.0, zone, |contents| {+ contents.retain(|(location, value)| other.contents.get(location) == Some(value));});- narrow_unless_shared(&mut merged.unexposed, &other.unexposed, |unexposed| {+ narrow_unless_shared(&mut merged.unexposed.0, &other.unexposed.0, zone, |unexposed| {unexposed.retain(|object| other.unexposed.contains(object));});- narrow_unless_shared(&mut merged.unvalidated, &other.unvalidated, |unvalidated| {- unvalidated.extend(other.unvalidated.iter().copied());- });+ if !merged.unvalidated.0.is_same(&other.unvalidated.0) {+ for value in other.unvalidated.iter() {+ merged.unvalidated.insert(zone, *value);+ }+ }merged.code_valid &= other.code_valid;- narrow_unless_shared(&mut merged.branch_outcomes, &other.branch_outcomes, |outcomes| {- outcomes.retain(|key, holds| other.branch_outcomes.get(key) == Some(holds));- });- narrow_unless_shared(&mut merged.refinements, &other.refinements, |refinements| {- refinements.retain(|key, value| other.refinements.get(key) == Some(value));+ narrow_unless_shared(+ &mut merged.branch_outcomes.0,+ &other.branch_outcomes.0,+ zone,+ |outcomes| {+ outcomes.retain(|(key, holds)| other.branch_outcomes.get(key) == Some(holds));+ },+ );+ narrow_unless_shared(&mut merged.refinements.0, &other.refinements.0, zone, |refinements| {+ refinements.retain(|(key, value)| other.refinements.get(key) == Some(value));});- narrow_unless_shared(&mut merged.shapes, &other.shapes, |shapes| {- shapes.retain(|value, shapes| {+ narrow_unless_shared(&mut merged.shapes.0, &other.shapes.0, zone, |shapes| {+ shapes.retain_mut(|(value, shapes)| {let Some(other_shapes) = other.shapes.get(value) else {return false;};- for shape in other_shapes {- if !shapes.contains(shape) {- shapes.push(*shape);+ if other_shapes.iter().any(|shape| !shapes.contains(shape)) {+ let mut united = ZoneVec::from_slice_in(shapes, zone);+ for shape in *other_shapes {+ if !united.contains(shape) {+ united.push(*shape);+ }}+ *shapes = united.into_slice();}true});@@ -732,7 +1104,7 @@ impl Facts {}let shapes = &merged.shapes;if merged.unvalidated.iter().any(|value| !shapes.contains_key(value)) {- Rc::make_mut(&mut merged.unvalidated).retain(|value| shapes.contains_key(value));+ merged.unvalidated.retain(zone, |value| shapes.contains_key(value));}merged}@@ -740,9 +1112,14 @@ impl Facts {/// Merges `other` into the facts `merged` with `merge`, unless both are the/// same facts, which then hold on both paths as they are.-fn narrow_unless_shared<T: Clone>(merged: &mut Rc<T>, other: &Rc<T>, merge: impl FnOnce(&mut T)) {- if !Rc::ptr_eq(merged, other) {- merge(Rc::make_mut(merged));+fn narrow_unless_shared<'w, T: Copy>(+ merged: &mut Part<'w, T>,+ other: &Part<'w, T>,+ zone: &'w Zone,+ merge: impl FnOnce(&mut ZoneVec<'w, T>),+) {+ if !merged.is_same(other) {+ merge(merged.make_mut(zone));}}@@ -773,23 +1150,32 @@ mod tests {Location::Named { object, offset }}+ fn facts() -> Facts<'static> {+ Facts::new_in(crate::test_zone())+ }++ /// Where the elements of a part are.+ fn storage<T: Copy>(part: &Part<'_, T>) -> *const T {+ part.as_slice().as_ptr()+ }+#[test]fn merges_intersect_knowledge_and_union_shape_sets() {let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3));- let mut left = Facts::default();+ let mut left = facts();left.set_object(a);left.set_object(b);left.set_value_kind(c, ValueKind::Int32);left.set_shapes(a, &[shape(10)]);left.set_shapes(b, &[shape(20)]);left.set_contents(named(a, 0), c);- let mut right = Facts::default();+ let mut right = facts();right.set_object(a);right.set_value_kind(c, ValueKind::Double);right.set_shapes(a, &[shape(11)]);right.set_contents(named(a, 0), c);- let merged = Facts::merge([left, right].into_iter());+ let merged = Facts::merge(crate::test_zone(), [left, right].into_iter());assert!(merged.is_object(a));assert!(!merged.is_object(b));assert_eq!(merged.value_kind(c), Some(ValueKind::Number));@@ -800,57 +1186,62 @@ mod tests {#[test]fn fact_maps_keep_order_through_updates_and_filtering() {- let mut facts = FactMap::default();+ let zone = crate::test_zone();+ let mut facts = FactMap::new();for (key, value) in [(3, 30), (1, 10), (2, 20), (3, 31), (4, 40)] {- facts.insert(key, value);+ facts.insert(zone, key, value);}- assert_eq!(facts.0, [(1, 10), (2, 20), (3, 31), (4, 40)]);- facts.remove(&2);- facts.remove(&9);- facts.retain(|key, value| {+ assert_eq!(facts.as_slice(), [(1, 10), (2, 20), (3, 31), (4, 40)]);+ facts.remove(zone, &2);+ facts.remove(zone, &9);+ facts.retain(zone, |key, value| {*value += 1;*key != 3});- assert_eq!(facts.0, [(1, 11), (4, 41)]);+ assert_eq!(facts.as_slice(), [(1, 11), (4, 41)]);assert_eq!(facts.get(&4), Some(&41));assert_eq!(facts.get(&2), None);- assert_eq!(facts.clone(), facts);+ assert_eq!(facts.share(), facts);}#[test]fn unchanged_facts_keep_shared_storage() {let value = NodeId(1);- let mut facts = Facts::default();+ let mut facts = facts();facts.set_object(value);facts.set_shapes(value, &[shape(1)]);facts.set_contents(named(value, 0), value);- let shared = facts.clone();+ let shared = facts.share();facts.set_object(value);facts.set_shapes(value, &[shape(1)]);facts.set_contents(named(value, 0), value);- assert!(Rc::ptr_eq(&facts.kinds, &shared.kinds));- assert!(Rc::ptr_eq(&facts.shapes, &shared.shapes));- assert!(Rc::ptr_eq(&facts.contents, &shared.contents));+ assert!(facts.kinds.0.is_same(&shared.kinds.0));+ assert!(facts.shapes.0.is_same(&shared.shapes.0));+ assert!(facts.contents.0.is_same(&shared.contents.0));+ // A change copies the part, which is no longer the same.+ facts.set_contents(named(value, 1), value);+ assert!(!facts.contents.0.is_same(&shared.contents.0));+ assert_eq!(shared.contents(named(value, 1)), None);}#[test]fn merging_consumes_unique_storage() {let value = NodeId(1);- let mut first = Facts::default();+ let mut first = facts();first.set_object(value);- let storage = Rc::as_ptr(&first.kinds);- let mut second = Facts::default();+ let first_storage = storage(&first.kinds.0);+ let mut second = facts();second.set_object(value);- let merged = Facts::merge([first, second].into_iter());- assert_eq!(Rc::as_ptr(&merged.kinds), storage);+ let merged = Facts::merge(crate::test_zone(), [first, second].into_iter());+ assert_eq!(storage(&merged.kinds.0), first_storage);assert!(merged.is_object(value));}#[test]fn shape_writes_remove_unvalidated_values_without_shapes() {let value = NodeId(1);- let mut facts = Facts::default();- facts.unvalidated = Rc::new([value].into_iter().collect());+ let mut facts = facts();+ facts.unvalidated.insert(crate::test_zone(), value);let write = NodeProperties {writes: Locations::SHAPES,..crate::ir::Op::Unreachable.properties()@@ -862,7 +1253,7 @@ mod tests {#[test]fn narrowing_and_killing() {let (a, b, count) = (NodeId(1), NodeId(2), NodeId(3));- let mut facts = Facts::default();+ let mut facts = facts();facts.set_shapes(a, &[shape(1), shape(2)]);facts.set_shapes(a, &[shape(2), shape(3)]);assert_eq!(facts.shapes(a), Some(&[shape(2)][..]));@@ -907,7 +1298,7 @@ mod tests {environment: CellId(7),index: 0,};- let mut facts = Facts::default();+ let mut facts = facts();facts.set_contents(binding(first, 0), value);facts.set_contents(binding(second, 1), value);facts.set_contents(global, value);@@ -939,7 +1330,7 @@ mod tests {});}let value = NodeId(1);- let mut facts = Facts::default();+ let mut facts = facts();assert_eq!(facts.decides(&graph, value, BranchCondition::Object), None);facts.set_passed(value, BranchCondition::Int32Value);assert_eq!(facts.decides(&graph, value, BranchCondition::Int32Value), Some(true));diff --git a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rsindex 54b048fcb34..fed6a7cb73e 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/gvn.rs@@ -41,8 +41,8 @@ fn is_numbered(op: &Op) -> bool {&& !op.is_control()}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Result<(), ColumnFull> {- run_with_hash(graph, dominators, |node, replacements| {+pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {+ run_with_hash(graph, dominators, work, |node, replacements| {let mut hash = FastHasher::default();discriminant(&node.op).hash(&mut hash);node.inputs.len().hash(&mut hash);@@ -56,6 +56,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Resufn run_with_hash(graph: &mut Graph,dominators: &mut Dominators,+ work: &Zone,hash: impl Fn(&Node, &Replacements) -> u64,) -> Result<(), ColumnFull> {if graph@@ -70,7 +71,7 @@ fn run_with_hash(return Ok(());}dominators.compute(graph)?;- let mut replacements = Replacements::new(graph);+ let mut replacements = Replacements::new(graph, work);let mut removed = BitSet::new(graph.nodes.len());// NB: Hash borrowed inputs instead of allocating keys. Candidates with// the same hash form a chain through `previous`; equality is checked@@ -171,7 +172,7 @@ mod tests {.body.assign(&[first, different_input, different_operation, duplicate]);graph.blocks[0].control = Some(returned);- run_with_hash(&mut graph, &mut Dominators::new(), |_, _| 0).unwrap();+ run_with_hash(&mut graph, &mut Dominators::new(), crate::test_zone(), |_, _| 0).unwrap();assert_eq!(graph.blocks[0].body, [first, different_input, different_operation]);assert_eq!(graph.node(returned).inputs, [first]);}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs b/Libraries/LibJS/JIT/Rust/src/passes/licm.rsindex 0c0ca32a8a2..807c9f2b4f9 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs@@ -145,7 +145,7 @@ fn find_loops(graph: &Graph, dominators: &Dominators) -> Vec<Loop> {loops}-pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Result<(), ColumnFull> {+pub fn run(graph: &mut Graph, dominators: &mut Dominators, work: &Zone) -> Result<(), ColumnFull> {// NB: Loops have a back edge from a later block or the block itself.let has_loops = graph.blocks.iter().enumerate().any(|(index, block)| {block@@ -161,7 +161,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Resu// NB: The phis of headers that merged their entries in a preheader// only take the value the preheader brings where the loop leaves// it as it is, which is then invariant in the loop.- edit::remove_trivial_phis(graph);+ edit::remove_trivial_phis(graph, work);dominators.compute(graph)?;}let dominators = &*dominators;@@ -239,7 +239,7 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Resucontinue;}let state = *exit_state.get_or_insert_with(|| {- let state = edit::frame_state_entering(graph, loop_.header, loop_.preheader)?;+ let state = edit::frame_state_entering(graph, loop_.header, loop_.preheader, work)?;Some(graph.add_frame_state(state))});let Some(state) = state else {diff --git a/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs b/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rsindex f7f59edf290..660747bcd40 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/loop_rotation.rs@@ -24,7 +24,7 @@ use ak::ZoneVec;use super::dominators::Dominators;use super::edit;-use crate::bitset::BitSet;+use crate::bitset::ZoneBitSet;use crate::ir::Block;use crate::ir::BlockId;use crate::ir::FrameStateId;@@ -35,7 +35,13 @@ use crate::ir::Op;/// How many nodes the blocks of a test that gets copied may have at most.const MAX_COPIED_NODES: usize = 64;-pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Result<(), ColumnFull> {+pub fn run(+ graph: &mut Graph,+ dominators: &mut Dominators,+ work: &Zone,+ steps: &mut [Zone; 2],+) -> Result<(), ColumnFull> {+ let [step, _] = steps;if graph.osr_entries.is_empty() {return Ok(());}@@ -43,31 +49,40 @@ pub fn run(graph: &mut Graph, dominators: &mut Dominators, _work: &Zone) -> Resu// NB: Each rotation makes one irreducible loop reducible; a graph has fewer such loops than blocks.for _ in 0..graph.blocks.len() {dominators.compute(graph)?;- let Some((test, region, sources)) = find_rotatable_test(graph, dominators) else {+ // NB: Each rotation makes tables as large as the graph, which go when it ends.+ let rotated_one = step.scope(|step| {+ let Some((test, region, sources)) = find_rotatable_test(graph, dominators, step) else {+ return false;+ };+ rotate(graph, test, ®ion, &sources, step);+ true+ });+ if !rotated_one {break;- };- rotate(graph, test, ®ion, &sources);+ }rotated = true;}if rotated {- lay_out_in_reverse_post_order(graph);- edit::remove_trivial_phis(graph);+ lay_out_in_reverse_post_order(graph, work);+ edit::remove_trivial_phis(graph, work);}Ok(())}/// The blocks a depth-first walk from the entries reaches each block from over a retreating edge: an edge to a block/// the walk is still in.-fn retreating_edges(graph: &Graph) -> Vec<Vec<BlockId>> {- let mut sources = vec![Vec::new(); graph.blocks.len()];- let mut state = vec![0u8; graph.blocks.len()];+fn retreating_edges<'w>(graph: &Graph, work: &'w Zone) -> ZoneVec<'w, ZoneVec<'w, BlockId>> {+ let mut sources = ZoneVec::from_iter_in((0..graph.blocks.len()).map(|_| ZoneVec::new_in(work)), work);+ let mut state = ZoneVec::from_elem_in(0u8, graph.blocks.len(), work);const ON_STACK: u8 = 1;const DONE: u8 = 2;+ let mut stack = ZoneVec::new_in(work);for entry in graph.entries() {if state[entry.index()] != 0 {continue;}- let mut stack = vec![(entry, 0usize)];+ stack.clear();+ stack.push((entry, 0usize));state[entry.index()] = ON_STACK;while let Some((block, next)) = stack.last_mut() {let block = *block;@@ -93,9 +108,14 @@ fn retreating_edges(graph: &Graph) -> Vec<Vec<BlockId>> {/// A block that a retreating edge it does not dominate leads to, with the blocks it dominates, if they can be copied/// for the paths that enter it from elsewhere, and the sources of the retreating edges to it.-fn find_rotatable_test(graph: &Graph, dominators: &Dominators) -> Option<(BlockId, BitSet, Vec<BlockId>)> {- let retreating = retreating_edges(graph);- let entries = graph.entries().collect::<Vec<_>>();+fn find_rotatable_test<'w>(+ graph: &Graph,+ dominators: &Dominators,+ work: &'w Zone,+) -> Option<(BlockId, ZoneBitSet<'w>, ZoneVec<'w, BlockId>)> {+ let mut retreating = retreating_edges(graph, work);+ let entries = ZoneVec::from_iter_in(graph.entries(), work);+ let mut region = ZoneBitSet::new_in(graph.blocks.len(), work);'blocks: for (index, sources) in retreating.iter().enumerate() {let test = BlockId::from_index(index);if sources.is_empty()@@ -104,7 +124,7 @@ fn find_rotatable_test(graph: &Graph, dominators: &Dominators) -> Option<(BlockI{continue;}- let mut region = BitSet::new(graph.blocks.len());+ region.clear();let mut node_count = 0;for (block, block_sources) in retreating.iter().enumerate() {let block_id = BlockId::from_index(block);@@ -134,26 +154,30 @@ fn find_rotatable_test(graph: &Graph, dominators: &Dominators) -> Option<(BlockIif sources.iter().any(|source| region.contains(source.index())) || !enters_from_before || leads_to_loop_header {continue;}- return Some((test, region, sources.clone()));+ return Some((test, region, retreating[index].take()));}None}/// Copies the blocks of `region`, which `test` dominates, for the predecessors of `test` that enter it from before/// the loop (all but the `sources` of retreating edges), and makes those predecessors branch to the copy of `test`.-fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]) {- let entering = graph- .block(test)- .predecessors- .iter()- .map(|predecessor| !sources.contains(predecessor))- .collect::<Vec<_>>();+fn rotate(graph: &mut Graph, test: BlockId, region: &ZoneBitSet, sources: &[BlockId], work: &Zone) {+ let entering = ZoneVec::from_iter_in(+ graph+ .block(test)+ .predecessors+ .iter()+ .map(|predecessor| !sources.contains(predecessor)),+ work,+ );+ let mut inputs = ZoneVec::new_in(work);+ let mut phis = ZoneVec::new_in(work);// The copies of the blocks, and of their nodes, with the inputs and frame states of the originals for now. The// copy of the test takes the phi inputs from the predecessors that enter it.- let mut block_copy = vec![None; graph.blocks.len()];- let mut node_copy: Vec<Option<NodeId>> = vec![None; graph.nodes.len()];- let blocks = region.iter().map(BlockId::from_index).collect::<Vec<_>>();+ let mut block_copy = ZoneVec::from_elem_in(None, graph.blocks.len(), work);+ let mut node_copy: ZoneVec<Option<NodeId>> = ZoneVec::from_elem_in(None, graph.nodes.len(), work);+ let blocks = ZoneVec::from_iter_in(region.iter().map(BlockId::from_index), work);for &block in &blocks {let data = graph.block(block);let copy = graph.add_block(Block {@@ -166,16 +190,18 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]}let copied = |block: BlockId, block_copy: &[Option<BlockId>]| block_copy[block.index()].expect("in the region");let test_copy = copied(test, &block_copy);- let phis = graph.block(test).phis.to_vec();- for phi in phis {- let inputs = graph- .node(phi)- .inputs- .iter()- .zip(&entering)- .filter(|(_, entering)| **entering)- .map(|(input, _)| *input)- .collect::<Vec<_>>();+ phis.assign(&graph.block(test).phis);+ for phi in phis.iter().copied() {+ inputs.clear();+ inputs.extend(+ graph+ .node(phi)+ .inputs+ .iter()+ .zip(&entering)+ .filter(|(_, entering)| **entering)+ .map(|(input, _)| *input),+ );node_copy[phi.index()] = Some(if inputs.iter().all(|input| *input == inputs[0]) {inputs[0]} else {@@ -185,14 +211,19 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]copy});}- let mut copies = Vec::new();+ let mut copies = ZoneVec::new_in(work);+ let mut body = ZoneVec::new_in(work);+ let mut predecessors = ZoneVec::new_in(work);for &block in &blocks {let copy = copied(block, &block_copy);let data = graph.block(block);- let phis = if block == test { Vec::new() } else { data.phis.to_vec() };- let body = data.body.to_vec();+ phis.clear();+ if block != test {+ phis.extend_from_slice(&data.phis);+ }+ body.assign(&data.body);let control = data.control;- let predecessors = data.predecessors.to_vec();+ predecessors.assign(&data.predecessors);for (node, is_phi) in phis.iter().map(|node| (*node, true))@@ -222,9 +253,13 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]// The copies use the copies of the region's values, and exit with copies of the frame states that refer to them.// Frame states that refer to none (like those of the callers of inlined calls) stay shared.- let mut frame_state_copy: Vec<Option<FrameStateId>> = vec![None; graph.frame_states.len()];+ let mut frame_state_copy: ZoneVec<Option<FrameStateId>> =+ ZoneVec::from_elem_in(None, graph.frame_states.len(), work);+ let mut chain = ZoneVec::new_in(work);+ let mut values = ZoneVec::new_in(work);let mut copy_frame_state = |graph: &mut Graph, id: FrameStateId| -> FrameStateId {- let chain = graph.frame_state_chain(id);+ chain.clear();+ chain.extend(graph.frame_state_chain(id));let mut copied_parent = None;for id in chain.iter().rev() {if let Some(copy) = frame_state_copy[id.index()] {@@ -232,17 +267,19 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]continue;}let original = graph.frame_state(*id);- let values = original- .values- .iter()- .map(|(slot, value)| (*slot, map(*value, &node_copy)))- .collect::<Vec<_>>();+ values.clear();+ values.extend(+ original+ .values+ .iter()+ .map(|(slot, value)| (*slot, map(*value, &node_copy))),+ );let parent = if copied_parent.is_some() {copied_parent} else {original.parent};- let copy = if original.values == values && original.parent == parent {+ let copy = if *original.values == *values && original.parent == parent {*id} else {let mut state = edit::frame_state_with_values(graph, *id, &values);@@ -264,7 +301,7 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]}for &block in &blocks {let copy = copied(block, &block_copy);- for successor in graph.successors(copy).iter().copied().collect::<Vec<_>>() {+ for successor in graph.successors(copy) {if let Some(successor_copy) = block_copy[successor.index()] {graph.replace_successor(copy, successor, successor_copy);}@@ -277,18 +314,10 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]// The edges of the copies out of the region bring the copies of the values the originals bring.for &block in &blocks {let copy = copied(block, &block_copy);- for successor in graph.successors(block).iter().copied().collect::<Vec<_>>() {+ for successor in graph.successors(block) {if region.contains(successor.index()) {continue;}- let positions = graph- .block(successor)- .predecessors- .iter()- .enumerate()- .filter(|(_, predecessor)| **predecessor == block)- .map(|(position, _)| position)- .collect::<Vec<_>>();// NB: A block that branches to the same block twice is its predecessor twice.let already = graph.block(successor)@@ -296,10 +325,18 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId].iter().filter(|predecessor| **predecessor == copy).count();- let position = positions[already];+ let position = graph+ .block(successor)+ .predecessors+ .iter()+ .enumerate()+ .filter(|(_, predecessor)| **predecessor == block)+ .map(|(position, _)| position)+ .nth(already)+ .expect("each edge from the block has a place among the predecessors");graph.blocks[successor.index()].predecessors.push(copy);- let phis = graph.block(successor).phis.to_vec();- for phi in phis {+ phis.assign(&graph.block(successor).phis);+ for phi in phis.iter().copied() {let input = map(graph.node(phi).inputs[position], &node_copy);graph.nodes[phi.index()].inputs.push(input);}@@ -308,9 +345,13 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]// The blocks of the loop that the test leads to are its header now, which a rotation of a loop around it must not// make the header of that loop too.+ let mut visited = ZoneBitSet::new_in(graph.blocks.len(), work);+ let mut pending = ZoneVec::new_in(work);for &block in &blocks {- for successor in graph.successors(block).iter().copied().collect::<Vec<_>>() {- if !region.contains(successor.index()) && reaches_without(graph, successor, sources, test) {+ for successor in graph.successors(block) {+ if !region.contains(successor.index())+ && reaches_without(graph, successor, sources, test, (&mut visited, &mut pending))+ {graph.blocks[successor.index()].is_loop_header = true;}}@@ -318,38 +359,37 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]graph.blocks[test.index()].is_loop_header = false;// The predecessors that entered the test enter its copy instead, and the test keeps the others.- let predecessors = graph.block(test).predecessors.to_vec();+ predecessors.assign(&graph.block(test).predecessors);for (predecessor, entering) in predecessors.iter().zip(&entering) {if *entering {graph.replace_successor(*predecessor, test, test_copy);}}- let test_copy_predecessors = predecessors- .iter()- .zip(&entering)- .filter(|(_, entering)| **entering)- .map(|(predecessor, _)| *predecessor)- .collect::<Vec<_>>();- graph.blocks[test_copy.index()]- .predecessors- .assign(&test_copy_predecessors);- let test_predecessors = predecessors- .iter()- .zip(&entering)- .filter(|(_, entering)| !**entering)- .map(|(predecessor, _)| *predecessor)- .collect::<Vec<_>>();- graph.blocks[test.index()].predecessors.assign(&test_predecessors);- let phis = graph.block(test).phis.to_vec();- for phi in phis {- let inputs = graph- .node(phi)- .inputs+ let selected = |keep: bool| {+ predecessors.iter().zip(&entering)- .filter(|(_, entering)| !**entering)- .map(|(input, _)| *input)- .collect::<Vec<_>>();+ .filter(move |(_, entering)| **entering == keep)+ .map(|(predecessor, _)| *predecessor)+ };+ let test_copy_predecessors = &mut graph.blocks[test_copy.index()].predecessors;+ test_copy_predecessors.clear();+ test_copy_predecessors.extend(selected(true));+ let test_predecessors = &mut graph.blocks[test.index()].predecessors;+ test_predecessors.clear();+ test_predecessors.extend(selected(false));+ phis.assign(&graph.block(test).phis);+ for phi in phis.iter().copied() {+ inputs.clear();+ inputs.extend(+ graph+ .node(phi)+ .inputs+ .iter()+ .zip(&entering)+ .filter(|(_, entering)| !**entering)+ .map(|(input, _)| *input),+ );graph.nodes[phi.index()].inputs.assign(&inputs);}let zone = graph.zone;@@ -368,10 +408,18 @@ fn rotate(graph: &mut Graph, test: BlockId, region: &BitSet, sources: &[BlockId]}}-/// Whether a path that does not go through `avoided` leads from `start` to one of `targets`.-fn reaches_without(graph: &Graph, start: BlockId, targets: &[BlockId], avoided: BlockId) -> bool {- let mut visited = BitSet::new(graph.blocks.len());- let mut pending = vec![start];+/// Whether a path that does not go through `avoided` leads from `start` to one of `targets`. `visited` and `pending`+/// are lists for the walk, which it empties first.+fn reaches_without(+ graph: &Graph,+ start: BlockId,+ targets: &[BlockId],+ avoided: BlockId,+ (visited, pending): (&mut ZoneBitSet, &mut ZoneVec<BlockId>),+) -> bool {+ visited.clear();+ pending.clear();+ pending.push(start);while let Some(block) = pending.pop() {if targets.contains(&block) {return true;@@ -387,17 +435,19 @@ fn reaches_without(graph: &Graph, start: BlockId, targets: &[BlockId], avoided:/// Orders the blocks so that each comes after its predecessors but those that reach it over a retreating edge, and/// marks the blocks such edges lead to as loop headers too.-fn lay_out_in_reverse_post_order(graph: &mut Graph) {- let mut post_order = Vec::with_capacity(graph.blocks.len());- let mut visited = vec![false; graph.blocks.len()];+fn lay_out_in_reverse_post_order(graph: &mut Graph, work: &Zone) {+ let mut post_order = ZoneVec::with_capacity_in(graph.blocks.len(), work);+ let mut visited = ZoneVec::from_elem_in(false, graph.blocks.len(), work);// NB: The walk starts at the on-stack replacement entries, so that block 0 comes first.- let entries = graph.entries().collect::<Vec<_>>();+ let entries = ZoneVec::from_iter_in(graph.entries(), work);+ let mut stack = ZoneVec::new_in(work);for &entry in entries.iter().rev() {if visited[entry.index()] {continue;}visited[entry.index()] = true;- let mut stack = vec![(entry, graph.successors(entry).len())];+ stack.clear();+ stack.push((entry, graph.successors(entry).len()));while let Some((block, remaining)) = stack.last_mut() {let block = *block;if *remaining == 0 {diff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rsindex 879c6fe29d5..ac287cf74a2 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs@@ -21,20 +21,16 @@ mod bounds_check_elimination;mod branch_fusion;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod branch_splitting;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod check_elimination;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod dce;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod dominators;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]pub mod edit;mod enumerated_keys;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod escape_analysis;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod exit_unboxing;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod facts;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod frame_initialization;@@ -46,9 +42,7 @@ mod interrupt_check_elimination;mod key_strings;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod licm;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod loop_rotation;-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod representation;#[allow(clippy::disallowed_types, clippy::disallowed_macros)]mod simplify;@@ -73,25 +67,57 @@ struct Pass {run: Run,}-/// How a pass is run.+/// How a pass runs. A pass that repeats a step whose work data grows with the graph keeps the data of each step in+/// the step zone, which drops it when the step ends: the work zone takes nothing back before the pass ends, so it+/// would hold the data of every step. A pass whose steps hand data on to later steps moves what is still in use from+/// one step zone to the other (see `check_elimination`).#[derive(Clone, Copy)]enum Run {Plain(fn(&mut Graph, &Zone)),/// The pass computes the dominators of the graph into the tables it gets. It fails if the graph is too large/// for them.WithDominators(fn(&mut Graph, &mut Dominators, &Zone) -> Result<(), ColumnFull>),+ /// A pass that keeps what lasts for the whole pass in the work zone, and the data of its steps in the step zones+ /// (see `Scratch::steps`).+ Steps(fn(&mut Graph, &Zone, &mut [Zone; 2])),+ StepsWithDominators(fn(&mut Graph, &mut Dominators, &Zone, &mut [Zone; 2]) -> Result<(), ColumnFull>),}+/// How many bytes of memory each step zone keeps after a pass, so that the steps of most functions take no memory from+/// the system again.+const STEP_MEMORY_KEPT: usize = 4 << 20;+impl Run {- /// Runs the pass. It keeps its own data in `work`, which holds none of it when this returns.- fn run(self, graph: &mut Graph, dominators: &mut Dominators, work: &mut Zone) -> Result<(), ColumnFull> {- work.scope(|work| match self {+ /// Runs the pass. It keeps its own data in `work` and `steps`, which hold none of it when this returns.+ fn run(+ self,+ graph: &mut Graph,+ dominators: &mut Dominators,+ work: &mut Zone,+ steps: &mut [Zone; 2],+ ) -> Result<(), ColumnFull> {+ let result = work.scope(|work| match self {Run::Plain(run) => {run(graph, work);Ok(())}Run::WithDominators(run) => run(graph, dominators, work),- })+ Run::Steps(run) => {+ run(graph, work, steps);+ Ok(())+ }+ Run::StepsWithDominators(run) => run(graph, dominators, work, steps),+ });+ if let Run::Steps(_) | Run::StepsWithDominators(_) = self {+ // NB: A pass that moves its data between the step zones leaves data in both. The memory of large steps+ // goes back to the system, so that it does not stay on top of what the stages after this one take+ // in the work zone.+ for zone in steps {+ zone.reset();+ zone.trim(STEP_MEMORY_KEPT);+ }+ }+ result}}@@ -99,11 +125,11 @@ impl Run {const PASSES: &[Pass] = &[Pass {name: "loop rotation",- run: Run::WithDominators(loop_rotation::run),+ run: Run::StepsWithDominators(loop_rotation::run),},Pass {name: "trivial phi removal",- run: Run::Plain(|graph, _| edit::remove_trivial_phis(graph)),+ run: Run::Plain(edit::remove_trivial_phis),},Pass {name: "truncation",@@ -123,7 +149,7 @@ const PASSES: &[Pass] = &[},Pass {name: "branch splitting",- run: Run::WithDominators(branch_splitting::run),+ run: Run::StepsWithDominators(branch_splitting::run),},Pass {name: "global value numbering",@@ -131,7 +157,7 @@ const PASSES: &[Pass] = &[},Pass {name: "check elimination",- run: Run::Plain(check_elimination::run),+ run: Run::Steps(check_elimination::run),},Pass {name: "simplification",@@ -163,7 +189,7 @@ const PASSES: &[Pass] = &[},Pass {name: "escape analysis",- run: Run::Plain(escape_analysis::run),+ run: Run::Steps(escape_analysis::run),},Pass {name: "dead code elimination",@@ -192,8 +218,9 @@ pub fn optimize(verify: bool,dominators: &mut Dominators,work: &mut Zone,+ steps: &mut [Zone; 2],) -> Result<(), ColumnFull> {- run_passes(graph, layout, verify, dominators, work, &mut |_, _| {})+ run_passes(graph, layout, verify, dominators, work, steps, &mut |_, _| {})}/// `optimize()`, returning the graph as text after building it and after@@ -204,9 +231,10 @@ pub fn optimize_with_dumps(verify: bool,dominators: &mut Dominators,work: &mut Zone,+ steps: &mut [Zone; 2],) -> Result<String, ColumnFull> {let mut text = String::new();- run_passes(graph, layout, verify, dominators, work, &mut |graph, after| {+ run_passes(graph, layout, verify, dominators, work, steps, &mut |graph, after| {text.push_str(&format!("=== after {after}\n"));text.push_str(&crate::ir::dump(graph, layout));})?;@@ -219,31 +247,32 @@ fn run_passes(verify: bool,dominators: &mut Dominators,work: &mut Zone,+ steps: &mut [Zone; 2],observe: &mut dyn FnMut(&Graph, &str),) -> Result<(), ColumnFull> {let verify = verify || cfg!(debug_assertions) || cfg!(test);// NB: Graph building builds the loops around OSR entries even without// a forward entry, which no entry reaches when every path out of the// inner loop ends in an exit.- edit::remove_unreachable_blocks(graph);+ work.scope(|work| edit::remove_unreachable_blocks(graph, work));check(graph, layout, verify, dominators, "graph building");observe(graph, "graph building");for pass in PASSES {- pass.run.run(graph, dominators, work)?;+ pass.run.run(graph, dominators, work, steps)?;check(graph, layout, verify, dominators, pass.name);observe(graph, pass.name);}// NB: Nodes that took different refinements of one value compute the// same once the refinements are gone, and nothing moves anymore.- edit::remove_refinements(graph);- Run::WithDominators(gvn::run).run(graph, dominators, work)?;+ work.scope(|work| edit::remove_refinements(graph, work));+ Run::WithDominators(gvn::run).run(graph, dominators, work, steps)?;// NB: Checks that merged took their frame states along, which may have been the last uses of what those refer to.- Run::Plain(dce::run).run(graph, dominators, work)?;+ Run::Plain(dce::run).run(graph, dominators, work, steps)?;check(graph, layout, verify, dominators, "refinement removal");observe(graph, "refinement removal");frame_initialization::run(graph, layout);check(graph, layout, verify, dominators, "frame initialization");- edit::remove_unused_frame_states(graph);+ work.scope(|work| edit::remove_unused_frame_states(graph, work));// NB: Only the final block order puts the cold code last; passes see// every block after its predecessors (except over back edges).// On-stack replacement entries run once per entry, so they are cold@@ -253,7 +282,7 @@ fn run_passes(for (_, block) in osr_entries {graph.blocks[block.index()].is_cold = true;}- edit::move_cold_blocks_last(graph);+ work.scope(|work| edit::move_cold_blocks_last(graph, work));check(graph, layout, verify, dominators, "cold block layout");observe(graph, "frame initialization");Ok(())diff --git a/Libraries/LibJS/JIT/Rust/src/passes/representation.rs b/Libraries/LibJS/JIT/Rust/src/passes/representation.rsindex e3ecd8e6094..9b33da447d8 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/representation.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/representation.rs@@ -22,9 +22,8 @@use super::edit;use super::edit::Constants;use super::edit::Replacements;-use crate::bitset::BitSet;+use crate::bitset::ZoneBitSet;use crate::code::Repr;-use crate::fast_hash::HashMap;use crate::ir::BlockId;use crate::ir::FrameStateId;use crate::ir::Graph;@@ -32,7 +31,9 @@ use crate::ir::Node;use crate::ir::NodeId;use crate::ir::Op;use crate::ir::value;+use crate::zone_map::ZoneMap;use ak::Zone;+use ak::ZoneVec;/// An unboxed representation phis can take.struct Unboxed {@@ -86,15 +87,15 @@ const UNBOXED: [Unboxed; 3] = [},];-pub fn run(graph: &mut Graph, _work: &Zone) {+pub fn run(graph: &mut Graph, work: &Zone) {for unboxed in &UNBOXED {- unbox_phis(graph, unboxed);+ unbox_phis(graph, unboxed, work);}}/// Whether `node` is among the phis being unboxed. Nodes added by the pass/// are not.-fn is_candidate(candidates: &BitSet, node: NodeId) -> bool {+fn is_candidate(candidates: &ZoneBitSet, node: NodeId) -> bool {node.index() < candidates.capacity() && candidates.contains(node.index())}@@ -107,7 +108,7 @@ enum UnboxedInput {Converted(NodeId),}-fn unboxed_input(graph: &Graph, unboxed: &Unboxed, input: NodeId, candidates: &BitSet) -> Option<UnboxedInput> {+fn unboxed_input(graph: &Graph, unboxed: &Unboxed, input: NodeId, candidates: &ZoneBitSet) -> Option<UnboxedInput> {let node = graph.node(input);match node.op {ref op if *op == unboxed.box_op => Some(UnboxedInput::Value(node.inputs[0])),@@ -120,7 +121,7 @@ fn unboxed_input(graph: &Graph, unboxed: &Unboxed, input: NodeId, candidates: &B}/// Marks the phis of `phis` connected to marked ones through their inputs.-fn spread_over_phis(graph: &Graph, phis: &BitSet, marked: &mut BitSet) {+fn spread_over_phis(graph: &Graph, phis: &ZoneBitSet, marked: &mut ZoneBitSet) {let mut changed = true;while changed {changed = false;@@ -144,8 +145,8 @@ fn spread_over_phis(graph: &Graph, phis: &BitSet, marked: &mut BitSet) {/// (like loop invariant values carried around loops entered at their header/// and at an on-stack replacement entry), at worst exits before the check/// would, once.-fn checked_phis(graph: &Graph, unboxed: &Unboxed, phis: &BitSet) -> BitSet {- let mut checked = BitSet::new(graph.nodes.len());+fn checked_phis<'w>(graph: &Graph, unboxed: &Unboxed, phis: &ZoneBitSet, work: &'w Zone) -> ZoneBitSet<'w> {+ let mut checked = ZoneBitSet::new_in(graph.nodes.len(), work);let Some(check) = &unboxed.check_op else {return checked;};@@ -168,12 +169,14 @@ fn checked_phis(graph: &Graph, unboxed: &Unboxed, phis: &BitSet) -> BitSet {/// block that the check never exited at before. Exits start that block over./// Only the values of `checked` phis, which the code checks elsewhere, are/// checked where they enter.-fn checkable_inputs(+fn checkable_inputs<'w>(graph: &Graph,unboxed: &Unboxed,- checked: &BitSet,-) -> HashMap<NodeId, (BlockId, Vec<Option<edit::EnteringValues>>)> {- let mut checkable = HashMap::default();+ checked: &ZoneBitSet,+ work: &'w Zone,+) -> ZoneMap<'w, NodeId, (BlockId, &'w [Option<edit::EnteringValues<'w>>])> {+ let mut checkable = ZoneMap::new_in(work);+ let mut entering = ZoneVec::new_in(work);for (index, block) in graph.blocks.iter().enumerate() {let block_id = BlockId::from_index(index);let gated = match (unboxed.check_op.as_ref(), block.start_frame_state) {@@ -187,51 +190,50 @@ fn checkable_inputs(};// OPTIMIZATION: The frame state entering the block from a predecessor is the same for every phi, and blocks of// large functions can have hundreds of phis with as many values in that frame state.- let mut entering = vec![None; block.predecessors.len()];+ entering.clear();+ entering.resize(block.predecessors.len(), None);for phi in &block.phis {- let inputs = block- .predecessors- .iter()- .zip(&graph.node(*phi).inputs)- .enumerate()- .map(|(entry, (predecessor, input))| {- let checkable = !gated- && checked.contains(phi.index())- && graph.node(*input).repr == Some(Repr::Tagged)- && graph.control(*predecessor).op == (Op::Jump { target: block_id });- checkable- .then(|| {- entering[entry]- .get_or_insert_with(|| edit::values_entering(graph, block_id, *predecessor))- .clone()- })- .flatten()- })- .collect();- checkable.insert(*phi, (block_id, inputs));+ let inputs =+ work.alloc_slice_from_iter(block.predecessors.iter().zip(&graph.node(*phi).inputs).enumerate().map(+ |(entry, (predecessor, input))| {+ let checkable = !gated+ && checked.contains(phi.index())+ && graph.node(*input).repr == Some(Repr::Tagged)+ && graph.control(*predecessor).op == (Op::Jump { target: block_id });+ checkable+ .then(|| {+ *entering[entry]+ .get_or_insert_with(|| edit::values_entering(graph, block_id, *predecessor, work))+ })+ .flatten()+ },+ ));+ checkable.insert(*phi, (block_id, &*inputs));}}checkable}-fn unbox_phis(graph: &mut Graph, unboxed: &Unboxed) {- let phis = graph- .blocks- .iter()- .flat_map(|block| block.phis.iter().copied())- .filter(|phi| graph.node(*phi).repr == Some(Repr::Tagged))- .collect::<Vec<_>>();+fn unbox_phis(graph: &mut Graph, unboxed: &Unboxed, work: &Zone) {+ let phis = ZoneVec::from_iter_in(+ graph+ .blocks+ .iter()+ .flat_map(|block| block.phis.iter().copied())+ .filter(|phi| graph.node(*phi).repr == Some(Repr::Tagged)),+ work,+ );if phis.is_empty() {return;}let count = graph.nodes.len();- let mut candidates = BitSet::new(count);+ let mut candidates = ZoneBitSet::new_in(count, work);for phi in &phis {candidates.insert(phi.index());}// NB: Phis that benefit from being unboxed: those of boxed values, and// those that users unbox.- let mut benefiting = BitSet::new(count);+ let mut benefiting = ZoneBitSet::new_in(count, work);for phi in candidates.iter() {if graph.nodes[phi].inputs@@ -255,8 +257,8 @@ fn unbox_phis(graph: &mut Graph, unboxed: &Unboxed) {if benefiting.is_empty() {return;}- let checked = checked_phis(graph, unboxed, &candidates);- let checkable = checkable_inputs(graph, unboxed, &checked);+ let checked = checked_phis(graph, unboxed, &candidates, work);+ let checkable = checkable_inputs(graph, unboxed, &checked, work);// Drop phis with an input that cannot be unboxed until none is left.let mut changed = true;while changed {@@ -264,7 +266,8 @@ fn unbox_phis(graph: &mut Graph, unboxed: &Unboxed) {for phi in &phis {if candidates.contains(phi.index())&& graph.node(*phi).inputs.iter().enumerate().any(|(index, input)| {- unboxed_input(graph, unboxed, *input, &candidates).is_none() && checkable[phi].1[index].is_none()+ unboxed_input(graph, unboxed, *input, &candidates).is_none()+ && checkable.get(phi).expect("phis are checkable").1[index].is_none()}){candidates.remove(phi.index());@@ -274,7 +277,7 @@ fn unbox_phis(graph: &mut Graph, unboxed: &Unboxed) {}// Keep the phis connected to something that benefits.- let mut useful = BitSet::new(count);+ let mut useful = ZoneBitSet::new_in(count, work);for phi in benefiting.iter().filter(|phi| candidates.contains(*phi)) {useful.insert(phi);}@@ -285,41 +288,39 @@ fn unbox_phis(graph: &mut Graph, unboxed: &Unboxed) {}// Unbox the phis in place.- let mut constants = Constants::new(graph);- let mut conversions = HashMap::default();- let mut checks = HashMap::default();+ let mut constants = Constants::new(graph, work);+ let mut conversions = ZoneMap::new_in(work);+ let mut checks = ZoneMap::new_in(work);+ let mut phi_inputs = ZoneVec::new_in(work);+ let mut inputs = ZoneVec::new_in(work);for phi in candidates.iter() {let phi_id = NodeId::from_index(phi);- let (block, states) = &checkable[&phi_id];- let phi_inputs = graph.nodes[phi].inputs.to_vec();- let inputs = phi_inputs- .into_iter()- .enumerate()- .map(- |(index, input)| match unboxed_input(graph, unboxed, input, &candidates) {- Some(UnboxedInput::Value(value)) => value,- Some(UnboxedInput::Constant(bits)) => constants.get_typed(graph, bits, unboxed.repr),- Some(UnboxedInput::Converted(integer)) => match graph.constant_value(integer) {- Some(bits) => {- let number = f64::from((bits as u32).cast_signed());- constants.get_typed(graph, number.to_bits(), unboxed.repr)- }- None => *conversions- .entry(integer)- .or_insert_with(|| convert_int32(graph, integer)),- },- None => {- let predecessor = graph.block(*block).predecessors[index];- let (template, values) = states[index]- .as_ref()- .expect("candidate phis only have unboxable inputs");- *checks- .entry((predecessor, input))- .or_insert_with(|| check_at_end(graph, unboxed, predecessor, input, *template, values))+ let (block, states) = *checkable.get(&phi_id).expect("phis are checkable");+ phi_inputs.assign(&graph.nodes[phi].inputs);+ inputs.clear();+ for (index, input) in phi_inputs.iter().copied().enumerate() {+ let value = match unboxed_input(graph, unboxed, input, &candidates) {+ Some(UnboxedInput::Value(value)) => value,+ Some(UnboxedInput::Constant(bits)) => constants.get_typed(graph, bits, unboxed.repr),+ Some(UnboxedInput::Converted(integer)) => match graph.constant_value(integer) {+ Some(bits) => {+ let number = f64::from((bits as u32).cast_signed());+ constants.get_typed(graph, number.to_bits(), unboxed.repr)}+ None => *conversions+ .entry(integer)+ .or_insert_with(|| convert_int32(graph, integer)),},- )- .collect::<Vec<_>>();+ None => {+ let predecessor = graph.block(block).predecessors[index];+ let (template, values) = states[index].expect("candidate phis only have unboxable inputs");+ *checks+ .entry((predecessor, input))+ .or_insert_with(|| check_at_end(graph, unboxed, predecessor, input, template, values))+ }+ };+ inputs.push(value);+ }let node = &mut graph.nodes[phi];node.inputs.assign(&inputs);node.repr = Some(unboxed.repr);@@ -327,19 +328,22 @@ fn unbox_phis(graph: &mut Graph, unboxed: &Unboxed) {// Unboxing checks of the phis are the phis themselves; other users that// need a tagged value get one boxing per phi.- let mut replacements = Replacements::new(graph);- let mut removed = BitSet::new(graph.nodes.len());- let mut boxes = HashMap::default();+ let mut replacements = Replacements::new(graph, work);+ let mut removed = ZoneBitSet::new_in(graph.nodes.len(), work);+ let mut boxes = ZoneMap::new_in(work);+ let mut nodes = ZoneVec::new_in(work);for block in 0..graph.blocks.len() {let block_data = &graph.blocks[block];- let nodes = block_data- .phis- .iter()- .chain(&block_data.body)- .chain(&block_data.control)- .copied()- .collect::<Vec<_>>();- for user in nodes {+ nodes.clear();+ nodes.extend(+ block_data+ .phis+ .iter()+ .chain(&block_data.body)+ .chain(&block_data.control)+ .copied(),+ );+ for user in nodes.iter().copied() {let user_node = graph.node(user);if unboxed.check_op.as_ref() == Some(&user_node.op) && is_candidate(&candidates, user_node.inputs[0]) {replacements.replace(user, user_node.inputs[0]);diff --git a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rsindex b267953df53..2d2b10be20c 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs@@ -319,18 +319,18 @@ fn constant_number(graph: &Graph, node: NodeId) -> Option<f64> {}}-pub fn run(graph: &mut Graph, _work: &Zone) {- simplify(graph, true);+pub fn run(graph: &mut Graph, work: &Zone) {+ simplify(graph, true, work);}/// Simplification after check elimination, which keeps every int32 check of/// a double: check elimination may have relied on what one established, like/// the int32 that an unboxing in a branch it decided takes.-pub fn run_after_check_elimination(graph: &mut Graph, _work: &Zone) {- simplify(graph, false);+pub fn run_after_check_elimination(graph: &mut Graph, work: &Zone) {+ simplify(graph, false, work);}-fn simplify(graph: &mut Graph, dissolve_checks: bool) {+fn simplify(graph: &mut Graph, dissolve_checks: bool, work: &Zone) {let dissolvable = if dissolve_checks {dissolvable_checks(graph)} else {@@ -342,8 +342,8 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool) {.then(|| checked_double(graph, value)).flatten()};- let mut constants = Constants::new(graph);- let mut replacements = Replacements::new(graph);+ let mut constants = Constants::new(graph, work);+ let mut replacements = Replacements::new(graph, work);let mut removed = BitSet::new(graph.nodes.len());let mut changed_control_flow = false;for block in 0..graph.blocks.len() {@@ -668,7 +668,7 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool) {// still uses stays, and frame states take the doubles of the others.if dissolvable.is_empty() {if changed_control_flow {- edit::clean_up_control_flow(graph);+ edit::clean_up_control_flow(graph, work);}return;}@@ -683,7 +683,7 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool) {}}}- let mut replacements = Replacements::new(graph);+ let mut replacements = Replacements::new(graph, work);let mut removed = BitSet::new(graph.nodes.len());for check in dissolvable.iter() {let check = NodeId::from_index(check);@@ -694,6 +694,6 @@ fn simplify(graph: &mut Graph, dissolve_checks: bool) {replacements.apply(graph);edit::remove_nodes(graph, &removed);if changed_control_flow {- edit::clean_up_control_flow(graph);+ edit::clean_up_control_flow(graph, work);}}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs b/Libraries/LibJS/JIT/Rust/src/passes/tests.rsindex 139ce31180d..872e3d07371 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs@@ -490,7 +490,7 @@ fn typed_array_storage_offsets_are_reused_across_stores_but_not_calls() {let ret = node(&mut graph, Op::Return, vec![object], None);graph.blocks[0].control = Some(ret);verify(&graph).unwrap();- super::check_elimination::run(&mut graph, crate::test_zone());+ super::check_elimination::run(&mut graph, crate::test_zone(), &mut crate::test_steps());assert!(!graph.blocks[0].body.contains(&second));assert_eq!(graph.node(second_data).inputs[0], first);assert!(graph.blocks[0].body.contains(&third));@@ -594,7 +594,7 @@ fn branches_on_known_kinds_fold() {}verify(&graph).unwrap();- super::check_elimination::run(&mut graph, crate::test_zone());+ super::check_elimination::run(&mut graph, crate::test_zone(), &mut crate::test_steps());let branches = graph.blocks.iter()@@ -604,6 +604,65 @@ fn branches_on_known_kinds_fold() {assert_eq!(branches, 1, "{:?}", graph.blocks);}+/// The zones of check elimination hold about as much as the facts in use, not every copy of a list that the visits+/// of blocks made.+#[test]+fn check_elimination_keeps_the_facts_in_use() {+ // NB: Each block of the chain knows the kind of one more value, so the lists of its facts copy all those before.+ let bytes = |count: u32| {+ let mut graph = Graph::default();+ for index in 0..count {+ let predecessors = if index == 0 {+ vec![]+ } else {+ vec![BlockId(2 * index - 2)]+ };+ graph.add_block(Block {+ predecessors: graph.list(&predecessors),+ ..Block::default()+ });+ graph.add_block(Block {+ predecessors: graph.list(&[BlockId(2 * index)]),+ ..Block::default()+ });+ }+ graph.add_block(Block {+ predecessors: graph.list(&[BlockId(2 * count - 2)]),+ ..Block::default()+ });+ let mut value = NodeId(0);+ for index in 0..count {+ value = node(&mut graph, Op::LoadSlot { slot: index }, vec![], Some(Repr::Tagged));+ let branch = node(+ &mut graph,+ Op::Branch {+ condition: BranchCondition::String,+ if_true: BlockId(2 * index + 2),+ if_false: BlockId(2 * index + 1),+ },+ vec![value],+ None,+ );+ graph.blocks[2 * index as usize].body.push(value);+ graph.blocks[2 * index as usize].control = Some(branch);+ let ret = node(&mut graph, Op::Return, vec![value], None);+ graph.blocks[2 * index as usize + 1].control = Some(ret);+ }+ let ret = node(&mut graph, Op::Return, vec![value], None);+ graph.blocks[2 * count as usize].control = Some(ret);+ verify(&graph).unwrap();+ let work = crate::test_work();+ let mut steps = crate::test_steps();+ super::check_elimination::run(&mut graph, &work, &mut steps);+ work.used() + steps[0].used() + steps[1].used()+ };+ let (small, large) = (bytes(1000), bytes(4000));+ assert!(+ large < 8 * small,+ "{small} bytes for 1000 blocks, {large} bytes for 4000 blocks"+ );+}+/// A value that passed an int32 check is no empty value, so a branch on/// whether it is one (like the initialization check of a binding store)/// takes the edge where it is not.@@ -653,7 +712,7 @@ fn branches_on_whether_values_of_known_kinds_are_empty_fold() {}verify(&graph).unwrap();- super::check_elimination::run(&mut graph, crate::test_zone());+ super::check_elimination::run(&mut graph, crate::test_zone(), &mut crate::test_steps());let control = graph.blocks[0].control.unwrap();assert!(matches!(graph.node(control).op, Op::Jump { target: BlockId(1) }),@@ -715,7 +774,7 @@ fn check_elimination_keeps_checks_that_a_later_entry_reaches_blocks_before_it()graph.blocks[4].control = Some(ret);verify(&graph).unwrap();- super::check_elimination::run(&mut graph, crate::test_zone());+ super::check_elimination::run(&mut graph, crate::test_zone(), &mut crate::test_steps());verify(&graph).unwrap();assert_eq!(graph.blocks[4].body, vec![second]);}@@ -1042,7 +1101,7 @@ fn control_flow_cleanup_preserves_duplicate_edges_and_phi_input_order() {graph.blocks[1].phis.push(phi);let returned = node(&mut graph, Op::Return, vec![phi], None);graph.blocks[1].control = Some(returned);- super::edit::clean_up_control_flow(&mut graph);+ super::edit::clean_up_control_flow(&mut graph, crate::test_zone());assert_eq!(graph.blocks[1].predecessors, [BlockId(0), BlockId(0)]);assert_eq!(graph.node(phi).inputs, values[..2]);}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/truncation.rs b/Libraries/LibJS/JIT/Rust/src/passes/truncation.rsindex 3aeae2c7423..b8168bf2e93 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/truncation.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/truncation.rs@@ -135,8 +135,8 @@ fn uint32_operand(graph: &Graph, value: NodeId, float64: bool) -> Option<Uint32O/// Makes comparisons of uint32 values unsigned int32 comparisons of their/// bits.-fn compare_uint32_bits(graph: &mut Graph) {- let mut constants = Constants::new(graph);+fn compare_uint32_bits(graph: &mut Graph, work: &Zone) {+ let mut constants = Constants::new(graph, work);for block in 0..graph.blocks.len() {for index in 0..graph.blocks[block].body.len() {let node = graph.blocks[block].body[index];@@ -168,8 +168,8 @@ fn compare_uint32_bits(graph: &mut Graph) {}}-pub fn run(graph: &mut Graph, _work: &Zone) {- compare_uint32_bits(graph);+pub fn run(graph: &mut Graph, work: &Zone) {+ compare_uint32_bits(graph, work);let count = graph.nodes.len();let mut wrapping = BitSet::new(count);let mut users: Vec<Vec<(NodeId, usize)>> = vec![Vec::new(); count];diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex 6ca6df2dddf..5fd7e44124d 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -819,7 +819,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {);// A frame slot that the code may write is no home.- let mut written = graph.clone();+ let mut written = graph.clone_in(crate::test_zone());written.unwritten_slots = crate::bitset::ZoneBitSet::new_in(0, written.zone);assert!(verify(&written, ®isters, &allocation).is_err());@@ -833,7 +833,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {assert!(verify(&graph, ®isters, &broken).is_err());// A store to the slot, which nothing may do, makes it hold another value.- let mut stored = graph.clone();+ let mut stored = graph.clone_in(crate::test_zone());let undefined = stored.add(Op::Constant(value::UNDEFINED), &[], Some(Repr::Tagged), 0);let store = stored.add(Op::StoreSlot { slot: a(0).raw() }, &[undefined], None, 0);let block = stored@@ -1101,7 +1101,7 @@ fn make_cold(graph: &mut Graph, blocks: &[BlockId]) {for block in blocks {graph.blocks[block.index()].is_cold = true;}- crate::passes::edit::move_cold_blocks_last(graph);+ crate::passes::edit::move_cold_blocks_last(graph, crate::test_zone());if let Err(errors) = crate::passes::verify::verify(graph) {panic!("{errors}\n{}", crate::ir::dump(graph, &test_layout()));}@@ -1173,7 +1173,7 @@ fn random_structured_programs_with_cold_blocks_allocate_correctly() {for block in &cold {graph.blocks[block.index()].is_cold = true;}- crate::passes::edit::move_cold_blocks_last(&mut graph);+ crate::passes::edit::move_cold_blocks_last(&mut graph, crate::test_zone());if let Err(errors) = crate::passes::verify::verify(&graph) {panic!("seed {seed}: {errors}\n{}", crate::ir::dump(&graph, &layout));}@@ -1245,6 +1245,7 @@ fn float64_values_get_floating_point_registers() {true,&mut Dominators::new(),&mut crate::test_work(),+ &mut crate::test_steps(),).unwrap();let allocation = allocate_and_verify(&graph);diff --git a/Libraries/LibJS/JIT/Rust/src/scratch.rs b/Libraries/LibJS/JIT/Rust/src/scratch.rsindex ce1c9f68b21..b1479cd096e 100644--- a/Libraries/LibJS/JIT/Rust/src/scratch.rs+++ b/Libraries/LibJS/JIT/Rust/src/scratch.rs@@ -24,6 +24,13 @@ pub struct Scratch {/// Where the stages of a compile keep the data that only they use. The stage that is done leaves nothing in it/// for the next one: the driver drops the data of the builder, and of each pass, when it ends.pub(crate) work: Zone,+ /// Where a stage that repeats a step keeps the data of one step, which the step drops when it ends. A stage+ /// keeps what lasts from one step to the next in `work`. So a stage whose steps each make data as large as the+ /// graph takes the memory of one step, not of all of them. A stage whose steps hand data on to later steps+ /// keeps that data in one of the two zones; when that zone holds much more than the data still in use, the+ /// stage moves the data in use to the other zone and resets the first (see `check_elimination`). The driver+ /// empties both after each stage.+ pub(crate) steps: [Zone; 2],pub(crate) tables: Tables,}@@ -53,6 +60,7 @@ impl Scratch {Self {zone: Zone::new(ZONE_LIMIT, c"JIT graph"),work: Zone::new(ZONE_LIMIT, c"JIT work"),+ steps: [Zone::new(ZONE_LIMIT, c"JIT step"), Zone::new(ZONE_LIMIT, c"JIT step 2")],tables: Tables {artifact: ArtifactWriter::new(),sites: SiteScratch::new(),@@ -66,14 +74,16 @@ impl Scratch {/// does not take it from the system again: a thread that has no compile for a while gives it back (see/// `release_memory()`).pub(crate) fn end_compile(&mut self) {- for zone in [&mut self.zone, &mut self.work] {+ let [step, other_step] = &mut self.steps;+ for zone in [&mut self.zone, &mut self.work, step, other_step] {zone.reset();}}/// Gives the memory of the scratch back to the system. The next compile takes memory again.pub fn release_memory(&mut self) {- for zone in [&mut self.zone, &mut self.work] {+ let [step, other_step] = &mut self.steps;+ for zone in [&mut self.zone, &mut self.work, step, other_step] {zone.reset();zone.trim(0);}