Skip to content

Truly independent web browser

LibJS/JIT: Keep the bytecode analysis and the builder state in a zone

Andreas Klingd04cecff1a72
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
index 195e85a4bda..edfbb279c4b 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs
@@ -56,6 +56,7 @@ use crate::ir::NodeId;
use crate::ir::Op;
use crate::ir::value;
use crate::snapshot::Intrinsic;
+use ak::ZoneVec;
/// Whether an instruction with `opcode` may write a binding of the function's
/// environment (where a mapped arguments object's parameters live), or create
@@ -147,7 +148,7 @@ pub(super) fn uses_virtual_arguments(graph: &Graph) -> bool {
})
}
-impl GraphBuilder<'_, '_> {
+impl<'a> GraphBuilder<'a, '_> {
/// Whether `node` is the virtual arguments object.
pub(super) fn is_virtual_arguments(&self, node: NodeId) -> bool {
self.graph
@@ -225,14 +226,15 @@ impl GraphBuilder<'_, '_> {
/// The values the call of the inlined callee being built passed it, all
/// of them, as arguments of a call it inlines, and their count; `None`
/// outside inlined callees.
- pub(super) fn inlined_call_arguments(&self) -> Option<(Vec<InlineValue>, u32)> {
+ pub(super) fn inlined_call_arguments(&self) -> Option<(ZoneVec<'a, InlineValue>, u32)> {
let count = self.function.inline.as_ref()?.passed_argument_count;
- let values = (0..count)
- .map(|argument| {
+ let values = ZoneVec::from_iter_in(
+ (0..count).map(|argument| {
let node = self.inlined_call_argument(argument).expect("the call passed it");
InlineValue::Node(node)
- })
- .collect();
+ }),
+ self.work,
+ );
Some((values, count))
}
@@ -443,11 +445,15 @@ impl GraphBuilder<'_, '_> {
let in_one_block = block.is_some()
&& block == self.function.cfg.block_for_pc(append.pc)
&& block == self.function.cfg.block_for_pc(call_pc);
- let array_dies = self
- .function
- .layout
- .tracked_index(array)
- .is_some_and(|slot| !self.function.liveness.live_out(index + 2).contains(slot));
+ let array_dies = match self.function.layout.tracked_index(array) {
+ Some(slot) => {
+ let live = self.live_out(index + 2);
+ let dies = !live.contains(slot);
+ self.release_slot_set(live);
+ dies
+ }
+ None => false,
+ };
if dst != array
|| self.function.is_virtual()
|| arguments != array
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
index 0de1af97874..91905009f4a 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs
@@ -373,13 +373,14 @@ impl GraphBuilder<'_, '_> {
debug_assert_eq!(self.frame.slots, frame.slots, "cases do not change frame slots");
self.set_control(Op::Jump { target: join }, &[]);
self.graph.blocks[join.index()].predecessors.push(self.block);
- case_shapes.push(std::mem::take(&mut self.frame.fresh_shapes));
+ case_shapes.push(self.frame.fresh_shapes.take());
}
self.order.push(join);
self.block = join;
self.frame = frame;
// NB: Cases may change shapes, like additions do.
- self.frame.fresh_shapes = super::AbstractFrame::common_fresh_shapes(case_shapes.iter().map(Vec::as_slice));
+ self.frame
+ .set_common_fresh_shapes(case_shapes.iter().map(|shapes| shapes.as_slice()));
let results = results.into_iter().collect::<Option<Vec<_>>>()?;
if results.iter().all(|result| *result == results[0]) {
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs
index cabc1e8f783..0ffca2b56ff 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs
@@ -234,7 +234,7 @@ impl GraphBuilder<'_, '_> {
/// A new block after `source`, which branches to it.
pub(super) fn add_block_after(&mut self, source: BlockId) -> BlockId {
- let block = self.start_new_block(vec![source]);
+ let block = self.start_new_block(&[source]);
self.block = source;
block
}
@@ -250,7 +250,7 @@ impl GraphBuilder<'_, '_> {
/// continues. Phis of the new block take their inputs in the order of
/// `predecessors`.
pub(super) fn join_blocks(&mut self, predecessors: Vec<BlockId>) -> BlockId {
- let join = self.start_new_block(predecessors.clone());
+ let join = self.start_new_block(&predecessors);
for block in predecessors {
self.block = block;
self.set_control(Op::Jump { target: join }, &[]);
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 6faba042fdc..af61f15612b 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -35,7 +35,7 @@ use super::GraphBuilder;
use super::SlotState;
use super::arguments;
use crate::CompileFailure;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::builder::Handling;
use crate::builder::handling;
use crate::bytecode::Instruction;
@@ -63,15 +63,17 @@ use crate::snapshot::Forwarding;
use crate::snapshot::Intrinsic;
use crate::snapshot::SuperConstructTarget;
use crate::snapshot::call_feedback_flags;
+use ak::Zone;
+use ak::ZoneVec;
/// How an inlined callee was called.
#[derive(Debug, Clone)]
-pub(super) struct InlineCall {
+pub(super) struct InlineCall<'a> {
/// The caller's frame state at the call: resuming after it, with the
/// result in `dst`. Every frame state inside the callee chains to it.
pub caller_frame_state: FrameStateId,
/// The caller's abstract frame at the call.
- pub caller_frame: AbstractFrame,
+ pub caller_frame: AbstractFrame<'a>,
/// For a call of a closure of the callee's function: the closure, whose
/// environments the callee's frame has, and which its materialized
/// frames run.
@@ -87,15 +89,15 @@ pub(super) struct InlineCall {
/// For callees with legacy `arguments`: the values the call passes beyond
/// the arguments the callee's bytecode reads (see
/// `legacy_argument_values()`).
- pub untracked_arguments: Vec<NodeId>,
+ pub untracked_arguments: ZoneVec<'a, NodeId>,
/// Where returns continue, once the first one is built.
pub continuation: Option<BlockId>,
/// The values returned, one per predecessor of the continuation, with
/// what was known at each return.
- pub returns: Vec<NodeId>,
+ pub returns: ZoneVec<'a, NodeId>,
/// The shapes every return knew objects have (see
/// `AbstractFrame::fresh_shapes`), once the first return is built.
- pub return_fresh_shapes: Option<Vec<(NodeId, CellId)>>,
+ pub return_fresh_shapes: Option<ZoneVec<'a, (NodeId, CellId)>>,
/// Interpreter stack bytes of this callee's frame and those of the
/// inlined calls it is in.
pub frame_bytes: u64,
@@ -225,7 +227,7 @@ fn returns_no_object(callee: &Function<'_>) -> bool {
/// catches what super() or its arguments throw runs in the materialized
/// frame and can return while `this` is still empty, and nothing checks the
/// value such a frame returns.
-fn calls_super_once_before_returning(callee: &Function<'_>) -> bool {
+fn calls_super_once_before_returning(callee: &Function<'_>, work: &Zone) -> bool {
if callee
.instructions
.iter()
@@ -233,7 +235,7 @@ fn calls_super_once_before_returning(callee: &Function<'_>) -> bool {
{
return false;
}
- let mut jump_targets = Vec::new();
+ let mut jump_targets = ZoneVec::new_in(work);
for instruction in callee.instructions {
instruction
.instruction
@@ -337,7 +339,7 @@ struct InlinableCallee<'a> {
}
/// A call to inline.
-struct InlinedCallSite {
+struct InlinedCallSite<'a> {
/// The snapshot index of the callee's executable.
index: u32,
/// The operand holding the function value checked to be the callee, or
@@ -346,7 +348,7 @@ struct InlinedCallSite {
/// ...if it is not the inlined function itself (a bound function).
expected_callee: Option<CellId>,
this: InlineValue,
- arguments: Vec<InlineValue>,
+ arguments: ZoneVec<'a, InlineValue>,
passed_argument_count: u32,
/// Whether the callee gets other arguments than the `Call` instruction's.
forwarded: bool,
@@ -365,10 +367,10 @@ struct InlinedCallSite {
callback: Option<CallbackTarget>,
}
-impl InlinedCallSite {
+impl<'a> InlinedCallSite<'a> {
/// A call of snapshot executable `index` through
- /// `Function.prototype.call` with `arguments`, whose first is `this`.
- fn through_call(index: u32, arguments: &[Operand], argument_count: u32, dst: Operand) -> Self {
+ /// `Function.prototype.call` with `arguments`, whose first is `this`, with its list in `work`.
+ fn through_call(index: u32, arguments: &[Operand], argument_count: u32, dst: Operand, work: &'a Zone) -> Self {
let this = arguments
.first()
.map_or(InlineValue::Constant(value::UNDEFINED), |this| {
@@ -377,7 +379,7 @@ impl InlinedCallSite {
Self::forwarded(
index,
this,
- arguments.iter().skip(1).copied().map(InlineValue::Operand).collect(),
+ ZoneVec::from_iter_in(arguments.iter().skip(1).copied().map(InlineValue::Operand), work),
argument_count.saturating_sub(1),
dst,
)
@@ -385,7 +387,7 @@ impl InlinedCallSite {
/// A call of snapshot executable `index` that gets other arguments than
/// the `Call` instruction's.
- fn forwarded(index: u32, this: InlineValue, arguments: Vec<InlineValue>, count: u32, dst: Operand) -> Self {
+ fn forwarded(index: u32, this: InlineValue, arguments: ZoneVec<'a, InlineValue>, count: u32, dst: Operand) -> Self {
Self {
forwarded: true,
..Self::new(index, this, arguments, count, dst)
@@ -397,7 +399,7 @@ impl InlinedCallSite {
fn new(
index: u32,
this: InlineValue,
- arguments: Vec<InlineValue>,
+ arguments: ZoneVec<'a, InlineValue>,
passed_argument_count: u32,
dst: Operand,
) -> Self {
@@ -424,21 +426,26 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
(u64::from(value::OBJECT_TAG) << 48) | (cell.0 & self.runtime.heap_region_offset_mask)
}
+ /// The values of `operands`, as arguments of an inlined call.
+ fn inline_operands(&self, operands: &[Operand]) -> ZoneVec<'a, InlineValue> {
+ ZoneVec::from_iter_in(operands.iter().copied().map(InlineValue::Operand), self.work)
+ }
+
/// A frame state of the function being walked at its current
/// instruction, resuming with `mode`, for the slots in `live`: every one
/// is listed, with its value (`frame_state_values()`) or as held by
/// frame memory. The destination of a `ResumeAfter` has the value it had
/// before the instruction, which is what the frame needs if the
/// instruction did not write it (see `ir::FrameState`).
- pub(super) fn new_frame_state(&self, live: &BitSet, mode: ResumeMode) -> FrameState<'z> {
+ pub(super) fn new_frame_state(&self, live: &ZoneBitSet<'_>, mode: ResumeMode) -> FrameState<'z> {
let values = self.frame_state_values(live);
let in_frame = self.frame_state_in_frame(live);
FrameState {
executable: self.function.index,
pc: self.function.pc,
mode,
- values: self.graph.list(&values),
- in_frame: self.graph.list(&in_frame),
+ values,
+ in_frame,
parent: self.parent_frame_state(),
passed_argument_count: None,
legacy_arguments: self.legacy_argument_slots(),
@@ -448,8 +455,9 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// The frame state after the instruction being built, which wrote
/// `dst` (`Operand::INVALID` if nothing), for the slots live after it.
pub(super) fn resume_after_frame_state(&mut self, dst: u32) -> FrameStateId {
- let live = self.function.liveness.live_out(self.function.instruction_index);
+ let live = self.live_out(self.function.instruction_index);
let frame_state = self.new_frame_state(&live, ResumeMode::ResumeAfter { dst });
+ self.release_slot_set(live);
self.graph.add_frame_state(frame_state)
}
@@ -461,7 +469,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
dst: u32,
outputs: &[usize],
) -> FrameStateId {
- let live = self.function.liveness.live_out(self.function.instruction_index);
+ let live = self.live_out(self.function.instruction_index);
let mut frame_state = self.new_frame_state(&live, ResumeMode::ResumeAfter { dst });
for slot in outputs.iter().copied().filter(|slot| live.contains(*slot)) {
let operand = self.function.layout.operand_for_tracked_index(slot).raw();
@@ -473,6 +481,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
frame_state.in_frame.insert(position, operand);
}
}
+ self.release_slot_set(live);
self.graph.add_frame_state(frame_state)
}
@@ -480,17 +489,19 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// state of the function being walked lists without a value: the
/// compiled function's slots that are in sync. Reserved registers are
/// not listed.
- fn frame_state_in_frame(&self, live: &BitSet) -> Vec<u32> {
+ fn frame_state_in_frame(&self, live: &ZoneBitSet<'_>) -> ZoneVec<'z, u32> {
if self.function.is_virtual() {
- return Vec::new();
+ return ZoneVec::new_in(self.graph.zone);
}
// NB: Exits never clear the reserved registers, which frames keep.
- live.iter()
- .filter(|slot| {
- *slot >= crate::bytecode::RESERVED_REGISTER_COUNT as usize && self.frame.slots[*slot].in_sync
- })
- .map(|slot| self.function.layout.operand_for_tracked_index(slot).raw())
- .collect()
+ ZoneVec::from_iter_in(
+ live.iter()
+ .filter(|slot| {
+ *slot >= crate::bytecode::RESERVED_REGISTER_COUNT as usize && self.frame.slots[*slot].in_sync
+ })
+ .map(|slot| self.function.layout.operand_for_tracked_index(slot).raw()),
+ self.graph.zone,
+ )
}
/// The values a frame state of the function being walked lists for the
@@ -498,7 +509,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// virtual frames, but the exception register. Inlined callees that are
/// not strict list all their passed arguments too, since their legacy
/// `arguments` shows them in the frames exits and slow paths materialize.
- fn frame_state_values(&self, live: &BitSet) -> Vec<(u32, NodeId)> {
+ fn frame_state_values(&self, live: &ZoneBitSet<'_>) -> ZoneVec<'z, (u32, NodeId)> {
let is_virtual = self.function.is_virtual();
// NB: Only the runtime writes the exception register (materialized frames start with it empty): when a
// handler of the frame catches an exception, before a leave writes the rest of the frame, which must keep
@@ -507,14 +518,15 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
.function
.layout
.tracked_index(Operand::from_raw(crate::bytecode::EXCEPTION_REGISTER));
- let mut values = live
- .iter()
- .filter(|slot| Some(*slot) != exception_register)
- .filter_map(|slot| {
- let SlotState { node, in_sync } = self.frame.slots[slot];
- (is_virtual || !in_sync).then(|| (self.function.layout.operand_for_tracked_index(slot).raw(), node))
- })
- .collect::<Vec<_>>();
+ let mut values = ZoneVec::from_iter_in(
+ live.iter()
+ .filter(|slot| Some(*slot) != exception_register)
+ .filter_map(|slot| {
+ let SlotState { node, in_sync } = self.frame.slots[slot];
+ (is_virtual || !in_sync).then(|| (self.function.layout.operand_for_tracked_index(slot).raw(), node))
+ }),
+ self.graph.zone,
+ );
for (operand, node) in self.legacy_argument_values() {
if !values.iter().any(|(slot, _)| *slot == operand) {
values.push((operand, node));
@@ -532,21 +544,22 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// all its passed arguments, which its legacy `arguments` shows. Those
/// its bytecode reads are its frame's, the others the values the call
/// passed.
- fn legacy_argument_values(&self) -> Vec<(u32, NodeId)> {
+ fn legacy_argument_values(&self) -> impl Iterator<Item = (u32, NodeId)> + '_ {
let function = &self.function;
- let Some(call) = function.inline.as_ref().filter(|_| function.has_legacy_arguments()) else {
- return Vec::new();
- };
+ let call = function.inline.as_ref().filter(|_| function.has_legacy_arguments());
let layout = function.layout;
- let mut values = Vec::new();
- for argument in 0..layout.number_of_arguments {
- let slot = (layout.registers_and_locals_count + argument) as usize;
- values.push((layout.arguments_base() + argument, self.frame.slots[slot].node));
- }
- for (argument, node) in (layout.number_of_arguments..).zip(&call.untracked_arguments) {
- values.push((layout.arguments_base() + argument, *node));
- }
- values
+ let tracked = call
+ .map_or(0..0, |_| 0..layout.number_of_arguments)
+ .map(move |argument| {
+ let slot = (layout.registers_and_locals_count + argument) as usize;
+ (layout.arguments_base() + argument, self.frame.slots[slot].node)
+ });
+ let untracked = call.into_iter().flat_map(move |call| {
+ (layout.number_of_arguments..)
+ .zip(&call.untracked_arguments)
+ .map(move |(argument, node)| (layout.arguments_base() + argument, *node))
+ });
+ tracked.chain(untracked)
}
/// Ends the instruction at `instruction_index` just built (with the
@@ -570,31 +583,34 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
}
let function_index = self.function.index;
let graph = &self.graph;
- let nodes = (first_node..graph.nodes.len())
- .map(|index| NodeId(index as u32))
- .filter(|node| {
- let data = graph.node(*node);
- // NB: Nodes of the calls the instruction inlined run in frames
- // of their own, after which those calls guard themselves.
- data.op.properties().runs_code
- && data.frame_state.is_some_and(|frame_state| {
- let innermost = graph.frame_state(frame_state);
- innermost.executable == function_index && innermost.parent == Some(parent)
- })
- })
- .collect::<Vec<_>>();
+ let nodes = ZoneVec::from_iter_in(
+ (first_node..graph.nodes.len())
+ .map(|index| NodeId(index as u32))
+ .filter(|node| {
+ let data = graph.node(*node);
+ // NB: Nodes of the calls the instruction inlined run in frames
+ // of their own, after which those calls guard themselves.
+ data.op.properties().runs_code
+ && data.frame_state.is_some_and(|frame_state| {
+ let innermost = graph.frame_state(frame_state);
+ innermost.executable == function_index && innermost.parent == Some(parent)
+ })
+ }),
+ graph.zone,
+ );
if nodes.is_empty() {
return;
}
let last = instruction_index + self.function.skipped_instructions;
+ let live = self.live_out(last);
let frame_state = FrameState {
pc: self.function.instructions[last].next_pc(),
- ..self.new_frame_state(&self.function.liveness.live_out(last), ResumeMode::ResumeAt)
+ ..self.new_frame_state(&live, ResumeMode::ResumeAt)
};
+ self.release_slot_set(live);
let frame_state = self.graph.add_frame_state(frame_state);
let guard = self.emit(Op::AssumeLegacyArgumentsUnread, &[], None);
self.graph.nodes[guard.index()].frame_state = Some(frame_state);
- let nodes = self.graph.list(&nodes);
self.graph.legacy_arguments_guards.push((guard, nodes));
}
@@ -661,7 +677,8 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
if let Some(native) = feedback.native_call.filter(|native| native.entry.is_some()) {
// NB: Native calls take the callee, the `this` value and the
// arguments as inputs like direct calls do.
- let mut inputs = vec![*callee, *this_value];
+ let mut inputs = ZoneVec::with_capacity_in(arguments.len() + 2, self.work);
+ inputs.extend([*callee, *this_value]);
inputs.extend(arguments.iter().copied());
// NB: Calls without the frames of the inlined calls they are in check their callee (see
// `check_call_without_frames_target()`), and are generic where those checks exited before.
@@ -768,7 +785,8 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
// are written whole, and for the virtual arguments object.
// NB: Calls without the frames of the inlined calls they are in
// always take `this`, for their slow paths.
- let mut inputs = vec![*callee, *this_value];
+ let mut inputs = ZoneVec::with_capacity_in(arguments.len() + 2, self.work);
+ inputs.extend([*callee, *this_value]);
inputs.extend(arguments.iter().copied());
// NB: Calls without those frames check their callee, unless it is constant (see
// `check_call_without_frames_target()`), and are generic where those checks exited before.
@@ -903,10 +921,11 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
op: Op<'z>,
inputs: &[Operand],
) -> Result<Flow, CompileFailure> {
- let input_nodes = inputs
- .iter()
- .map(|operand| self.read(*operand))
- .collect::<Result<Vec<_>, _>>()?;
+ let mut input_nodes = ZoneVec::with_capacity_in(inputs.len(), self.work);
+ for operand in inputs {
+ let node = self.read(*operand)?;
+ input_nodes.push(node);
+ }
let mut destination = None;
instruction.for_each_operand(|operand, role| {
if role.is_written() {
@@ -956,7 +975,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
..InlinedCallSite::new(
index,
InlineValue::Operand(*this_value),
- arguments.iter().copied().map(InlineValue::Operand).collect(),
+ self.inline_operands(arguments),
*argument_count,
*dst,
)
@@ -986,7 +1005,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
..InlinedCallSite::new(
callback.index,
InlineValue::Operand(*this_value),
- arguments.iter().copied().map(InlineValue::Operand).collect(),
+ self.inline_operands(arguments),
*argument_count,
*dst,
)
@@ -1007,7 +1026,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
..InlinedCallSite::new(
index,
InlineValue::Operand(*this_value),
- arguments.iter().copied().map(InlineValue::Operand).collect(),
+ self.inline_operands(arguments),
*argument_count,
*dst,
)
@@ -1034,7 +1053,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
}
InlinedCallSite {
callee: Some(*this_value),
- ..InlinedCallSite::through_call(index, arguments, *argument_count, *dst)
+ ..InlinedCallSite::through_call(index, arguments, *argument_count, *dst, self.work)
}
}
Forwarding::Apply => {
@@ -1049,7 +1068,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
let (arguments, count) = match self.inlined_call_arguments() {
Some(arguments) => arguments,
None if self.may_speculate(ExitKind::UnexpectedValue) => (
- (0..forwarded.argument_count).map(InlineValue::FrameArgument).collect(),
+ ZoneVec::from_iter_in((0..forwarded.argument_count).map(InlineValue::FrameArgument), self.work),
forwarded.argument_count,
),
None => return Ok(None),
@@ -1076,12 +1095,14 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
..InlinedCallSite::new(
index,
InlineValue::Constant(forwarded.bound_this),
- bound_arguments
- .iter()
- .copied()
- .map(InlineValue::Constant)
- .chain(arguments.iter().copied().map(InlineValue::Operand))
- .collect(),
+ ZoneVec::from_iter_in(
+ bound_arguments
+ .iter()
+ .copied()
+ .map(InlineValue::Constant)
+ .chain(arguments.iter().copied().map(InlineValue::Operand)),
+ self.work,
+ ),
forwarded.bound_argument_count + argument_count,
*dst,
)
@@ -1115,7 +1136,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
let call = InlinedCallSite::new(
index,
InlineValue::Operand(*this_value),
- arguments.iter().copied().map(InlineValue::Operand).collect(),
+ self.inline_operands(arguments),
*argument_count,
*dst,
);
@@ -1136,21 +1157,27 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
if self.constant_intrinsic(*callee) != Some(Intrinsic::FunctionPrototypeCall) {
return Ok(None);
}
- self.inline_call(InlinedCallSite::through_call(index, arguments, *argument_count, *dst))
+ self.inline_call(InlinedCallSite::through_call(
+ index,
+ arguments,
+ *argument_count,
+ *dst,
+ self.work,
+ ))
}
/// The functions the callee of a call may be, with the snapshot
/// executables of those whose calls may be inlined, if the callee is a
/// phi of a few function constants in the current block, like the
/// methods a property lookup found for the shapes it switched on.
- fn callee_cases(&self, callee: Operand) -> Option<Vec<(u64, Option<u32>)>> {
+ fn callee_cases(&self, callee: Operand) -> Option<ZoneVec<'a, (u64, Option<u32>)>> {
let node = self.peek(callee)?.node;
// NB: Phis of loop headers get the inputs of their back edges later.
let block = &self.graph.blocks[self.block.index()];
if block.is_loop_header || !block.phis.contains(&node) {
return None;
}
- let mut cases: Vec<(u64, Option<u32>)> = Vec::new();
+ let mut cases = ZoneVec::new_in(self.work);
for input in &self.graph.node(node).inputs {
let bits = self.graph.constant_value(*input)?;
if value::tag(bits) != value::OBJECT_TAG {
@@ -1177,7 +1204,11 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// predecessors jump to it. Each case can then start on its edges, which
/// keep what the code knew there, like the shape of the receiver the
/// `GetById` that found the methods switched on.
- fn callee_case_edges(&self, callee_phi: NodeId, cases: &[(u64, Option<u32>)]) -> Option<Vec<Vec<BlockId>>> {
+ fn callee_case_edges(
+ &self,
+ callee_phi: NodeId,
+ cases: &[(u64, Option<u32>)],
+ ) -> Option<ZoneVec<'a, ZoneVec<'a, BlockId>>> {
let block = &self.graph.blocks[self.block.index()];
if !block.body.is_empty() || block.phis != [callee_phi] {
return None;
@@ -1193,20 +1224,20 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
return None;
}
let inputs = &self.graph.node(callee_phi).inputs;
- Some(
- cases
- .iter()
- .map(|(bits, _)| {
+ Some(ZoneVec::from_iter_in(
+ cases.iter().map(|(bits, _)| {
+ ZoneVec::from_iter_in(
block
.predecessors
.iter()
.zip(inputs)
.filter(|(_, input)| self.graph.constant_value(**input) == Some(*bits))
- .map(|(predecessor, _)| *predecessor)
- .collect()
- })
- .collect(),
- )
+ .map(|(predecessor, _)| *predecessor),
+ self.work,
+ )
+ }),
+ self.work,
+ ))
}
/// Makes `edges`, edges into the current block `join` (see
@@ -1221,13 +1252,15 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
) -> BlockId {
if case == 0 {
let block = &self.graph.blocks[join.index()];
- let kept_inputs = block
- .predecessors
- .iter()
- .zip(&self.graph.node(callee_phi).inputs)
- .filter(|(predecessor, _)| edges.contains(predecessor))
- .map(|(_, input)| *input)
- .collect::<Vec<_>>();
+ let kept_inputs = ZoneVec::from_iter_in(
+ block
+ .predecessors
+ .iter()
+ .zip(&self.graph.node(callee_phi).inputs)
+ .filter(|(predecessor, _)| edges.contains(predecessor))
+ .map(|(_, input)| *input),
+ self.work,
+ );
self.graph.nodes[callee_phi.index()].inputs.assign(&kept_inputs);
self.graph.blocks[join.index()].predecessors.assign(edges);
return join;
@@ -1282,14 +1315,13 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
let Some(dst_slot) = self.function.layout.tracked_index(*dst) else {
return Ok(None);
};
- let operands = std::iter::once(*callee)
+ let mut operands = std::iter::once(*callee)
.chain(std::iter::once(*this_value))
- .chain(arguments.iter().copied())
- .collect::<Vec<_>>();
+ .chain(arguments.iter().copied());
if self.graph.legacy_arguments.contains(&dst.raw())
|| info.reads_whole_frame
|| crate::codegen::slow_path_call(OpCode::Call).is_none()
- || operands.iter().any(|operand| self.holds_virtual_arguments(*operand))
+ || operands.any(|operand| self.holds_virtual_arguments(operand))
{
return Ok(None);
}
@@ -1309,8 +1341,8 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
};
let join = self.block;
let frame = self.frame.clone();
- let mut results = Vec::new();
- let mut case_shapes = Vec::new();
+ let mut results = ZoneVec::new_in(self.work);
+ let mut case_shapes = ZoneVec::new_in(self.work);
for (case, (bits, index)) in cases.iter().enumerate() {
let mut next_case = None;
match (&edges, callee_value) {
@@ -1342,7 +1374,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
Some(index) if self.may_inline_callee_case(*index) => self.inline_call(InlinedCallSite::new(
*index,
InlineValue::Operand(*this_value),
- arguments.iter().copied().map(InlineValue::Operand).collect(),
+ self.inline_operands(arguments),
*argument_count,
*dst,
))?,
@@ -1367,9 +1399,9 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
"cases change no slot but the destination"
);
results.push((self.block, node, *bits));
- case_shapes.push(std::mem::take(&mut self.frame.fresh_shapes));
+ case_shapes.push(self.frame.fresh_shapes.take());
}
- self.frame = frame.clone();
+ self.frame.clone_from(&frame);
if let Some(next_case) = next_case {
self.block = next_case;
}
@@ -1381,10 +1413,11 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
self.join_blocks(results.iter().map(|(block, _, _)| *block).collect());
if edges.is_some() {
// NB: The callee's phi no longer reaches here.
- let functions = results
- .iter()
- .map(|(_, _, bits)| self.constant(*bits))
- .collect::<Vec<_>>();
+ let mut functions = ZoneVec::with_capacity_in(results.len(), self.work);
+ for (_, _, bits) in &results {
+ let function = self.constant(*bits);
+ functions.push(function);
+ }
let function = if functions.iter().all(|function| *function == functions[0]) {
functions[0]
} else {
@@ -1395,16 +1428,18 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
in_sync: callee_in_sync,
};
}
- let values = results
- .iter()
- .map(|(block, value, _)| self.tagged_at_end_of(*block, *value))
- .collect::<Vec<_>>();
+ let mut values = ZoneVec::with_capacity_in(results.len(), self.work);
+ for (block, value, _) in &results {
+ let value = self.tagged_at_end_of(*block, *value);
+ values.push(value);
+ }
let result = if values.iter().all(|value| *value == values[0]) {
values[0]
} else {
self.add_phi(&values)
};
- self.frame.fresh_shapes = AbstractFrame::common_fresh_shapes(case_shapes.iter().map(Vec::as_slice));
+ self.frame
+ .set_common_fresh_shapes(case_shapes.iter().map(|shapes| shapes.as_slice()));
self.write(*dst, result)?;
Ok(Some(Flow::Continue))
}
@@ -1424,7 +1459,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
self.inline_call(InlinedCallSite {
closure: getter,
check_closure: getter.is_some(),
- ..InlinedCallSite::new(index, InlineValue::Operand(this), Vec::new(), 0, dst)
+ ..InlinedCallSite::new(index, InlineValue::Operand(this), ZoneVec::new_in(self.work), 0, dst)
})
}
@@ -1448,7 +1483,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
..InlinedCallSite::new(
index,
InlineValue::Operand(this),
- vec![InlineValue::Operand(value)],
+ ZoneVec::from_slice_in(&[InlineValue::Operand(value)], self.work),
1,
dst,
)
@@ -1494,7 +1529,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
..InlinedCallSite::new(
index,
InlineValue::Operand(*this_value),
- arguments.iter().copied().map(InlineValue::Operand).collect(),
+ self.inline_operands(arguments),
*argument_count,
*dst,
)
@@ -1537,7 +1572,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
..InlinedCallSite::new(
construct.executable,
InlineValue::Constant(value::UNDEFINED),
- arguments.iter().copied().map(InlineValue::Operand).collect(),
+ self.inline_operands(arguments),
*argument_count,
*dst,
)
@@ -1560,7 +1595,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
return false;
}
// NB: The constructors inlined above `target` by then, from the derived constructor here down.
- let mut inlined_above = vec![constructor_executable.cell];
+ let mut inlined_above = ZoneVec::from_slice_in(&[constructor_executable.cell], self.work);
loop {
let kind = if target.derived {
InlinedCallKind::DerivedConstruct
@@ -1675,7 +1710,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
} => (
dst,
super_constructor,
- arguments.iter().copied().map(InlineValue::Operand).collect::<Vec<_>>(),
+ self.inline_operands(arguments),
*argument_count,
false,
),
@@ -1690,12 +1725,12 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
.as_ref()
.expect("derived constructs are inlined calls");
let count = call.passed_argument_count;
- let arguments = self
- .legacy_argument_values()
- .into_iter()
- .take(count as usize)
- .map(|(_, node)| InlineValue::Node(node))
- .collect::<Vec<_>>();
+ let arguments = ZoneVec::from_iter_in(
+ self.legacy_argument_values()
+ .take(count as usize)
+ .map(|(_, node)| InlineValue::Node(node)),
+ self.work,
+ );
if arguments.len() != count as usize {
return Err(CompileFailure::InvalidBytecode {
pc: self.function.pc,
@@ -2185,7 +2220,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
|| (closure && callee_executable.is_non_strict_function())
|| (virtual_arguments && uses_passed_arguments)
|| forwards_arguments_to_super;
- let callee_function = Function::new(snapshot, index, decoded, has_legacy_arguments).ok()?;
+ let callee_function = Function::new(snapshot, index, decoded, has_legacy_arguments, self.work).ok()?;
if !can_inline(&callee_function, virtual_arguments, derived_construct) {
return None;
}
@@ -2204,7 +2239,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
returns_no_object(&callee_function)
&& (!callee_executable.has_instance_elements || callee_executable.literal_instance_fields.is_some())
}
- InlinedCallKind::DerivedConstruct => calls_super_once_before_returning(&callee_function),
+ InlinedCallKind::DerivedConstruct => calls_super_once_before_returning(&callee_function, self.work),
};
qualifies.then_some(InlinableCallee {
executable: callee_executable,
@@ -2214,7 +2249,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
}
/// Inlines the call `call` describes, if its callee qualifies.
- fn inline_call(&mut self, call: InlinedCallSite) -> Result<Option<Flow>, CompileFailure> {
+ fn inline_call(&mut self, call: InlinedCallSite<'a>) -> Result<Option<Flow>, CompileFailure> {
let InlinedCallSite {
index,
callee,
@@ -2337,15 +2372,16 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
None,
);
}
- let argument_values = arguments
- .into_iter()
- .map(|argument| self.inline_value(argument))
- .collect::<Result<Vec<_>, _>>()?;
+ let mut argument_values = ZoneVec::with_capacity_in(arguments.len(), self.work);
+ for argument in arguments {
+ let value = self.inline_value(argument)?;
+ argument_values.push(value);
+ }
let argument_count = &passed_argument_count;
let dst = &dst;
// NB: Exits in the callee resume the caller after the call.
- let mut caller_live = self.function.liveness.live_out(self.function.instruction_index);
+ let mut caller_live = self.live_out(self.function.instruction_index);
if let Some(slot) = self.function.layout.tracked_index(*dst) {
caller_live.remove(slot);
}
@@ -2353,6 +2389,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
passed_argument_count: forwarded.then_some(passed_argument_count),
..self.new_frame_state(&caller_live, ResumeMode::ResumeAfter { dst: dst.raw() })
};
+ self.release_slot_set(caller_live);
let caller_frame_state = self.graph.add_frame_state(caller_frame_state);
let frame_bytes = self.function.inline.as_ref().map_or(0, |call| call.frame_bytes)
+ callee_executable.frame_size(self.runtime.offsets.execution_context_slots, *argument_count);
@@ -2362,13 +2399,14 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
let layout = callee_function.layout;
let empty = self.constant(value::EMPTY);
let undefined = self.constant(value::UNDEFINED);
- let mut slots = vec![
+ let mut slots = ZoneVec::from_elem_in(
SlotState {
node: empty,
in_sync: true,
- };
- layout.tracked_slot_count()
- ];
+ },
+ layout.tracked_slot_count(),
+ self.work,
+ );
slots[crate::bytecode::THIS_VALUE_REGISTER as usize] = SlotState {
node: receiver,
in_sync: true,
@@ -2394,15 +2432,17 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
passed_argument_count: *argument_count,
has_legacy_arguments,
untracked_arguments: if has_legacy_arguments {
- argument_values
- .get(layout.number_of_arguments as usize..)
- .unwrap_or_default()
- .to_vec()
+ ZoneVec::from_slice_in(
+ argument_values
+ .get(layout.number_of_arguments as usize..)
+ .unwrap_or_default(),
+ self.work,
+ )
} else {
- Vec::new()
+ ZoneVec::new_in(self.work)
},
continuation: None,
- returns: Vec::new(),
+ returns: ZoneVec::new_in(self.work),
return_fresh_shapes: None,
frame_bytes,
construct: construct.is_some(),
@@ -2411,6 +2451,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
});
// NB: Walk the callee's bytecode, then continue in the caller.
+ callee_function.start_walk();
let caller = std::mem::replace(&mut self.function, callee_function);
self.callers.push(caller);
self.frame = callee_frame;
@@ -2430,7 +2471,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
self.order.push(continuation);
self.block = continuation;
self.frame = call.caller_frame;
- self.frame.fresh_shapes = call.return_fresh_shapes.unwrap_or_default();
+ self.frame.fresh_shapes = call.return_fresh_shapes.unwrap_or_else(|| ZoneVec::new_in(self.work));
let values = call.returns;
let result = if values.iter().all(|value| *value == values[0]) {
values[0]
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 77aa3dccf30..154c16ac03a 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -54,7 +54,7 @@ pub use speculation::OperationInput;
pub(crate) use osr::is_loop_back_edge;
use crate::CompileFailure;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
use crate::bytecode::DecodedInstruction;
use crate::bytecode::FrameLayout;
use crate::bytecode::Instruction;
@@ -71,7 +71,6 @@ use crate::bytecode::liveness::Liveness;
use crate::code::ExitKind;
use crate::code::Repr;
use crate::code::ResumeMode;
-use crate::fast_hash::HashMap;
use crate::ir::Block;
use crate::ir::BlockId;
use crate::ir::BranchCondition;
@@ -89,6 +88,7 @@ use crate::snapshot::ExecutableSnapshot;
use crate::snapshot::Intrinsic;
use crate::snapshot::RuntimeInfo;
use crate::snapshot::Snapshot;
+use crate::zone_map::ZoneMap;
use ak::Zone;
use ak::ZoneVec;
pub(crate) use slow_paths::is_ssa_slow_path_output;
@@ -118,7 +118,7 @@ pub fn build_graph_with_feedback<'z>(
has_run: &dyn Fn(u32) -> bool,
zone: &'z Zone,
) -> Result<Graph<'z>, CompileFailure> {
- let mut attempts = Attempts::new(snapshot, has_run, zone);
+ let attempts = Attempts::new(snapshot, has_run, zone);
loop {
if let Some(graph) = attempts.build(zone)? {
return Ok(graph);
@@ -169,9 +169,9 @@ pub struct Attempts<'a> {
has_run: &'a dyn Fn(u32) -> bool,
/// Where the builds keep their own data. It holds the data of all the builds until its owner resets it.
work: &'a Zone,
- decoded: Vec<OnceCell<Result<DecodedFunction, CompileFailure>>>,
+ decoded: Vec<OnceCell<Result<DecodedFunction<'a>, CompileFailure>>>,
virtualized_inlined_arguments: Cell<bool>,
- next: Attempt,
+ next: Cell<Attempt>,
}
/// What a build of `Attempts` does differently from the first one.
@@ -191,13 +191,14 @@ impl<'a> Attempts<'a> {
work,
decoded: (0..snapshot.executables.len()).map(|_| OnceCell::new()).collect(),
virtualized_inlined_arguments: Cell::new(false),
- next: Attempt::First,
+ next: Cell::new(Attempt::First),
}
}
/// Builds a graph in `zone`. Returns `None` for a graph that cannot be used: the caller then drops what is in
- /// `zone` and calls this again, which builds the graph in another way.
- pub fn build<'z>(&mut self, zone: &'z Zone) -> Result<Option<Graph<'z>>, CompileFailure> {
+ /// `zone` and calls this again, which builds the graph in another way. The builds keep the decoded functions, whose
+ /// analyses are in the work zone, borrowed for as long as the attempts live.
+ pub fn build<'z>(&'a self, zone: &'z Zone) -> Result<Option<Graph<'z>>, CompileFailure> {
let build = |virtualize_arguments, virtualize_inlined_arguments, build_osr_entries| {
GraphBuilder::new(
self.snapshot,
@@ -214,11 +215,11 @@ impl<'a> Attempts<'a> {
)?
.build()
};
- let graph = match self.next {
+ let graph = match self.next.get() {
Attempt::First => match build(true, true, true) {
Ok(graph) if !arguments::uses_virtual_arguments(&graph) => return Ok(Some(graph)),
_ if self.virtualized_inlined_arguments.get() => {
- self.next = Attempt::WithoutVirtualArgumentsOfInlinedCallees;
+ self.next.set(Attempt::WithoutVirtualArgumentsOfInlinedCallees);
return Ok(None);
}
result => result?,
@@ -236,18 +237,18 @@ impl<'a> Attempts<'a> {
return Ok(Some(graph));
}
// Something needs the arguments object itself.
- self.next = Attempt::WithoutVirtualArguments;
+ self.next.set(Attempt::WithoutVirtualArguments);
return Ok(None);
}
Attempt::WithoutVirtualArguments => return build(false, false, true).map(Some),
};
// NB: The graph uses the virtual arguments object of the compiled function.
- self.next = if graph.osr_entries.is_empty() {
+ self.next.set(if graph.osr_entries.is_empty() {
// Something needs the arguments object itself.
Attempt::WithoutVirtualArguments
} else {
Attempt::WithoutOsrEntries
- };
+ });
Ok(None)
}
}
@@ -278,11 +279,11 @@ const MAX_FRESH_SHAPES: usize = 16;
/// The builder's view of the frame's registers, locals and arguments,
/// indexed by `FrameLayout::tracked_index()`, and of the fields of its
/// execution context.
-#[derive(Debug, Clone)]
-struct AbstractFrame {
+#[derive(Debug)]
+struct AbstractFrame<'a> {
/// Every slot holds a value. Slots that are not live hold `undefined` where the walk does not know their values
/// (at entries and merges), as in sync, so that nothing ever stores them, though frame memory may hold anything.
- slots: Vec<SlotState>,
+ slots: ZoneVec<'a, SlotState>,
/// For each `FrameField` (in the order of `FrameField::ALL`), the value
/// the field holds on this path, once loaded or set (see
/// `GraphBuilder::frame_field()`).
@@ -290,22 +291,40 @@ struct AbstractFrame {
/// The shapes of objects the code allocated, by their allocation nodes,
/// as far as this path knows them: each object's shape since its last
/// addition, until something runs that may change shapes otherwise.
- fresh_shapes: Vec<(NodeId, CellId)>,
+ fresh_shapes: ZoneVec<'a, (NodeId, CellId)>,
+}
+
+impl Clone for AbstractFrame<'_> {
+ fn clone(&self) -> Self {
+ Self {
+ slots: self.slots.clone(),
+ fields: self.fields,
+ fresh_shapes: self.fresh_shapes.clone(),
+ }
+ }
+
+ fn clone_from(&mut self, other: &Self) {
+ // NB: This keeps the memory of the lists where the copies fit.
+ self.slots.assign(&other.slots);
+ self.fields = other.fields;
+ self.fresh_shapes.assign(&other.fresh_shapes);
+ }
}
-impl AbstractFrame {
- /// A frame whose slots all hold `value` in sync and whose fields are not loaded yet.
- fn filled(slot_count: usize, value: NodeId) -> Self {
+impl<'a> AbstractFrame<'a> {
+ /// A frame whose slots all hold `value` in sync and whose fields are not loaded yet, with its lists in `work`.
+ fn filled(slot_count: usize, value: NodeId, work: &'a Zone) -> Self {
Self {
- slots: vec![
+ slots: ZoneVec::from_elem_in(
SlotState {
node: value,
in_sync: true,
- };
- slot_count
- ],
+ },
+ slot_count,
+ work,
+ ),
fields: [None; FrameField::ALL.len()],
- fresh_shapes: Vec::new(),
+ fresh_shapes: ZoneVec::new_in(work),
}
}
@@ -317,17 +336,17 @@ impl AbstractFrame {
self.fields[field as usize] = Some(value);
}
- /// The shapes every one of `frames` (their `fresh_shapes`) knows its
- /// objects have.
- fn common_fresh_shapes<'f>(mut frames: impl Iterator<Item = &'f [(NodeId, CellId)]>) -> Vec<(NodeId, CellId)> {
+ /// Makes `fresh_shapes` the shapes every one of `frames` (their
+ /// `fresh_shapes`) knows its objects have.
+ fn set_common_fresh_shapes<'f>(&mut self, mut frames: impl Iterator<Item = &'f [(NodeId, CellId)]>) {
+ self.fresh_shapes.clear();
let Some(first) = frames.next() else {
- return Vec::new();
+ return;
};
- let mut shapes = first.to_vec();
+ self.fresh_shapes.extend_from_slice(first);
for other in frames {
- shapes.retain(|shape| other.contains(shape));
+ self.fresh_shapes.retain(|shape| other.contains(shape));
}
- shapes
}
/// Forgets the environments, which an instruction may change.
@@ -358,18 +377,22 @@ fn replaces_environments(opcode: OpCode) -> bool {
/// Whether each loop has an instruction that may replace an environment
/// (see `replaces_environments()`), nested loops included.
-fn loops_replacing_environments(cfg: &Cfg, instructions: &[DecodedInstruction]) -> Vec<bool> {
- cfg.loops
- .iter()
- .map(|current_loop| {
+fn loops_replacing_environments<'w>(
+ cfg: &Cfg<'_>,
+ instructions: &[DecodedInstruction],
+ work: &'w Zone,
+) -> ZoneVec<'w, bool> {
+ ZoneVec::from_iter_in(
+ cfg.loops.iter().map(|current_loop| {
current_loop.blocks.iter().any(|block| {
cfg.blocks[*block]
.instructions
.clone()
.any(|index| replaces_environments(instructions[index].instruction.opcode()))
})
- })
- .collect()
+ }),
+ work,
+ )
}
/// What ends the instruction currently being built.
@@ -380,8 +403,8 @@ enum Flow {
Ended,
}
-fn written_constants(instructions: &[DecodedInstruction], layout: &FrameLayout) -> BitSet {
- let mut written = BitSet::new(layout.number_of_constants as usize);
+fn written_constants<'w>(instructions: &[DecodedInstruction], layout: &FrameLayout, work: &'w Zone) -> ZoneBitSet<'w> {
+ let mut written = ZoneBitSet::new_in(layout.number_of_constants as usize, work);
let constants = layout.constants_base()..layout.arguments_base();
for instruction in instructions {
instruction.instruction.for_each_operand(|operand, role| {
@@ -397,19 +420,19 @@ fn written_constants(instructions: &[DecodedInstruction], layout: &FrameLayout)
/// and those any loop whose header lies in its body assigns, since that
/// header gives them new values. Without irreducible control flow (as
/// `finally` dispatch can create), those loops are nested in it anyway.
-fn loop_phi_slots(cfg: &Cfg) -> Vec<BitSet> {
- let mut slots = cfg
- .loops
- .iter()
- .map(|current_loop| current_loop.assigned_slots.clone())
- .collect::<Vec<_>>();
+fn loop_phi_slots<'w>(cfg: &Cfg<'w>, work: &'w Zone) -> ZoneVec<'w, ZoneBitSet<'w>> {
+ let mut slots = ZoneVec::from_iter_in(
+ cfg.loops.iter().map(|current_loop| current_loop.assigned_slots.clone()),
+ work,
+ );
+ let mut other_slots = ZoneBitSet::new_in(0, work);
let mut changed = true;
while changed {
changed = false;
for (index, current_loop) in cfg.loops.iter().enumerate() {
for (other_index, other) in cfg.loops.iter().enumerate() {
if other_index != index && current_loop.blocks.contains(&other.header) {
- let other_slots = slots[other_index].clone();
+ other_slots.clone_from(&slots[other_index]);
changed |= slots[index].union_with(&other_slots);
}
}
@@ -420,16 +443,17 @@ fn loop_phi_slots(cfg: &Cfg) -> Vec<BitSet> {
/// Bytecode decoding and analyses shared by every walk of an executable.
/// Analyses are lazy: an inlining budget rejection only needs decoding.
-struct DecodedFunction {
+/// The analyses are in the work zone of the builds.
+struct DecodedFunction<'w> {
instructions: Vec<DecodedInstruction>,
- analysis: OnceCell<Result<FunctionAnalysis, CompileFailure>>,
+ analysis: OnceCell<Result<FunctionAnalysis<'w>, CompileFailure>>,
}
-fn decoded_function<'a>(
+fn decoded_function<'c, 'w>(
snapshot: &Snapshot,
executable: &ExecutableSnapshot,
- cache: &'a OnceCell<Result<DecodedFunction, CompileFailure>>,
-) -> Result<&'a DecodedFunction, CompileFailure> {
+ cache: &'c OnceCell<Result<DecodedFunction<'w>, CompileFailure>>,
+) -> Result<&'c DecodedFunction<'w>, CompileFailure> {
cache
.get_or_init(|| {
let bytecode = &snapshot[executable.bytecode];
@@ -452,13 +476,13 @@ fn decoded_function<'a>(
.map_err(|error| *error)
}
-struct FunctionAnalysis {
- cfg: Cfg,
+struct FunctionAnalysis<'w> {
+ cfg: Cfg<'w>,
/// Liveness without and with arguments observable through `f.arguments`.
- liveness: [OnceCell<Liveness>; 2],
- loop_phi_slots: Vec<BitSet>,
- loops_replacing_environments: Vec<bool>,
- written_constants: BitSet,
+ liveness: [OnceCell<Liveness<'w>>; 2],
+ loop_phi_slots: ZoneVec<'w, ZoneBitSet<'w>>,
+ loops_replacing_environments: ZoneVec<'w, bool>,
+ written_constants: ZoneBitSet<'w>,
writes_arguments: bool,
may_write_parameter_bindings: bool,
}
@@ -472,36 +496,38 @@ struct Function<'a> {
executable: &'a ExecutableSnapshot,
layout: FrameLayout,
instructions: &'a [DecodedInstruction],
- cfg: &'a Cfg,
- liveness: &'a Liveness,
+ cfg: &'a Cfg<'a>,
+ liveness: &'a Liveness<'a>,
+ // NB: The lists of the walk below have an element for each bytecode block once the walk starts (see
+ // `start_walk()`), and none before.
/// The IR block of each bytecode block, created when first referenced.
- ir_blocks: Vec<Option<BlockId>>,
+ ir_blocks: ZoneVec<'a, Option<BlockId>>,
/// Forward edges into each bytecode block not yet started: the IR
/// predecessor and the abstract frame at its end.
- incoming: Vec<Vec<(BlockId, AbstractFrame)>>,
+ incoming: ZoneVec<'a, ZoneVec<'a, (BlockId, AbstractFrame<'a>)>>,
/// Whether each bytecode block was started.
- started: Vec<bool>,
+ started: ZoneVec<'a, bool>,
/// The abstract frame at the start of each loop header that was started,
/// which every back edge must reconcile with.
- loop_header_frames: Vec<Option<AbstractFrame>>,
+ loop_header_frames: ZoneVec<'a, Option<AbstractFrame<'a>>>,
/// For each loop, the slots that get phis at its header.
- loop_phi_slots: &'a [BitSet],
+ loop_phi_slots: &'a [ZoneBitSet<'a>],
/// For each loop, whether it may replace an environment.
loops_replacing_environments: &'a [bool],
/// The loop headers that on-stack replacement entries lead to over back
/// edges, which are built even if no forward edge reaches them.
- osr_loop_headers: Vec<bool>,
+ osr_loop_headers: ZoneVec<'a, bool>,
/// Constant slots some instruction writes. The interpreter keeps a copy of
/// the constants in the frame, and writes to a constant operand change that
/// copy, so such slots live in frame memory.
- written_constants: &'a BitSet,
+ written_constants: &'a ZoneBitSet<'a>,
/// Index of the instruction being built.
instruction_index: usize,
pc: u32,
/// The frame state shared by every eager exit of the current instruction.
eager_frame_state: Option<FrameStateId>,
/// How this executable was called, if it is an inlined callee.
- inline: Option<inlining::InlineCall>,
+ inline: Option<inlining::InlineCall<'a>>,
/// Whether some instruction writes an argument slot.
writes_arguments: bool,
/// How many of the next instructions the instruction being built built
@@ -513,12 +539,14 @@ struct Function<'a> {
}
impl<'a> Function<'a> {
- /// The state for a walk over executable `index` of `snapshot`, which `decoded` is the instructions of.
+ /// The state for a walk over executable `index` of `snapshot`, which `decoded` is the instructions of, with its
+ /// data in `work`.
fn new(
snapshot: &'a Snapshot,
index: u32,
- decoded: &'a DecodedFunction,
+ decoded: &'a DecodedFunction<'a>,
has_legacy_arguments: bool,
+ work: &'a Zone,
) -> Result<Self, CompileFailure> {
let executable = &snapshot.executables[index as usize];
let layout = executable.layout;
@@ -527,13 +555,14 @@ impl<'a> Function<'a> {
.analysis
.get_or_init(|| {
let handlers = &snapshot[executable.exception_handlers];
- let cfg = Cfg::new(instructions, handlers, &layout).map_err(|_| CompileFailure::InvalidBytecode {
- pc: 0,
- reason: "invalid control flow",
- })?;
- let loop_phi_slots = loop_phi_slots(&cfg);
- let loops_replacing_environments = loops_replacing_environments(&cfg, instructions);
- let written_constants = written_constants(instructions, &layout);
+ let cfg =
+ Cfg::new(instructions, handlers, &layout, work).map_err(|_| CompileFailure::InvalidBytecode {
+ pc: 0,
+ reason: "invalid control flow",
+ })?;
+ let loop_phi_slots = loop_phi_slots(&cfg, work);
+ let loops_replacing_environments = loops_replacing_environments(&cfg, instructions, work);
+ let written_constants = written_constants(instructions, &layout, work);
let may_write_parameter_bindings = instructions
.iter()
.any(|decoded| arguments::may_write_parameter_bindings(decoded.instruction.opcode()));
@@ -556,8 +585,7 @@ impl<'a> Function<'a> {
.as_ref()
.map_err(|error| *error)?;
let liveness = analysis.liveness[usize::from(has_legacy_arguments)]
- .get_or_init(|| Liveness::compute(instructions, &analysis.cfg, &layout, has_legacy_arguments));
- let block_count = analysis.cfg.blocks.len();
+ .get_or_init(|| Liveness::compute(instructions, &analysis.cfg, &layout, has_legacy_arguments, work));
Ok(Self {
snapshot,
index,
@@ -566,13 +594,13 @@ impl<'a> Function<'a> {
instructions,
cfg: &analysis.cfg,
liveness,
- ir_blocks: vec![None; block_count],
- incoming: vec![Vec::new(); block_count],
- started: vec![false; block_count],
- loop_header_frames: vec![None; block_count],
+ ir_blocks: ZoneVec::new_in(work),
+ incoming: ZoneVec::new_in(work),
+ started: ZoneVec::new_in(work),
+ loop_header_frames: ZoneVec::new_in(work),
loop_phi_slots: &analysis.loop_phi_slots,
loops_replacing_environments: &analysis.loops_replacing_environments,
- osr_loop_headers: vec![false; block_count],
+ osr_loop_headers: ZoneVec::new_in(work),
written_constants: &analysis.written_constants,
instruction_index: 0,
pc: 0,
@@ -584,6 +612,18 @@ impl<'a> Function<'a> {
})
}
+ /// Gives the lists of the walk an element for each bytecode block. A function that is not walked, like a callee
+ /// that is not inlined after all, takes no memory for them.
+ fn start_walk(&mut self) {
+ let block_count = self.cfg.blocks.len();
+ self.ir_blocks.resize(block_count, None);
+ let work = self.ir_blocks.zone();
+ self.incoming.resize(block_count, ZoneVec::new_in(work));
+ self.started.resize(block_count, false);
+ self.loop_header_frames.resize(block_count, None);
+ self.osr_loop_headers.resize(block_count, false);
+ }
+
/// Whether this is the frame of an inlined call, whose slots are only
/// SSA values until it is materialized.
fn is_virtual(&self) -> bool {
@@ -601,21 +641,21 @@ struct GraphBuilder<'a, 'z> {
runtime: &'a RuntimeInfo,
has_run: &'a dyn Fn(u32) -> bool,
- decoded: &'a [OnceCell<Result<DecodedFunction, CompileFailure>>],
+ decoded: &'a [OnceCell<Result<DecodedFunction<'a>, CompileFailure>>],
graph: Graph<'z>,
/// Where the builder keeps its own data. Nothing of the graph is there.
work: &'a Zone,
/// The blocks in linear order, as they are started.
order: ZoneVec<'a, BlockId>,
/// The constant node of each value and representation.
- constants: HashMap<(u64, Repr), NodeId>,
+ constants: ZoneMap<'a, (u64, Repr), NodeId>,
block: BlockId,
- frame: AbstractFrame,
+ frame: AbstractFrame<'a>,
/// The executable being walked.
function: Function<'a>,
/// The executables whose walks are suspended at an inlined call, outermost first.
- callers: Vec<Function<'a>>,
+ callers: ZoneVec<'a, Function<'a>>,
/// Bytecode instructions inlined so far, for the inlining budget.
inlined_instructions: usize,
/// Where `CreateArguments` may build a virtual arguments object.
@@ -623,24 +663,28 @@ struct GraphBuilder<'a, 'z> {
/// Whether to build on-stack replacement entries (see `arguments`).
build_osr_entries: bool,
/// The intrinsics among the constants, by value.
- intrinsics: HashMap<u64, Intrinsic>,
+ intrinsics: ZoneMap<'a, u64, Intrinsic>,
/// The functions among the constants that calls may inline, by value:
/// their indices in `Snapshot::executables`.
- inlinable_functions: HashMap<u64, u32>,
+ inlinable_functions: ZoneMap<'a, u64, u32>,
/// The functions among the constants that calls may call directly, by
/// value.
- direct_call_functions: HashMap<u64, crate::snapshot::DirectCallTarget>,
+ direct_call_functions: ZoneMap<'a, u64, crate::snapshot::DirectCallTarget>,
/// How `instanceof` runs with the functions the code uses as constants
/// on its right-hand side (see `GlobalValueSnapshot::has_instance`), by
/// their bits.
- has_instance: HashMap<u64, crate::snapshot::OrdinaryHasInstanceSnapshot>,
+ has_instance: ZoneMap<'a, u64, crate::snapshot::OrdinaryHasInstanceSnapshot>,
+ /// Sets of slots that are free to use again (see `live_in()`).
+ free_slot_sets: ZoneVec<'a, ZoneBitSet<'a>>,
+ /// Lists of slots that are free to use again (see `slot_list()`).
+ free_slot_lists: ZoneVec<'a, ZoneVec<'a, usize>>,
}
impl<'a, 'z> GraphBuilder<'a, 'z> {
fn new(
snapshot: &'a Snapshot,
has_run: &'a dyn Fn(u32) -> bool,
- decoded: &'a [OnceCell<Result<DecodedFunction, CompileFailure>>],
+ decoded: &'a [OnceCell<Result<DecodedFunction<'a>, CompileFailure>>],
virtualize_arguments: ArgumentsVirtualization<'a>,
build_osr_entries: bool,
zone: &'z Zone,
@@ -658,7 +702,8 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
.instructions
.iter()
.any(|instruction| instruction.instruction.opcode() == OpCode::GetArgument);
- let function = Function::new(snapshot, 0, decoded_root, reads_argument_slots)?;
+ let mut function = Function::new(snapshot, 0, decoded_root, reads_argument_slots, work)?;
+ function.start_walk();
let arguments_base = function.layout.arguments_base();
let legacy_arguments = if executable.supports_legacy_arguments {
arguments_base..arguments_base + function.layout.number_of_arguments
@@ -676,26 +721,28 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
},
work,
order: ZoneVec::new_in(work),
- constants: HashMap::default(),
+ constants: ZoneMap::new_in(work),
block: BlockId(0),
// NB: Replaced by the frame of the first block built.
- frame: AbstractFrame::filled(0, NodeId(0)),
+ frame: AbstractFrame::filled(0, NodeId(0), work),
function,
- callers: Vec::new(),
+ callers: ZoneVec::new_in(work),
inlined_instructions: 0,
virtualize_arguments,
build_osr_entries,
- intrinsics: HashMap::default(),
- inlinable_functions: HashMap::default(),
- direct_call_functions: HashMap::default(),
- has_instance: HashMap::default(),
+ intrinsics: ZoneMap::new_in(work),
+ inlinable_functions: ZoneMap::new_in(work),
+ direct_call_functions: ZoneMap::new_in(work),
+ has_instance: ZoneMap::new_in(work),
+ free_slot_sets: ZoneVec::new_in(work),
+ free_slot_lists: ZoneVec::new_in(work),
})
}
fn build(mut self) -> Result<Graph<'z>, CompileFailure> {
// NB: The entry block has no predecessors and jumps to the first bytecode
// block, which may be a loop header.
- let entry = self.start_new_block(Vec::new());
+ let entry = self.start_new_block(&[]);
// OPTIMIZATION: The code of top-level code that a loop triggered the compile of is only entered inside, so
// what only its start reaches is left out, like a large literal that ran before the loop.
let builds_entry_at_osr_pc = self.snapshot.options.osr_pc.is_some_and(|pc| {
@@ -757,9 +804,12 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// The slots (as operands) that hold the values the compiled function starts with wherever it runs: the arguments
/// and the this value register, unless instructions of the function write them. The frame's initialization
/// changes the other registers and the locals, and the runtime the other reserved registers.
- fn slots_kept_from_start(&self) -> BitSet {
+ fn slots_kept_from_start(&self) -> ZoneBitSet<'z> {
let layout = self.function.layout;
- let mut kept = BitSet::new(layout.arguments_base() as usize + layout.number_of_arguments as usize);
+ let mut kept = ZoneBitSet::new_in(
+ layout.arguments_base() as usize + layout.number_of_arguments as usize,
+ self.graph.zone,
+ );
kept.insert_range(layout.arguments_base() as usize..kept.capacity());
if THIS_VALUE_REGISTER < layout.registers_and_locals_count {
kept.insert(THIS_VALUE_REGISTER as usize);
@@ -781,15 +831,55 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// slots live there are loaded from frame memory (loads nothing uses go away in dead code elimination).
fn load_entry_slots(&mut self) {
self.frame = self.dead_frame();
- for slot in self.function.liveness.live_in(0).iter() {
+ let live = self.live_in(0);
+ for slot in live.iter() {
self.load_slot(slot);
}
+ self.release_slot_set(live);
}
/// A frame whose slots are all dead: they hold `undefined` (see `AbstractFrame::slots`).
- fn dead_frame(&mut self) -> AbstractFrame {
+ fn dead_frame(&mut self) -> AbstractFrame<'a> {
let undefined = self.constant(value::UNDEFINED);
- AbstractFrame::filled(self.function.layout.tracked_slot_count(), undefined)
+ AbstractFrame::filled(self.function.layout.tracked_slot_count(), undefined, self.work)
+ }
+
+ /// The slots live before the instruction with the given index of the function being walked executes, in a set to
+ /// give back with `release_slot_set()` once it is not needed any more.
+ fn live_in(&mut self, instruction_index: usize) -> ZoneBitSet<'a> {
+ let mut live = self.slot_set();
+ self.function.liveness.live_in(instruction_index, &mut live);
+ live
+ }
+
+ /// Like `live_in()`, for the slots live after the instruction.
+ fn live_out(&mut self, instruction_index: usize) -> ZoneBitSet<'a> {
+ let mut live = self.slot_set();
+ self.function.liveness.live_out(instruction_index, &mut live);
+ live
+ }
+
+ fn slot_set(&mut self) -> ZoneBitSet<'a> {
+ self.free_slot_sets
+ .pop()
+ .unwrap_or_else(|| ZoneBitSet::new_in(0, self.work))
+ }
+
+ /// Gives back a set that `live_in()` or `live_out()` gave, for them to use again.
+ fn release_slot_set(&mut self, set: ZoneBitSet<'a>) {
+ self.free_slot_sets.push(set);
+ }
+
+ /// An empty list of slots, to give back with `release_slot_list()` once it is not needed any more.
+ fn slot_list(&mut self) -> ZoneVec<'a, usize> {
+ let mut list = self.free_slot_lists.pop().unwrap_or_else(|| ZoneVec::new_in(self.work));
+ list.clear();
+ list
+ }
+
+ /// Gives back a list that `slot_list()` gave, for it to use again.
+ fn release_slot_list(&mut self, list: ZoneVec<'a, usize>) {
+ self.free_slot_lists.push(list);
}
/// Loads a slot from frame memory, which then holds its value in sync.
@@ -833,9 +923,9 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// Creates a block, appends it to the linear order and makes it current.
/// The caller sets the abstract frame.
- fn start_new_block(&mut self, predecessors: Vec<BlockId>) -> BlockId {
+ fn start_new_block(&mut self, predecessors: &[BlockId]) -> BlockId {
let block = self.graph.add_block(Block {
- predecessors: self.graph.list(&predecessors),
+ predecessors: self.graph.list(predecessors),
..self.graph.new_block()
});
self.order.push(block);
@@ -846,7 +936,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// Starts the IR block of a bytecode block, merging the abstract frames of
/// its forward predecessors. Returns false if no built block reaches it.
fn start_bytecode_block(&mut self, block_index: BlockIndex) -> bool {
- let incoming = std::mem::take(&mut self.function.incoming[block_index]);
+ let incoming = self.function.incoming[block_index].take();
// NB: A loop whose forward entry was never built can still be
// running when compiled code is entered at a back edge inside it.
let only_back_edges = incoming.is_empty() && self.function.osr_loop_headers[block_index];
@@ -889,12 +979,16 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// header has a phi for each live slot the loop assigns, whose back edges add their inputs (see
/// `reconcile_back_edge()`). So does a loop header that on-stack replacement entries reach over back edges, for
/// every live slot: the values there come from different entries.
- fn merge(&mut self, block_index: BlockIndex, incoming: Vec<(BlockId, AbstractFrame)>) -> AbstractFrame {
- let bytecode_block = &self.function.cfg.blocks[block_index];
- let live = self.function.liveness.live_in(bytecode_block.instructions.start);
- let assigned_in_loop = bytecode_block
- .loop_index
- .map(|loop_index| self.function.loop_phi_slots[loop_index].clone());
+ fn merge(
+ &mut self,
+ block_index: BlockIndex,
+ incoming: ZoneVec<'a, (BlockId, AbstractFrame<'a>)>,
+ ) -> AbstractFrame<'a> {
+ let cfg = self.function.cfg;
+ let bytecode_block = &cfg.blocks[block_index];
+ let live = self.live_in(bytecode_block.instructions.start);
+ let loop_phi_slots = self.function.loop_phi_slots;
+ let assigned_in_loop = bytecode_block.loop_index.map(|loop_index| &loop_phi_slots[loop_index]);
let is_loop_header = bytecode_block.is_loop_header();
let mut merged = self.dead_frame();
@@ -909,8 +1003,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
let osr_loop_header = self.function.osr_loop_headers[block_index];
// NB: Loops may change the shapes their headers would know.
if !is_loop_header {
- merged.fresh_shapes =
- AbstractFrame::common_fresh_shapes(incoming.iter().map(|(_, frame)| frame.fresh_shapes.as_slice()));
+ merged.set_common_fresh_shapes(incoming.iter().map(|(_, frame)| frame.fresh_shapes.as_slice()));
}
for field in FrameField::ALL {
let first = incoming.first().and_then(|(_, frame)| frame.field(field));
@@ -922,11 +1015,12 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
merged.set_field(field, value);
}
}
+ let mut values = ZoneVec::with_capacity_in(incoming.len(), self.work);
+ let mut inputs = ZoneVec::with_capacity_in(incoming.len(), self.work);
for slot in live.iter() {
- let assigned = assigned_in_loop
- .as_ref()
- .is_some_and(|assigned| assigned.contains(slot));
- let values = incoming.iter().map(|(_, frame)| frame.slots[slot]).collect::<Vec<_>>();
+ let assigned = assigned_in_loop.is_some_and(|assigned| assigned.contains(slot));
+ values.clear();
+ values.extend(incoming.iter().map(|(_, frame)| frame.slots[slot]));
// NB: Back edges keep frame memory in sync with the values of the slots the loop does not assign, and
// the phis of the others get values memory need not hold.
let in_sync = values.iter().all(|value| value.in_sync) && !(is_loop_header && assigned);
@@ -956,16 +1050,17 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
None if reloads => self.emit(Op::LoadSlot { slot: operand.raw() }, &[], Some(Repr::Tagged)),
None => {
// NB: Phis start out tagged; representation selection unboxes them later.
- let inputs = incoming
- .iter()
- .zip(&values)
- .map(|((predecessor, _), value)| self.tagged_at_end_of(*predecessor, value.node))
- .collect::<Vec<_>>();
+ inputs.clear();
+ for ((predecessor, _), value) in incoming.iter().zip(&values) {
+ let input = self.tagged_at_end_of(*predecessor, value.node);
+ inputs.push(input);
+ }
self.add_phi(&inputs)
}
};
merged.slots[slot] = SlotState { node, in_sync };
}
+ self.release_slot_set(live);
merged
}
@@ -1054,7 +1149,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
fn end_with_branch(
&mut self,
make_op: impl FnOnce(BlockId, BlockId) -> Op<'z>,
- inputs: Vec<NodeId>,
+ inputs: &[NodeId],
if_true: BlockIndex,
if_false: BlockIndex,
) -> Result<(), CompileFailure> {
@@ -1070,10 +1165,10 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
});
self.order.push(true_edge);
self.order.push(false_edge);
- self.set_control(make_op(true_edge, false_edge), &inputs);
+ self.set_control(make_op(true_edge, false_edge), inputs);
for (edge, target) in [(true_edge, if_true), (false_edge, if_false)] {
self.block = edge;
- self.frame = frame.clone();
+ self.frame.clone_from(&frame);
self.end_with_jump(target)?;
}
Ok(())
@@ -1083,14 +1178,25 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
/// one at the start of the loop header `target`, and adds the inputs of
/// the header's phis for this back edge.
fn reconcile_back_edge(&mut self, target: BlockIndex) -> Result<(), CompileFailure> {
- let header = self.function.ir_blocks[target].expect("started loop headers have an IR block");
+ // NB: The frame goes back to its place below.
let header_frame = self.function.loop_header_frames[target]
- .clone()
+ .take()
.expect("the loop header was started");
- let live = self
- .function
- .liveness
- .live_in(self.function.cfg.blocks[target].instructions.start);
+ let live = self.live_in(self.function.cfg.blocks[target].instructions.start);
+ let result = self.reconcile_back_edge_with(target, &header_frame, &live);
+ self.release_slot_set(live);
+ self.function.loop_header_frames[target] = Some(header_frame);
+ result
+ }
+
+ /// `reconcile_back_edge()` with the header's abstract frame `header_frame` and the slots `live` into it.
+ fn reconcile_back_edge_with(
+ &mut self,
+ target: BlockIndex,
+ header_frame: &AbstractFrame<'a>,
+ live: &ZoneBitSet<'a>,
+ ) -> Result<(), CompileFailure> {
+ let header = self.function.ir_blocks[target].expect("started loop headers have an IR block");
for slot in live.iter() {
let header_value = header_frame.slots[slot];
let current = self.frame.slots[slot];
@@ -1333,11 +1439,12 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
node: value,
in_sync: true,
})
- && self
- .function
- .liveness
- .live_in(self.function.instruction_index)
- .contains(slot);
+ && {
+ let live = self.live_in(self.function.instruction_index);
+ let live_slot = live.contains(slot);
+ self.release_slot_set(live);
+ live_slot
+ };
if !unchanged {
if writes_memory {
self.emit(Op::StoreSlot { slot: operand.raw() }, &[value], None);
@@ -1366,10 +1473,9 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
if let Some(frame_state) = self.function.eager_frame_state {
return frame_state;
}
- let frame_state = self.new_frame_state(
- &self.function.liveness.live_in(self.function.instruction_index),
- ResumeMode::ResumeAt,
- );
+ let live = self.live_in(self.function.instruction_index);
+ let frame_state = self.new_frame_state(&live, ResumeMode::ResumeAt);
+ self.release_slot_set(live);
let frame_state = self.graph.add_frame_state(frame_state);
self.function.eager_frame_state = Some(frame_state);
frame_state
@@ -1392,18 +1498,17 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
return Ok(Flow::Ended);
}
- let instruction = self.function.instructions[self.function.instruction_index]
- .instruction
- .clone();
+ let instructions = self.function.instructions;
+ let instruction = &instructions[self.function.instruction_index].instruction;
if osr::is_loop_back_edge(instruction.opcode()) {
self.emit_checked(Op::CheckInterrupt, &[], None);
}
if replaces_environments(instruction.opcode()) {
self.frame.forget_environments();
}
- match self.try_build_natively(&instruction)? {
+ match self.try_build_natively(instruction)? {
Some(flow) => Ok(flow),
- None => self.build_by_handling(&instruction),
+ None => self.build_by_handling(instruction),
}
}
@@ -1581,11 +1686,10 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
{
return Ok(Some(flow));
}
- let elements = elements
- .iter()
- .copied()
- .map(allocation::ArrayElement::Operand)
- .collect::<Vec<_>>();
+ let elements = ZoneVec::from_iter_in(
+ elements.iter().copied().map(allocation::ArrayElement::Operand),
+ self.work,
+ );
if !self.try_build_new_array(dst, &elements)? {
return Ok(None);
}
@@ -1612,11 +1716,10 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
}
}
Instruction::NewPrimitiveArray { dst, ref elements, .. } => {
- let elements = elements
- .iter()
- .copied()
- .map(allocation::ArrayElement::Constant)
- .collect::<Vec<_>>();
+ let elements = ZoneVec::from_iter_in(
+ elements.iter().copied().map(allocation::ArrayElement::Constant),
+ self.work,
+ );
if !self.try_build_new_array(dst, &elements)? {
return Ok(None);
}
@@ -1860,9 +1963,11 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
if let Some(continuation) = continuation {
let block = self.block_for_label(continuation)?;
let start = self.function.cfg.blocks[block].instructions.start;
- for slot in self.function.liveness.live_in(start).iter() {
+ let live = self.live_in(start);
+ for slot in live.iter() {
self.sync_slot(slot);
}
+ self.release_slot_set(live);
}
// NB: Like the interpreter's Yield and Await, an empty value yields
// `undefined`.
@@ -1947,7 +2052,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
if_true,
if_false,
},
- vec![value],
+ &[value],
if_true,
if_false,
)
@@ -1984,7 +2089,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
);
for (edge, target) in [(true_edge, if_true), (false_edge, if_false)] {
self.block = edge;
- self.frame = frame.clone();
+ self.frame.clone_from(&frame);
self.end_with_jump(target)?;
}
self.block = fallback;
@@ -1996,7 +2101,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
if_true,
if_false,
},
- vec![boolean],
+ &[boolean],
if_true,
if_false,
)
@@ -2076,30 +2181,28 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
forwarded: Option<Operand>,
) -> Result<Flow, CompileFailure> {
let opcode = instruction.opcode();
- let input_nodes = inputs
- .iter()
- .map(|operand| self.read(*operand))
- .collect::<Result<Vec<_>, _>>()?;
- let input_slots = inputs
- .iter()
- .filter_map(|operand| self.function.layout.tracked_index(*operand))
- .collect::<Vec<_>>();
- let live_in = self.function.liveness.live_in(self.function.instruction_index);
+ let mut input_nodes = ZoneVec::with_capacity_in(inputs.len(), self.work);
+ for operand in inputs {
+ let node = self.read(*operand)?;
+ input_nodes.push(node);
+ }
+ let layout = self.function.layout;
+ let is_input_slot = |slot: &usize| {
+ inputs
+ .iter()
+ .any(|operand| layout.tracked_index(*operand) == Some(*slot))
+ };
+ let live_in = self.live_in(self.function.instruction_index);
// NB: A virtual arguments object stays virtual unless the slow path reads
// it; codegen creates it if the slow path leaves the compiled code.
- let mut read_slots = Vec::new();
- let mut written_slots = Vec::new();
+ let mut read_slots = self.slot_list();
+ let mut written_slots = self.slot_list();
instruction.for_each_operand(|operand, role| {
if role.is_read() && Some(operand) != forwarded {
- read_slots.extend(
- self.function
- .layout
- .tracked_index(operand)
- .filter(|slot| !input_slots.contains(slot)),
- );
+ read_slots.extend(layout.tracked_index(operand).filter(|slot| !is_input_slot(slot)));
}
if role.is_written() {
- written_slots.extend(self.function.layout.tracked_index(operand));
+ written_slots.extend(layout.tracked_index(operand));
}
});
// NB: The slow path reads its operands from the frame, and a slot it
@@ -2111,16 +2214,9 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
// frame state gives the destination its old value where the call
// does not continue (see `ir::FrameState::in_frame`).
let value_is_result = !input_nodes.is_empty() && matches!(op, Op::CallDirect { .. } | Op::CallNative { .. });
- let operand_slots = read_slots
- .iter()
- .copied()
- .chain(
- written_slots
- .iter()
- .copied()
- .filter(|slot| live_in.contains(*slot) && !value_is_result),
- )
- .collect::<Vec<_>>();
+ let is_operand_slot = |slot: &usize| {
+ read_slots.contains(slot) || (written_slots.contains(slot) && live_in.contains(*slot) && !value_is_result)
+ };
// NB: Calls in inlined callees run in the published frames of the
// inlined calls (see `SiteKind::Publish`), which take all their
// operands as inputs. Nothing else reads the frames of inlined
@@ -2132,26 +2228,26 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
reason: "reads the frame of an inlined callee",
});
}
- let out_of_sync = (0..self.frame.slots.len())
- .filter(|slot| {
- let SlotState { node, in_sync } = self.frame.slots[*slot];
- let needed = if writes_only_operands {
- operand_slots.contains(slot)
- } else {
- info.reads_whole_frame || live_in.contains(*slot)
- };
- !in_sync
- && needed
- && (!self.is_virtual_arguments(node) || info.reads_whole_frame || read_slots.contains(slot))
- })
- .collect::<Vec<_>>();
- for slot in out_of_sync {
- self.sync_slot(slot);
+ // NB: Syncing a slot changes no other slot, so each one can be synced as soon as it is found to need it.
+ for slot in 0..self.frame.slots.len() {
+ let SlotState { node, in_sync } = self.frame.slots[slot];
+ let needed = if writes_only_operands {
+ is_operand_slot(&slot)
+ } else {
+ info.reads_whole_frame || live_in.contains(slot)
+ };
+ if !in_sync
+ && needed
+ && (!self.is_virtual_arguments(node) || info.reads_whole_frame || read_slots.contains(&slot))
+ {
+ self.sync_slot(slot);
+ }
}
+ self.release_slot_set(live_in);
+ self.release_slot_list(read_slots);
- let mut targets = Vec::new();
- instruction.for_each_jump_target(|label| targets.push(label));
- let is_conditional_jump = !targets.is_empty();
+ let mut is_conditional_jump = false;
+ instruction.for_each_jump_target(|_| is_conditional_jump = true);
let repr = if is_conditional_jump {
Some(Repr::Int32)
} else {
@@ -2169,15 +2265,19 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
// continue, they hold what it wrote, or their old values, which the frame holds too (see above), so its
// frame state lists them as held by the frame. Where it continues, they are loaded from there. Written
// constants live in frame memory, where the slow path writes them.
- let frame_outputs = if value_is_result { Vec::new() } else { written_slots };
+ if value_is_result {
+ written_slots.clear();
+ }
+ let frame_outputs = written_slots;
for slot in &frame_outputs {
self.frame.slots[*slot].in_sync = true;
}
let frame_state = self.resume_after_frame_state(destination.map_or(Operand::INVALID, Operand::raw));
self.graph.nodes[node.index()].frame_state = Some(frame_state);
- for slot in frame_outputs {
+ for &slot in &frame_outputs {
self.load_slot(slot);
}
+ self.release_slot_list(frame_outputs);
if value_is_result && let Some(destination) = destination {
self.write(destination, node)?;
}
@@ -2207,7 +2307,7 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
if_true,
if_false,
},
- vec![node],
+ &[node],
if_true,
if_false,
)?;
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
index ac44a74c34a..c5c3bf19e60 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs
@@ -44,6 +44,7 @@ use crate::bytecode::OpCode;
use crate::bytecode::cfg::BlockIndex;
use crate::bytecode::cfg::Loop;
use crate::ir::BlockId;
+use ak::ZoneVec;
/// Whether instructions with this opcode are loop back edges, which count
/// loop iterations in the interpreter.
@@ -74,7 +75,7 @@ pub(crate) fn is_loop_back_edge(opcode: OpCode) -> bool {
)
}
-impl GraphBuilder<'_, '_> {
+impl<'a> GraphBuilder<'a, '_> {
/// Whether the instruction with the given index is a back edge that an on-stack replacement entry can be built at.
pub(super) fn can_build_osr_entry(&self, index: usize) -> bool {
let pc = self.function.instructions[index].pc;
@@ -94,6 +95,7 @@ impl GraphBuilder<'_, '_> {
/// started.
pub(super) fn build_osr_entries(&mut self) -> Result<(), CompileFailure> {
debug_assert!(!self.function.is_virtual());
+ let mut targets = ZoneVec::new_in(self.work);
for index in 0..self.function.instructions.len() {
let pc = self.function.instructions[index].pc;
if (self.snapshot.options.osr_pc != Some(pc) && !self.snapshot.options.stress.osr_at_every_loop)
@@ -118,7 +120,7 @@ impl GraphBuilder<'_, '_> {
.cfg
.block_for_pc(pc)
.filter(|block| opcode != OpCode::JumpLoop && self.function.cfg.blocks[*block].start_pc == pc);
- let mut targets = Vec::new();
+ targets.clear();
if let Some(own_block) = own_block {
self.end_with_jump(own_block)?;
targets.push(own_block);
@@ -240,14 +242,16 @@ impl GraphBuilder<'_, '_> {
/// Starts an entry block into a frame that is running at the instruction with the given index: a block without
/// predecessors that loads every slot live there from the frame, whose memory holds them all.
fn start_entry_block(&mut self, index: usize) -> BlockId {
- let block = self.start_new_block(Vec::new());
+ let block = self.start_new_block(&[]);
self.frame = self.dead_frame();
self.function.instruction_index = index;
self.function.pc = self.function.instructions[index].pc;
self.function.eager_frame_state = None;
- for slot in self.function.liveness.live_in(index).iter() {
+ let live = self.live_in(index);
+ for slot in live.iter() {
self.load_slot(slot);
}
+ self.release_slot_set(live);
block
}
@@ -287,7 +291,7 @@ impl GraphBuilder<'_, '_> {
/// other back edges of the loops around that loop, from where a frame may
/// reach the entry on a later iteration.
fn record_osr_loop_back_edges(&mut self, pc: u32) {
- let cfg = &self.function.cfg;
+ let cfg = self.function.cfg;
let Some(back_edge_block) = cfg.block_for_pc(pc) else {
return;
};
@@ -302,14 +306,14 @@ impl GraphBuilder<'_, '_> {
else {
return;
};
- let back_edges_in = |current_loop: &Loop| {
+ let instructions = self.function.instructions;
+ let back_edges_in = |current_loop: &'a Loop<'a>| {
current_loop
.blocks
.iter()
- .flat_map(|&block| &self.function.instructions[cfg.blocks[block].instructions.clone()])
+ .flat_map(|&block| &instructions[cfg.blocks[block].instructions.clone()])
.filter(|instruction| is_loop_back_edge(instruction.instruction.opcode()))
.map(|instruction| instruction.pc)
- .collect::<Vec<_>>()
};
for back_edge_pc in back_edges_in(entered_loop) {
if !self.graph.osr_loop_back_edges.contains(&back_edge_pc) {
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
index c7e73a71040..e6966d274e8 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs
@@ -642,14 +642,16 @@ impl<'z> GraphBuilder<'_, 'z> {
/// A register other than `operands` that is dead after the current
/// instruction: nothing reads it before writing it again.
- fn dead_register(&self, operands: &[Operand]) -> Option<Operand> {
+ fn dead_register(&mut self, operands: &[Operand]) -> Option<Operand> {
let layout = self.function.layout;
- let live = self.function.liveness.live_out(self.function.instruction_index);
- (crate::bytecode::RESERVED_REGISTER_COUNT..layout.number_of_registers)
+ let live = self.live_out(self.function.instruction_index);
+ let register = (crate::bytecode::RESERVED_REGISTER_COUNT..layout.number_of_registers)
.map(Operand::from_raw)
.find(|register| {
!operands.contains(register) && layout.tracked_index(*register).is_some_and(|slot| !live.contains(slot))
- })
+ });
+ self.release_slot_set(live);
+ register
}
/// Builds `dst = base[property]` for a string or symbol key from the
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs
index ce14b2ec30a..1e7da9d8739 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs
@@ -775,7 +775,7 @@ impl GraphBuilder<'_, '_> {
if_true,
if_false,
},
- vec![result],
+ &[result],
if_true,
if_false,
)?;
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index 3bebb1c3852..56e1cef7172 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -90,8 +90,10 @@ fn executable_analyses_are_lazy_and_borrowed_by_independent_walks() {
decoded,
decoded_function(&snapshot, executable, &cache).unwrap()
));
- let mut first = Function::new(&snapshot, 0, decoded, false).unwrap();
- let second = Function::new(&snapshot, 0, decoded, false).unwrap();
+ let mut first = Function::new(&snapshot, 0, decoded, false, crate::test_zone()).unwrap();
+ first.start_walk();
+ let mut second = Function::new(&snapshot, 0, decoded, false, crate::test_zone()).unwrap();
+ second.start_walk();
assert!(std::ptr::eq(first.cfg, second.cfg));
assert!(std::ptr::eq(first.liveness, second.liveness));
assert_eq!(first.instructions.as_ptr(), second.instructions.as_ptr());
@@ -108,15 +110,20 @@ fn cached_liveness_keeps_legacy_arguments_only_for_inlined_walks() {
let executable = &snapshot.executables[0];
let cache = OnceCell::new();
let decoded = decoded_function(&snapshot, executable, &cache).unwrap();
- let first = Function::new(&snapshot, 0, decoded, first_mode).unwrap();
- let second = Function::new(&snapshot, 0, decoded, !first_mode).unwrap();
+ let first = Function::new(&snapshot, 0, decoded, first_mode, crate::test_zone()).unwrap();
+ let second = Function::new(&snapshot, 0, decoded, !first_mode, crate::test_zone()).unwrap();
+ let live_in = |function: &Function<'_>, slot| {
+ let mut live = crate::bitset::ZoneBitSet::new_in(0, crate::test_zone());
+ function.liveness.live_in(0, &mut live);
+ live.contains(slot)
+ };
assert!(std::ptr::eq(first.cfg, second.cfg));
let argument_slot = layout
.tracked_index(Operand::from_raw(layout.arguments_base()))
.unwrap();
- assert_eq!(first.liveness.live_in(0).contains(argument_slot), first_mode);
- assert_eq!(second.liveness.live_in(0).contains(argument_slot), !first_mode);
- let repeated = Function::new(&snapshot, 0, decoded, first_mode).unwrap();
+ assert_eq!(live_in(&first, argument_slot), first_mode);
+ assert_eq!(live_in(&second, argument_slot), !first_mode);
+ let repeated = Function::new(&snapshot, 0, decoded, first_mode, crate::test_zone()).unwrap();
assert!(std::ptr::eq(first.liveness, repeated.liveness));
}
}
@@ -344,36 +351,40 @@ fn writes_to_constant_operands_go_to_the_frame() {
#[test]
fn loop_headers_inside_a_loop_body_add_their_phis_to_it() {
- use crate::bitset::BitSet;
+ use crate::bitset::ZoneBitSet;
use crate::bytecode::cfg::Cfg;
use crate::bytecode::cfg::Loop;
+ let zone = crate::test_zone();
// Loop 1's header lies in loop 0's body, but loop 1 extends outside it,
// as `finally` dispatch can make happen. Loop 1 assigns slot 7.
let assigned = |slots: &[usize]| {
- let mut set = BitSet::new(10);
+ let mut set = ZoneBitSet::new_in(10, zone);
slots.iter().for_each(|slot| set.insert(*slot));
set
};
let cfg = Cfg {
- blocks: Vec::new(),
- reverse_post_order: Vec::new(),
- loops: vec![
- Loop {
- header: 1,
- back_edge_sources: vec![3],
- blocks: vec![1, 2, 3],
- assigned_slots: assigned(&[5]),
- },
- Loop {
- header: 2,
- back_edge_sources: vec![4],
- blocks: vec![0, 2, 4],
- assigned_slots: assigned(&[7]),
- },
- ],
+ blocks: ZoneVec::new_in(zone),
+ reverse_post_order: ZoneVec::new_in(zone),
+ loops: ZoneVec::from_iter_in(
+ [
+ Loop {
+ header: 1,
+ back_edge_sources: ZoneVec::from_slice_in(&[3], zone),
+ blocks: ZoneVec::from_slice_in(&[1, 2, 3], zone),
+ assigned_slots: assigned(&[5]),
+ },
+ Loop {
+ header: 2,
+ back_edge_sources: ZoneVec::from_slice_in(&[4], zone),
+ blocks: ZoneVec::from_slice_in(&[0, 2, 4], zone),
+ assigned_slots: assigned(&[7]),
+ },
+ ],
+ zone,
+ ),
};
- let slots = loop_phi_slots(&cfg);
+ let slots = loop_phi_slots(&cfg, zone);
assert_eq!(slots[0].iter().collect::<Vec<_>>(), [5, 7]);
assert_eq!(slots[1].iter().collect::<Vec<_>>(), [7]);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
index af7eb0aed9f..9619196177b 100644
--- a/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/cfg.rs
@@ -23,13 +23,15 @@ use super::FrameLayout;
use super::OpCode;
use super::Operand;
use super::THIS_VALUE_REGISTER;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
+use ak::Zone;
+use ak::ZoneVec;
use std::ops::Range;
pub type BlockIndex = usize;
#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct BasicBlock {
+pub struct BasicBlock<'w> {
/// Byte offset of the first instruction.
pub start_pc: u32,
/// Byte offset one past the last instruction.
@@ -37,20 +39,20 @@ pub struct BasicBlock {
/// Indices into the decoded instruction list.
pub instructions: Range<usize>,
/// Normal control flow successors, without duplicates.
- pub successors: Vec<BlockIndex>,
+ pub successors: ZoneVec<'w, BlockIndex>,
/// The block that receives exceptions thrown by instructions in this block.
pub exception_handler: Option<BlockIndex>,
/// Normal control flow predecessors, without duplicates.
- pub predecessors: Vec<BlockIndex>,
+ pub predecessors: ZoneVec<'w, BlockIndex>,
/// Blocks whose exceptions are handled by this block.
- pub exception_predecessors: Vec<BlockIndex>,
+ pub exception_predecessors: ZoneVec<'w, BlockIndex>,
/// Position in `Cfg::reverse_post_order`, or `None` if unreachable.
pub rpo_number: Option<u32>,
/// Index into `Cfg::loops` if this block is a loop header.
pub loop_index: Option<usize>,
}
-impl BasicBlock {
+impl BasicBlock<'_> {
pub fn predecessor_count(&self) -> usize {
self.predecessors.len()
}
@@ -62,16 +64,16 @@ impl BasicBlock {
/// A loop: a header (the target of one or more back edges) and its body.
#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Loop {
+pub struct Loop<'w> {
pub header: BlockIndex,
/// Sources of the back edges to the header.
- pub back_edge_sources: Vec<BlockIndex>,
+ pub back_edge_sources: ZoneVec<'w, BlockIndex>,
/// Blocks of the loop, including the header and nested loops, in increasing order.
- pub blocks: Vec<BlockIndex>,
+ pub blocks: ZoneVec<'w, BlockIndex>,
/// Tracked slots (see `FrameLayout::tracked_index()`) written by any
/// instruction in the loop, with the this value register where a
/// `ResolveThisBinding` writes it without naming it.
- pub assigned_slots: BitSet,
+ pub assigned_slots: ZoneBitSet<'w>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -83,24 +85,26 @@ pub enum CfgError {
}
#[derive(Debug, Clone)]
-pub struct Cfg {
+pub struct Cfg<'w> {
/// Blocks in bytecode order. Block 0 is the entry.
- pub blocks: Vec<BasicBlock>,
+ pub blocks: ZoneVec<'w, BasicBlock<'w>>,
/// Reachable blocks in reverse post order, starting with the entry.
- pub reverse_post_order: Vec<BlockIndex>,
- pub loops: Vec<Loop>,
+ pub reverse_post_order: ZoneVec<'w, BlockIndex>,
+ pub loops: ZoneVec<'w, Loop<'w>>,
}
-impl Cfg {
+impl<'w> Cfg<'w> {
+ /// The control flow graph of `instructions`, with its data in `work`.
pub fn new(
instructions: &[DecodedInstruction],
exception_handlers: &[ExceptionHandler],
layout: &FrameLayout,
+ work: &'w Zone,
) -> Result<Self, CfgError> {
let mut cfg = Self {
- blocks: Vec::new(),
- reverse_post_order: Vec::new(),
- loops: Vec::new(),
+ blocks: ZoneVec::new_in(work),
+ reverse_post_order: ZoneVec::new_in(work),
+ loops: ZoneVec::new_in(work),
};
if instructions.is_empty() {
return Ok(cfg);
@@ -134,7 +138,8 @@ impl Cfg {
.ok()
};
- let mut is_leader = vec![false; instructions.len()];
+ let zone = self.blocks.zone();
+ let mut is_leader = ZoneVec::from_elem_in(false, instructions.len(), zone);
is_leader[0] = true;
for (index, instruction) in instructions.iter().enumerate() {
let mut result = Ok(());
@@ -184,10 +189,10 @@ impl Cfg {
start_pc: instructions[start].pc,
end_pc: instructions[index - 1].next_pc(),
instructions: start..index,
- successors: Vec::new(),
+ successors: ZoneVec::new_in(zone),
exception_handler: None,
- predecessors: Vec::new(),
- exception_predecessors: Vec::new(),
+ predecessors: ZoneVec::new_in(zone),
+ exception_predecessors: ZoneVec::new_in(zone),
rpo_number: None,
loop_index: None,
});
@@ -201,17 +206,19 @@ impl Cfg {
instructions: &[DecodedInstruction],
exception_handlers: &[ExceptionHandler],
) -> Result<(), CfgError> {
+ let zone = self.blocks.zone();
+ let mut successors = ZoneVec::new_in(zone);
for block_index in 0..self.blocks.len() {
let block = &self.blocks[block_index];
let last = &instructions[block.instructions.end - 1];
- let mut successors = Vec::new();
+ successors.clear();
last.instruction
.for_each_jump_target(|target| successors.push(target.0));
if last.instruction.opcode().can_fall_through() && block_index + 1 < self.blocks.len() {
successors.push(last.next_pc());
}
- let mut successor_blocks = Vec::with_capacity(successors.len());
- for target in successors {
+ let mut successor_blocks = ZoneVec::with_capacity_in(successors.len(), zone);
+ for &target in &successors {
let successor = self
.block_for_pc(target)
.ok_or(CfgError::InvalidJumpTarget { pc: last.pc, target })?;
@@ -252,18 +259,18 @@ impl Cfg {
/// Computes the reverse post order with a depth first search from the
/// entry and returns the back edges (edges to a block on the DFS stack).
- fn compute_reverse_post_order(&mut self) -> Vec<(BlockIndex, BlockIndex)> {
+ fn compute_reverse_post_order(&mut self) -> ZoneVec<'w, (BlockIndex, BlockIndex)> {
#[derive(Clone, Copy, PartialEq, Eq)]
enum State {
Unvisited,
OnStack,
Done,
}
- let mut state = vec![State::Unvisited; self.blocks.len()];
- let mut post_order = Vec::with_capacity(self.blocks.len());
- let mut back_edges = Vec::new();
+ let zone = self.blocks.zone();
+ let mut state = ZoneVec::from_elem_in(State::Unvisited, self.blocks.len(), zone);
+ let mut back_edges = ZoneVec::new_in(zone);
// Each stack entry is a block and the index of the next successor to visit.
- let mut stack = vec![(0, 0)];
+ let mut stack = ZoneVec::from_slice_in(&[(0, 0)], zone);
state[0] = State::OnStack;
while let Some((block, next_successor)) = stack.last_mut() {
let block = *block;
@@ -280,12 +287,13 @@ impl Cfg {
},
None => {
state[block] = State::Done;
- post_order.push(block);
+ self.reverse_post_order.push(block);
stack.pop();
}
}
}
- self.reverse_post_order = post_order.into_iter().rev().collect();
+ // NB: The list holds the post order up to here.
+ self.reverse_post_order.reverse();
for (rpo_number, block) in self.reverse_post_order.iter().enumerate() {
self.blocks[*block].rpo_number = Some(u32::try_from(rpo_number).expect("block count fits in u32"));
}
@@ -296,30 +304,33 @@ impl Cfg {
&mut self,
instructions: &[DecodedInstruction],
layout: &FrameLayout,
- mut back_edges: Vec<(BlockIndex, BlockIndex)>,
+ mut back_edges: ZoneVec<'w, (BlockIndex, BlockIndex)>,
) {
+ let zone = self.blocks.zone();
back_edges.sort_by_key(|(source, header)| (self.blocks[*header].rpo_number, *source));
- let mut loops: Vec<Loop> = Vec::new();
- for (source, header) in back_edges {
+ let mut loops: ZoneVec<'w, Loop<'w>> = ZoneVec::new_in(zone);
+ for &(source, header) in &back_edges {
if let Some(existing) = loops.last_mut().filter(|existing| existing.header == header) {
existing.back_edge_sources.push(source);
} else {
loops.push(Loop {
header,
- back_edge_sources: vec![source],
- blocks: Vec::new(),
- assigned_slots: BitSet::new(layout.tracked_slot_count()),
+ back_edge_sources: ZoneVec::from_slice_in(&[source], zone),
+ blocks: ZoneVec::new_in(zone),
+ assigned_slots: ZoneBitSet::new_in(layout.tracked_slot_count(), zone),
});
}
}
let this_register = layout.tracked_index(Operand::from_raw(THIS_VALUE_REGISTER));
+ let mut in_loop = ZoneVec::from_elem_in(false, self.blocks.len(), zone);
+ let mut worklist = ZoneVec::new_in(zone);
for (loop_index, current_loop) in loops.iter_mut().enumerate() {
// The natural loop: the header plus every reachable block that
// reaches a back edge source without passing through the header.
- let mut in_loop = vec![false; self.blocks.len()];
+ in_loop.fill(false);
in_loop[current_loop.header] = true;
- let mut worklist = current_loop.back_edge_sources.clone();
+ worklist.assign(&current_loop.back_edge_sources);
while let Some(block) = worklist.pop() {
if in_loop[block] || self.blocks[block].rpo_number.is_none() {
continue;
@@ -328,7 +339,9 @@ impl Cfg {
let block = &self.blocks[block];
worklist.extend(block.predecessors.iter().chain(&block.exception_predecessors));
}
- current_loop.blocks = (0..self.blocks.len()).filter(|block| in_loop[*block]).collect();
+ current_loop
+ .blocks
+ .extend((0..self.blocks.len()).filter(|block| in_loop[*block]));
for block in &current_loop.blocks {
for instruction in &instructions[self.blocks[*block].instructions.clone()] {
@@ -547,7 +560,7 @@ mod tests {
]
});
let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();
- let error = Cfg::new(&instructions, &[], &test_layout()).unwrap_err();
+ let error = Cfg::new(&instructions, &[], &test_layout(), crate::test_zone()).unwrap_err();
assert!(matches!(error, CfgError::InvalidJumpTarget { pc: 0, .. }));
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/liveness.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/liveness.rs
index 7fead2e5ec2..471a8ded711 100644
--- a/Libraries/LibJS/JIT/Rust/src/bytecode/liveness.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/liveness.rs
@@ -21,7 +21,9 @@ use super::FrameLayout;
use super::RESERVED_REGISTER_COUNT;
use super::cfg::BasicBlock;
use super::cfg::Cfg;
-use crate::bitset::BitSet;
+use crate::bitset::ZoneBitSet;
+use ak::Zone;
+use ak::ZoneVec;
/// The live set after every this many instructions of a block, counted from its end, is kept, and the sets of the
/// instructions in between are computed again from it when asked for.
@@ -31,45 +33,47 @@ const CHECKPOINT_INTERVAL: usize = 64;
const NO_BLOCK: u32 = u32::MAX;
#[derive(Debug, Clone)]
-pub struct Liveness {
- transfers: Transfers,
+pub struct Liveness<'w> {
+ transfers: Transfers<'w>,
/// The block of each instruction, or `NO_BLOCK`.
- block_of_instruction: Vec<u32>,
+ block_of_instruction: ZoneVec<'w, u32>,
/// For each instruction, the index into `checkpoints` of the nearest one at or after it in its block, which holds
/// the instruction index and the slots live out of it.
- checkpoint_of_instruction: Vec<u32>,
- checkpoints: Vec<(usize, BitSet)>,
+ checkpoint_of_instruction: ZoneVec<'w, u32>,
+ checkpoints: ZoneVec<'w, (usize, ZoneBitSet<'w>)>,
}
/// What turns the slots live out of an instruction into those live into it.
#[derive(Debug, Clone)]
-struct Transfers {
- always_live: BitSet,
- block_live_in: Vec<BitSet>,
+struct Transfers<'w> {
+ always_live: ZoneBitSet<'w>,
+ block_live_in: ZoneVec<'w, ZoneBitSet<'w>>,
/// The exception handler of each block.
- exception_handlers: Vec<Option<usize>>,
+ exception_handlers: ZoneVec<'w, Option<usize>>,
/// The slots each instruction writes and then reads: those of instruction `i` are at
/// `slots[slot_starts[i].0..slot_starts[i].1]` and `slots[slot_starts[i].1..slot_starts[i + 1].0]`.
- slots: Vec<u32>,
- slot_starts: Vec<(u32, u32)>,
+ slots: ZoneVec<'w, u32>,
+ slot_starts: ZoneVec<'w, (u32, u32)>,
}
-impl Liveness {
+impl<'w> Liveness<'w> {
+ /// The liveness of the slots of `instructions`, with its data in `work`.
pub fn compute(
instructions: &[DecodedInstruction],
- cfg: &Cfg,
+ cfg: &Cfg<'_>,
layout: &FrameLayout,
has_legacy_arguments: bool,
+ work: &'w Zone,
) -> Self {
let slot_count = layout.tracked_slot_count();
- let mut always_live = BitSet::new(slot_count);
+ let mut always_live = ZoneBitSet::new_in(slot_count, work);
always_live.insert_range(0..(RESERVED_REGISTER_COUNT.min(layout.registers_and_locals_count) as usize));
if has_legacy_arguments {
always_live.insert_range(layout.registers_and_locals_count as usize..slot_count);
}
- let mut slots = Vec::new();
- let mut slot_starts = Vec::with_capacity(instructions.len() + 1);
+ let mut slots = ZoneVec::new_in(work);
+ let mut slot_starts = ZoneVec::with_capacity_in(instructions.len() + 1, work);
for instruction in instructions {
let start = slots.len() as u32;
for_each_written_slot(instruction, layout, |slot| slots.push(slot as u32));
@@ -80,11 +84,11 @@ impl Liveness {
slot_starts.push((slots.len() as u32, slots.len() as u32));
// Upward exposed uses and definitions of each block.
- let mut block_uses = Vec::with_capacity(cfg.blocks.len());
- let mut block_definitions = Vec::with_capacity(cfg.blocks.len());
+ let mut block_uses = ZoneVec::with_capacity_in(cfg.blocks.len(), work);
+ let mut block_definitions = ZoneVec::with_capacity_in(cfg.blocks.len(), work);
for block in &cfg.blocks {
- let mut uses = BitSet::new(slot_count);
- let mut definitions = BitSet::new(slot_count);
+ let mut uses = ZoneBitSet::new_in(slot_count, work);
+ let mut definitions = ZoneBitSet::new_in(slot_count, work);
for index in block.instructions.clone().rev() {
let (written, read) = instruction_slots(&slots, &slot_starts, index);
for slot in written {
@@ -101,20 +105,22 @@ impl Liveness {
// Iterate to a fixed point, visiting blocks in post order so that most
// successors are processed before their predecessors.
- let mut block_live_in = vec![always_live.clone(); cfg.blocks.len()];
- let post_order = cfg
- .reverse_post_order
- .iter()
- .rev()
- .copied()
- .chain((0..cfg.blocks.len()).filter(|block| cfg.blocks[*block].rpo_number.is_none()))
- .collect::<Vec<_>>();
+ let mut block_live_in = ZoneVec::from_elem_in(always_live.clone(), cfg.blocks.len(), work);
+ let post_order = ZoneVec::from_iter_in(
+ cfg.reverse_post_order
+ .iter()
+ .rev()
+ .copied()
+ .chain((0..cfg.blocks.len()).filter(|block| cfg.blocks[*block].rpo_number.is_none())),
+ work,
+ );
+ let mut live_in = ZoneBitSet::new_in(slot_count, work);
let mut changed = true;
while changed {
changed = false;
for &block_index in &post_order {
let block = &cfg.blocks[block_index];
- let mut live_in = block_live_out(block, &block_live_in, &always_live);
+ block_live_out(block, &block_live_in, &always_live, &mut live_in);
live_in.subtract(&block_definitions[block_index]);
live_in.union_with(&block_uses[block_index]);
if let Some(handler) = block.exception_handler {
@@ -130,15 +136,16 @@ impl Liveness {
let transfers = Transfers {
always_live,
block_live_in,
- exception_handlers: cfg.blocks.iter().map(|block| block.exception_handler).collect(),
+ exception_handlers: ZoneVec::from_iter_in(cfg.blocks.iter().map(|block| block.exception_handler), work),
slots,
slot_starts,
};
- let mut block_of_instruction = vec![NO_BLOCK; instructions.len()];
- let mut checkpoint_of_instruction = vec![0; instructions.len()];
- let mut checkpoints = Vec::new();
+ let mut block_of_instruction = ZoneVec::from_elem_in(NO_BLOCK, instructions.len(), work);
+ let mut checkpoint_of_instruction = ZoneVec::from_elem_in(0, instructions.len(), work);
+ let mut checkpoints = ZoneVec::new_in(work);
+ let mut live = live_in;
for (block_index, block) in cfg.blocks.iter().enumerate() {
- let mut live = block_live_out(block, &transfers.block_live_in, &transfers.always_live);
+ block_live_out(block, &transfers.block_live_in, &transfers.always_live, &mut live);
for (offset, index) in block.instructions.clone().rev().enumerate() {
block_of_instruction[index] = block_index as u32;
if offset % CHECKPOINT_INTERVAL == 0 {
@@ -156,44 +163,46 @@ impl Liveness {
}
}
- /// Slots live before the instruction with the given index executes.
- pub fn live_in(&self, instruction_index: usize) -> BitSet {
- let mut live = self.live_out(instruction_index);
+ /// Makes `live` the slots live before the instruction with the given index executes. `live` keeps its memory where
+ /// they fit.
+ pub fn live_in(&self, instruction_index: usize, live: &mut ZoneBitSet<'w>) {
+ self.live_out(instruction_index, live);
let block = self.block_of_instruction[instruction_index];
if block != NO_BLOCK {
- self.transfers.transfer(instruction_index, block as usize, &mut live);
+ self.transfers.transfer(instruction_index, block as usize, live);
}
- live
}
- /// Slots live after the instruction with the given index executes,
- /// including slots live into its exception handler.
- pub fn live_out(&self, instruction_index: usize) -> BitSet {
+ /// Makes `live` the slots live after the instruction with the given index executes, including slots live into its
+ /// exception handler. `live` keeps its memory where they fit.
+ pub fn live_out(&self, instruction_index: usize, live: &mut ZoneBitSet<'w>) {
let block = self.block_of_instruction[instruction_index];
if block == NO_BLOCK {
- return BitSet::new(self.transfers.always_live.capacity());
+ // NB: The set of always live slots has the capacity of every set.
+ live.clone_from(&self.transfers.always_live);
+ live.clear();
+ return;
}
let (checkpoint_index, checkpoint) =
&self.checkpoints[self.checkpoint_of_instruction[instruction_index] as usize];
- let mut live = checkpoint.clone();
+ live.clone_from(checkpoint);
if instruction_index < *checkpoint_index {
for index in (instruction_index + 1..=*checkpoint_index).rev() {
- self.transfers.transfer_slots(index, &mut live);
+ self.transfers.transfer_slots(index, live);
}
- self.transfers.add_slots_live_throughout(block as usize, &mut live);
+ self.transfers.add_slots_live_throughout(block as usize, live);
}
- live
}
}
-impl Transfers {
+impl<'w> Transfers<'w> {
/// Turns the slots live out of an instruction into those live into it.
- fn transfer(&self, index: usize, block: usize, live: &mut BitSet) {
+ fn transfer(&self, index: usize, block: usize, live: &mut ZoneBitSet<'w>) {
self.transfer_slots(index, live);
self.add_slots_live_throughout(block, live);
}
- fn transfer_slots(&self, index: usize, live: &mut BitSet) {
+ fn transfer_slots(&self, index: usize, live: &mut ZoneBitSet<'w>) {
let (written, read) = instruction_slots(&self.slots, &self.slot_starts, index);
for slot in written {
live.remove(*slot as usize);
@@ -205,7 +214,7 @@ impl Transfers {
/// Adds the slots live into and out of every instruction of the block: those always live and those live into its
/// exception handler. Transfers of several instructions in a row need to add them only once, at the end.
- fn add_slots_live_throughout(&self, block: usize, live: &mut BitSet) {
+ fn add_slots_live_throughout(&self, block: usize, live: &mut ZoneBitSet<'w>) {
if let Some(handler) = self.exception_handlers[block] {
live.union_with(&self.block_live_in[handler]);
}
@@ -222,12 +231,17 @@ fn instruction_slots<'a>(slots: &'a [u32], slot_starts: &[(u32, u32)], index: us
)
}
-fn block_live_out(block: &BasicBlock, block_live_in: &[BitSet], always_live: &BitSet) -> BitSet {
- let mut live_out = always_live.clone();
+/// Makes `live_out` the slots live out of `block`.
+fn block_live_out<'w>(
+ block: &BasicBlock<'_>,
+ block_live_in: &[ZoneBitSet<'w>],
+ always_live: &ZoneBitSet<'w>,
+ live_out: &mut ZoneBitSet<'w>,
+) {
+ live_out.clone_from(always_live);
for successor in block.successors.iter().chain(&block.exception_handler) {
live_out.union_with(&block_live_in[*successor]);
}
- live_out
}
fn for_each_read_slot(instruction: &DecodedInstruction, layout: &FrameLayout, mut callback: impl FnMut(usize)) {
@@ -258,7 +272,7 @@ mod tests {
use crate::bytecode::Operand;
struct Analysis {
- liveness: Liveness,
+ liveness: Liveness<'static>,
layout: FrameLayout,
}
@@ -268,21 +282,25 @@ mod tests {
let instructions = program.instructions();
let cfg = program.cfg();
Self {
- liveness: Liveness::compute(&instructions, &cfg, &layout, false),
+ liveness: Liveness::compute(&instructions, &cfg, &layout, false, crate::test_zone()),
layout,
}
}
/// The live in set of an instruction, without the always live reserved registers.
fn live_in(&self, index: usize) -> Vec<Operand> {
- self.operands(&self.liveness.live_in(index))
+ let mut live = ZoneBitSet::new_in(0, crate::test_zone());
+ self.liveness.live_in(index, &mut live);
+ self.operands(&live)
}
fn live_out(&self, index: usize) -> Vec<Operand> {
- self.operands(&self.liveness.live_out(index))
+ let mut live = ZoneBitSet::new_in(0, crate::test_zone());
+ self.liveness.live_out(index, &mut live);
+ self.operands(&live)
}
- fn operands(&self, set: &BitSet) -> Vec<Operand> {
+ fn operands(&self, set: &ZoneBitSet<'_>) -> Vec<Operand> {
for reserved in 0..RESERVED_REGISTER_COUNT as usize {
assert!(set.contains(reserved), "reserved register {reserved} is not live");
}
@@ -341,7 +359,7 @@ mod tests {
});
let analysis = Analysis::new(&program);
let instructions = program.instructions();
- let mut live = BitSet::new(analysis.layout.tracked_slot_count());
+ let mut live = ZoneBitSet::new_in(analysis.layout.tracked_slot_count(), crate::test_zone());
live.insert_range(0..RESERVED_REGISTER_COUNT as usize);
for index in (0..instructions.len()).rev() {
assert_eq!(
diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs
index 2b85264b541..c3e689a3d6f 100644
--- a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs
@@ -169,8 +169,8 @@ pub(crate) mod test_support {
decode_all(&self.bytes).unwrap()
}
- pub fn cfg(&self) -> Cfg {
- Cfg::new(&self.instructions(), &self.handlers, &test_layout()).unwrap()
+ pub fn cfg(&self) -> Cfg<'static> {
+ Cfg::new(&self.instructions(), &self.handlers, &test_layout(), crate::test_zone()).unwrap()
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
index 1056b80768a..b0eccd402c4 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
@@ -2005,13 +2005,17 @@ mod execution {
assert_eq!(machine.program_counter(), pc, "seed {seed}");
// Every slot the interpreter can still read must be right.
let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();
- let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout).unwrap();
- let liveness = crate::bytecode::liveness::Liveness::compute(&instructions, &cfg, &layout, false);
+ let work = crate::test_work();
+ let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout, &work).unwrap();
+ let liveness =
+ crate::bytecode::liveness::Liveness::compute(&instructions, &cfg, &layout, false, &work);
let index = instructions
.iter()
.position(|instruction| instruction.pc == pc)
.unwrap();
- for slot in liveness.live_in(index).iter() {
+ let mut live = crate::bitset::ZoneBitSet::new_in(0, &work);
+ liveness.live_in(index, &mut live);
+ for slot in live.iter() {
let operand = layout.operand_for_tracked_index(slot);
assert_eq!(
machine.slot(operand),
@@ -2174,14 +2178,17 @@ mod execution {
) => {
assert_eq!(resumed_pc, *pc, "seed {seed}: resumed exit");
let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();
- let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout).unwrap();
+ let work = crate::test_work();
+ let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout, &work).unwrap();
let liveness =
- crate::bytecode::liveness::Liveness::compute(&instructions, &cfg, &layout, false);
+ crate::bytecode::liveness::Liveness::compute(&instructions, &cfg, &layout, false, &work);
let index = instructions
.iter()
.position(|instruction| instruction.pc == *pc)
.unwrap();
- for slot in liveness.live_in(index).iter() {
+ let mut live = crate::bitset::ZoneBitSet::new_in(0, &work);
+ liveness.live_in(index, &mut live);
+ for slot in live.iter() {
let slot = layout.operand_for_tracked_index(slot).raw() as usize;
assert_eq!(resumed_slots[slot], slots[slot], "seed {seed}: slot {slot} at pc {pc}");
}
@@ -2203,13 +2210,17 @@ mod execution {
assert_eq!(result.status, RESUME, "seed {seed}");
assert_eq!(machine.program_counter(), pc, "seed {seed}");
let instructions = crate::bytecode::decode_all(&program.bytes).unwrap();
- let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout).unwrap();
- let liveness = crate::bytecode::liveness::Liveness::compute(&instructions, &cfg, &layout, false);
+ let work = crate::test_work();
+ let cfg = crate::bytecode::cfg::Cfg::new(&instructions, &[], &layout, &work).unwrap();
+ let liveness =
+ crate::bytecode::liveness::Liveness::compute(&instructions, &cfg, &layout, false, &work);
let index = instructions
.iter()
.position(|instruction| instruction.pc == pc)
.unwrap();
- for slot in liveness.live_in(index).iter() {
+ let mut live = crate::bitset::ZoneBitSet::new_in(0, &work);
+ liveness.live_in(index, &mut live);
+ for slot in live.iter() {
let operand = layout.operand_for_tracked_index(slot);
assert_eq!(
machine.slot(operand),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 7b4518613eb..f4d1f58e0a4 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -1695,7 +1695,7 @@ pub struct Graph<'z> {
/// wherever its code runs: the arguments and the `this` value register, unless an instruction writes them. Nothing
/// stores to them (the verifier enforces this), so the register allocator reloads what was loaded from them from
/// there (see `regalloc::frame_home()`).
- pub unwritten_slots: crate::bitset::BitSet,
+ pub unwritten_slots: crate::bitset::ZoneBitSet<'z>,
}
impl<'z> Graph<'z> {
@@ -1721,7 +1721,7 @@ impl<'z> Graph<'z> {
speculatively_hoisted: ZoneVec::new_in(zone),
legacy_arguments: 0..0,
legacy_arguments_guards: ZoneVec::new_in(zone),
- unwritten_slots: crate::bitset::BitSet::default(),
+ unwritten_slots: crate::bitset::ZoneBitSet::new_in(0, zone),
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rs
index 464cbc58236..6772246d04b 100644
--- a/Libraries/LibJS/JIT/Rust/src/lib.rs
+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs
@@ -143,15 +143,16 @@ fn run_stages<M: asm::PortableMacroAssembler>(
let Scratch { zone, work, tables } = scratch;
// NB: Nothing of the compile before this one is in use (see `Scratch`).
work.reset();
- let mut attempts = builder::Attempts::new(snapshot, has_run, work);
- let mut graph = loop {
- // NB: This drops the graph of the compile before this one, and a graph that the builder gave up.
- zone.reset();
- if let Some(graph) = attempts.build(zone)? {
- break graph;
+ let mut graph = {
+ let attempts = builder::Attempts::new(snapshot, has_run, work);
+ loop {
+ // NB: This drops the graph of the compile before this one, and a graph that the builder gave up.
+ zone.reset();
+ if let Some(graph) = attempts.build(zone)? {
+ break graph;
+ }
}
};
- drop(attempts);
// NB: The builder is done, and nothing of the graph is in its work data.
work.reset();
let executable = &snapshot.executables[0];
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
index afa33397737..139ce31180d 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
@@ -362,7 +362,7 @@ fn loads_of_slots_that_nothing_writes_move_out_of_loops_that_call() {
..Block::default()
});
}
- graph.unwritten_slots = crate::bitset::BitSet::new(8);
+ graph.unwritten_slots = crate::bitset::ZoneBitSet::new_in(8, graph.zone);
graph.unwritten_slots.insert(7);
let enter = node(&mut graph, Op::Jump { target: BlockId(1) }, vec![], None);
graph.blocks[0].control = Some(enter);
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index 985b9796b77..048f5a97c9c 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -820,7 +820,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();
- written.unwritten_slots = crate::bitset::BitSet::new(0);
+ written.unwritten_slots = crate::bitset::ZoneBitSet::new_in(0, written.zone);
assert!(verify(&written, &registers, &allocation).is_err());
// Another frame slot holds another value.