Skip to content

Truly independent web browser

LibJS/JIT: Allocate rope strings through the runtime when out of cells

Andreas Klingb067220e47c0
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
index e181aa98ad6..dbc7f04157b 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
@@ -26,7 +26,7 @@ use crate::snapshot::CellId;
/// The runtime call that allocates what an allocation node allocates.
#[derive(Clone, Copy)]
-enum AllocationCall {
+pub(super) enum AllocationCall {
/// `ObjectAllocationInfo::slow_path` with the shape and the properties
/// to make room for.
Object(CellId, u32),
@@ -38,6 +38,9 @@ enum AllocationCall {
/// `RuntimeInfo::create_lexical_environment` with the parent in the
/// node's input, the environment shape cache and the capacity.
Environment(u32, u32),
+ /// `RopeAllocationInfo::slow_path` with the strings in the node's
+ /// inputs.
+ Rope,
}
/// The out of line part of an allocation: the runtime call.
@@ -89,7 +92,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// The entry and resume labels of the out-of-line call that allocates
/// for `node` where its inline allocation cannot (see
/// `emit_deferred_allocations()`).
- fn defer_allocation(&mut self, node: NodeId, call: AllocationCall) -> (Label, Label) {
+ pub(super) fn defer_allocation(&mut self, node: NodeId, call: AllocationCall) -> (Label, Label) {
let entry = self.masm.new_label();
let resume = self.masm.new_label();
self.deferred_allocations.push(DeferredAllocation {
@@ -239,6 +242,16 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.move_imm32(arguments[4], capacity);
self.masm.call_absolute(self.runtime.create_lexical_environment);
}
+ AllocationCall::Rope => {
+ // NB: Each input is read before the argument register
+ // that may hold it is written.
+ let scratch = self.pinned.scratch;
+ self.emit_unbox_cell(scratch, self.input(allocation.node, 1));
+ self.emit_unbox_cell(arguments[1], self.input(allocation.node, 0));
+ self.masm.move64(arguments[2], scratch);
+ self.masm.move64(arguments[0], self.pinned.vm);
+ self.masm.call_absolute(self.runtime.rope_allocation.slow_path);
+ }
}
for (offset, bits) in &allocation.constant_fields {
self.masm.move_imm64(self.pinned.scratch, *bits);
@@ -246,10 +259,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
.store64(&Address::new(M::RETURN_GPRS[0], *offset as i32), self.pinned.scratch);
}
self.masm.move64(output, M::RETURN_GPRS[0]);
- if let AllocationCall::Environment(..) = allocation.call {
- self.box_cell(output, output);
- } else {
- self.box_object(output);
+ match allocation.call {
+ AllocationCall::Environment(..) => self.box_cell(output, output),
+ AllocationCall::Rope => self.box_cell_with_tag(output, output, value::STRING_TAG),
+ _ => self.box_object(output),
}
self.emit_restore_registers(&saved, None);
self.masm.jump(allocation.resume);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs
index cba69e9bb17..f70ae7458c3 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs
@@ -6,13 +6,16 @@
//! Lowering of `ConcatenateStrings` and `IntegerToString`. Two strings make
//! a rope string, allocated inline per the allocation contract (see
-//! `RopeAllocationInfo`), unless one of them is empty (then the result is
-//! the other one). Concatenations short enough to become short flat strings
-//! (whose ASCII bytes are in their storage word) find them in the VM's cache
-//! of fly strings if both strings are short. Everything else results in the
-//! empty value, for the slow path, which also fills that cache.
+//! `RopeAllocationInfo`), or by a call of the runtime out of line where
+//! there is no local free cell, unless one of them is empty (then the
+//! result is the other one). Concatenations short enough to become short
+//! flat strings (whose ASCII bytes are in their storage word) find them in
+//! the VM's cache of fly strings if both strings are short. Everything else
+//! results in the empty value, for the slow path, which also fills that
+//! cache.
use super::Codegen;
+use super::allocation::AllocationCall;
use super::call::ConstantField;
use crate::asm::Address;
use crate::asm::Condition;
@@ -31,12 +34,23 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let temps = &self.allocation.node(node).temps;
let temps = [Gpr(temps[0]), Gpr(temps[1]), Gpr(temps[2])];
let (slow, done) = (self.masm.new_label(), self.masm.new_label());
+ let mut resume = None;
if self.runtime.rope_allocation.allocator != 0 && self.rope_template_fits() {
- self.emit_concatenation_of_strings(node, [lhs, rhs], temps, slow, done);
+ let no_free_cell = if self.runtime.rope_allocation.slow_path != 0 {
+ let (entry, resume_label) = self.defer_allocation(node, AllocationCall::Rope);
+ resume = Some(resume_label);
+ entry
+ } else {
+ slow
+ };
+ self.emit_concatenation_of_strings(node, [lhs, rhs], temps, no_free_cell, slow, done);
}
self.masm.bind(slow);
self.masm.move_imm64(output, value::EMPTY);
self.masm.bind(done);
+ if let Some(resume) = resume {
+ self.masm.bind(resume);
+ }
}
/// `IntegerToString`: the VM's string of an int32, as
@@ -84,12 +98,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// The concatenation of the strings `lhs` and `rhs` into the node's
/// output, continuing at `done`, with the temps `cell`, `other` and
- /// `length`.
+ /// `length`. Branches to `no_free_cell` where the rope string's cell
+ /// cannot be allocated inline.
fn emit_concatenation_of_strings(
&mut self,
node: NodeId,
[lhs, rhs]: [Gpr; 2],
[cell, other, length]: [Gpr; 3],
+ no_free_cell: Label,
slow: Label,
done: Label,
) {
@@ -128,8 +144,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.branch_test64(Condition::NonZero, scratch, u64::MAX, slow);
// The cell, per the allocation contract.
- self.emit_check_heap_threshold(rope.cell_size, cell, other, slow);
- self.emit_pop_free_list(rope.allocator, cell, other, slow);
+ self.emit_check_heap_threshold(rope.cell_size, cell, other, no_free_cell);
+ self.emit_pop_free_list(rope.allocator, cell, other, no_free_cell);
self.emit_count_allocation(rope.cell_size, rope.cell_size, other, false);
let mut fields: Vec<ConstantField> = (0u32..)
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
index cb2ba0cf5f5..93286daab81 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
@@ -3700,6 +3700,7 @@ fn short_string_concatenations_through_the_fly_string_cache() {
rhs_offset: 40,
length_offset: 16,
min_length: 8,
+ slow_path: 0,
};
snapshot.runtime.layout.fly_string_cache = cache_address;
snapshot.runtime.layout.fly_string_cache_mask = 1023;
@@ -4198,3 +4199,99 @@ fn in_of_array_elements() {
assert_eq!(has(value::UNDEFINED, holey.value()), MARKER);
assert_eq!(has(value::int32(0), value::int32(0)), MARKER);
}
+
+/// The words of the fake VM that the fake rope string slow path records
+/// its strings in.
+const VM_ROPE_STRINGS_WORDS: [usize; 2] = [10, 11];
+
+/// The fake `RopeAllocationInfo::slow_path`: records its strings, and
+/// returns `ROPE_FROM_RUNTIME`.
+extern "C" fn fake_create_rope_string(vm: *mut u64, lhs: u64, rhs: u64) -> u64 {
+ // SAFETY: The fake VM has room for the words the fakes here use.
+ unsafe {
+ vm.add(VM_ROPE_STRINGS_WORDS[0]).write(lhs);
+ vm.add(VM_ROPE_STRINGS_WORDS[1]).write(rhs);
+ }
+ ROPE_FROM_RUNTIME
+}
+
+/// The cell pointer the fake rope string slow path returns.
+const ROPE_FROM_RUNTIME: u64 = 0x7654_3210;
+
+#[test]
+fn rope_strings_come_from_the_runtime_without_a_local_free_cell() {
+ // A fake heap (allocated, threshold and total bytes), and a block whose
+ // one cell is the only never-allocated cell, if `free`.
+ let concatenate = |lhs: u64, rhs: u64, threshold: u64, free: bool| {
+ let mut heap = vec![100u64, threshold, 1000];
+ let block = FakeBlock::new(8, 0);
+ let address = block.cell().as_ptr() as u64;
+ // NB: The head of the free list, then the cursor, the end and the cell size of the never-allocated cells.
+ let mut free_list = if free {
+ vec![0, address, address + 64, 64]
+ } else {
+ vec![0, 0, 0, 64]
+ };
+ let program = assemble(|_| {
+ vec![
+ Instruction::Enter,
+ Instruction::Add {
+ arith_feedback: 0,
+ dst: r(5),
+ lhs: argument(0),
+ rhs: argument(1),
+ },
+ Instruction::Return { value: r(5) },
+ ]
+ });
+ let (result, machine) = run_program_with_snapshot(
+ &program,
+ &[lhs, rhs],
+ |snapshot| {
+ snapshot.runtime.rope_allocation = crate::snapshot::RopeAllocationInfo {
+ allocator: free_list.as_mut_ptr() as u64,
+ cell_size: 64,
+ template: vec![0x1234; 8],
+ lhs_offset: 32,
+ rhs_offset: 40,
+ length_offset: 16,
+ min_length: 8,
+ slow_path: fake_create_rope_string as *const () as u64,
+ };
+ let allocation = &mut snapshot.runtime.object_allocation;
+ allocation.heap = heap.as_mut_ptr() as u64;
+ allocation.heap_allocated_bytes_offset = 0;
+ allocation.heap_threshold_offset = 8;
+ allocation.heap_total_allocated_bytes_offset = 16;
+ allocation.local_free_list_offset = 0;
+ allocation.freelist_next_offset = 0;
+ allocation.freelist_link_mask = FakeBlock::LINK_MASK;
+ allocation.local_cursor_offset = 8;
+ allocation.local_end_offset = 16;
+ allocation.local_cell_size_offset = 24;
+ // ArithFeedback::String.
+ snapshot.executables[0].feedback.arith = vec![1 << 3];
+ },
+ |_| {},
+ );
+ assert_eq!(result.status, RETURNED);
+ let strings = VM_ROPE_STRINGS_WORDS.map(|word| machine.vm[word]);
+ (result.value, strings, block.cell()[..6].to_vec(), address)
+ };
+ let pointer = |string: u64| string & ((1 << 48) - 1);
+ let string = |pointer: u64| u64::from(STRING_TAG) << 48 | pointer;
+ let (lhs, rhs) = (fake_string_of_length(5, 0), fake_string_of_length(4, 0));
+
+ // A local free cell becomes the rope string.
+ let (result, strings, cell, address) = concatenate(lhs, rhs, 10_000, true);
+ assert_eq!((result, strings), (string(address), [0, 0]));
+ assert_eq!(cell, [0x1234, 0x1234, 9, 0x1234, pointer(lhs), pointer(rhs)]);
+
+ // Without one, or without room before the next collection, the runtime
+ // makes it.
+ for (threshold, free) in [(10_000, false), (150, true)] {
+ let (result, strings, _, _) = concatenate(lhs, rhs, threshold, free);
+ assert_eq!(result, string(ROPE_FROM_RUNTIME));
+ assert_eq!(strings, [pointer(lhs), pointer(rhs)]);
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 04bab7d27ef..51dfdf9a074 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -1033,8 +1033,9 @@ pub enum Op {
StringsEqual,
/// The concatenation of the strings 0 and 1, or the empty value where
/// only the slow path makes it. An empty string concatenates to the
- /// other one; a rope string is allocated inline (see
- /// `RopeAllocationInfo`), but for results short enough to be short
+ /// other one; a rope string is allocated inline, or by the runtime where
+ /// there is no local free cell (see `RopeAllocationInfo`), but for
+ /// results short enough to be short
/// strings, which come from the VM's cache of fly strings (when both
/// strings are short).
ConcatenateStrings,
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index ed2e991731d..a248ff9aef0 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -115,6 +115,7 @@ pub fn saves_only_gprs(op: &Op) -> bool {
| Op::AllocateArray { .. }
| Op::AllocateFunction { .. }
| Op::AllocateEnvironment { .. }
+ | Op::ConcatenateStrings
)
}
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 43b97a59bf3..2c1f93e74da 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -1268,7 +1268,11 @@ impl ObjectAllocationInfo {
/// `template` (`8 * template.len()` bytes) to it, and stores the length
/// (u32) at `cell + length_offset` and the halves (cell pointers) at
/// `cell + lhs_offset` and `cell + rhs_offset`. If `allocator` is 0, there is
-/// no fast path. The slow path is the interpreter's.
+/// no fast path. Where there is no local free cell or the heap wants to
+/// collect garbage, JIT code calls
+/// `PrimitiveString* slow_path(VM*, PrimitiveString* lhs, PrimitiveString* rhs)`
+/// instead, which returns the rope string; if `slow_path` is 0, the
+/// interpreter's slow path concatenates the strings.
#[derive(Debug, Clone, Default)]
pub struct RopeAllocationInfo {
/// The `GC::CellAllocator` of rope strings.
@@ -1280,6 +1284,7 @@ pub struct RopeAllocationInfo {
pub rhs_offset: u32,
pub length_offset: u32,
pub min_length: u32,
+ pub slow_path: u64,
}
/// The allocation contract for arrays with packed elements (`JS::Array`
diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rs
index 842a0b31887..9b93bd83862 100644
--- a/Libraries/LibJS/Rust/src/jit/allocation.rs
+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs
@@ -163,6 +163,7 @@ pub fn allocation_infos(vm: &Vm, realm: Gc<Realm>) -> AllocationInfos {
rhs_offset: offset(ROPE_STRING_RHS_OFFSET),
length_offset: offset(core::mem::offset_of!(PrimitiveString, length_in_utf16_code_units)),
min_length: ROPE_STRING_MIN_LENGTH,
+ slow_path: libjs_jit_create_rope_string as *const () as u64,
};
let function = FunctionAllocationInfo {
@@ -509,6 +510,19 @@ pub extern "C" fn libjs_jit_allocate_object(vm: &Vm, shape: Gc<Shape>, reserve:
Object::create_with_premade_shape_and_reserve(vm, shape, reserve).as_ptr()
}
+/// `PrimitiveString* libjs_jit_create_rope_string(VM*, PrimitiveString* lhs, PrimitiveString* rhs)`: the rope string of
+/// `lhs` and `rhs`.
+///
+/// JIT code calls this with its VM and live non-empty strings, whose lengths add up to at least `ROPE_STRING_MIN_LENGTH`
+/// and less than `u32::MAX`.
+pub extern "C" fn libjs_jit_create_rope_string(
+ vm: &Vm,
+ lhs: Gc<PrimitiveString>,
+ rhs: Gc<PrimitiveString>,
+) -> *mut PrimitiveString {
+ PrimitiveString::create_rope(vm, lhs, rhs).as_ptr()
+}
+
/// `Array* libjs_jit_allocate_array(VM*, u32 count)`: an array of the running realm with `count` packed undefined
/// elements.
///
diff --git a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
index b6dd4adf3cf..682820584ac 100644
--- a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
+++ b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
@@ -346,7 +346,12 @@ impl PrimitiveString {
return Ok(inline_string);
}
- Ok(vm.heap().allocate(RopeString::new(lhs, rhs)).upcast())
+ Ok(Self::create_rope(vm, lhs, rhs))
+ }
+
+ /// The rope string of the non-empty strings `lhs` and `rhs`, whose lengths add up to less than `u32::MAX`.
+ pub(crate) fn create_rope(vm: &Vm, lhs: Gc<PrimitiveString>, rhs: Gc<PrimitiveString>) -> Gc<PrimitiveString> {
+ vm.heap().allocate(RopeString::new(lhs, rhs)).upcast()
}
pub fn create_from_substring(