Skip to content

Truly independent web browser

LibJS: Shrink SharedFunctionInstanceData and environments

Andreas Klingb28e92eb35c7
diff --git a/Libraries/LibJS/Flap/src/hir/mod.rs b/Libraries/LibJS/Flap/src/hir/mod.rs
index 19632f7327e..3d399474200 100644
--- a/Libraries/LibJS/Flap/src/hir/mod.rs
+++ b/Libraries/LibJS/Flap/src/hir/mod.rs
@@ -20,10 +20,10 @@ use crate::frontend::layout;
use crate::hash::{HashMap, HashSet};
use crate::identity::{ExternalSymbol, InlineFunctionId};
use crate::intrinsic::{
- AddressOperation, AggregateOperation, BinaryOperation, BytecodeOperation, CallOperation, ComparisonRelation,
- ControlOperation, FieldAccess, FieldAccessKind, FieldPair, FieldWidth, FloatBinaryOperation,
- FloatingPointOperation, IntegerBinaryOperation, IntegerComparisonOperation, Intrinsic, LowLevelOperation,
- MemoryOperation, OperandLoad, OperandOperation, OperationValue, ShiftOperation, ValueOperation,
+ AddressOperation, BinaryOperation, BytecodeOperation, CallOperation, ComparisonRelation, ControlOperation,
+ FieldAccess, FieldAccessKind, FieldPair, FieldWidth, FloatBinaryOperation, FloatingPointOperation,
+ IntegerBinaryOperation, IntegerComparisonOperation, Intrinsic, LowLevelOperation, MemoryOperation, OperandLoad,
+ OperandOperation, OperationValue, ShiftOperation, ValueOperation,
};
use crate::types::{BlockTemperature, InterpreterRegister, Type};
use capture::{collect_captures, collect_input_captures};
@@ -1695,79 +1695,6 @@ impl<'a> Checker<'a> {
format!("cannot assign null to non-null field '{}.{field_name}'", base.ty),
);
}
- if matches!(
- &initializer.kind,
- ExpressionKind::Call { callee, arguments }
- if callee == "zeroed" && arguments.is_empty()
- ) {
- if field.ty != Type::ScriptOrModule {
- return self.error(
- initializer.span,
- format!(
- "cannot zero-initialize field '{}.{field_name}' of type {}",
- base.ty, field.ty
- ),
- );
- }
- return Ok(Call::new(
- CallTarget::Intrinsic(Intrinsic::Aggregate(AggregateOperation::Zero16)),
- vec![Value::new(
- ValueKind::Memory(vec![
- base,
- Value::new(ValueKind::LayoutValue(field.offset), Type::U64, span),
- ]),
- Type::Memory,
- span,
- )],
- vec![ParameterMode::In],
- None,
- ));
- }
- if field.ty == Type::ScriptOrModule {
- let ExpressionKind::Name(source_name) = &initializer.kind else {
- return self.error(
- initializer.span,
- "a ScriptOrModule field can only be copied from another ScriptOrModule field",
- );
- };
- let (source_base, source_field_name) = self.check_field_projection_base(source_name, initializer.span)?;
- let source_field = self
- .layouts
- .get(&(source_base.ty.clone(), source_field_name.clone()))
- .cloned()
- .ok_or_else(|| {
- Diagnostic::new(
- self.filename,
- initializer.span,
- format!("type {} has no field '{source_field_name}'", source_base.ty),
- )
- })?;
- if source_field.ty != Type::ScriptOrModule {
- return self.error(
- initializer.span,
- format!("expected ScriptOrModule, got {}", source_field.ty),
- );
- }
- let memory = |base, offset: layout::LayoutValue, value_span| {
- Value::new(
- ValueKind::Memory(vec![
- base,
- Value::new(ValueKind::LayoutValue(offset), Type::U64, value_span),
- ]),
- Type::Memory,
- value_span,
- )
- };
- return Ok(Call::new(
- CallTarget::Intrinsic(Intrinsic::Aggregate(AggregateOperation::Copy16)),
- vec![
- memory(base, field.offset, span),
- memory(source_base, source_field.offset, initializer.span),
- ],
- vec![ParameterMode::In, ParameterMode::In],
- None,
- ));
- }
let memory = self.field_memory(base, &field, span);
let value = self.check_materialized_value(initializer, &field.ty)?;
let width = field_width(&field.ty, true)
diff --git a/Libraries/LibJS/Flap/src/types.rs b/Libraries/LibJS/Flap/src/types.rs
index 424ab3ddacd..73bb922d8ea 100644
--- a/Libraries/LibJS/Flap/src/types.rs
+++ b/Libraries/LibJS/Flap/src/types.rs
@@ -228,7 +228,6 @@ define_named_types! {
RawNativeFunction => "RawNativeFunction", Some(8), true;
DirectGetterFunction => "DirectGetterFunction", Some(8), true;
SharedFunctionInstanceData => "SharedFunctionInstanceData", Some(8), true;
- ScriptOrModule => "ScriptOrModule", Some(8), true;
PropertyStorage => "PropertyStorage", Some(8), true;
}
source {
diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S
index 511f5dfeaf6..693099e2d8b 100644
--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S
+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S
@@ -3669,7 +3669,7 @@ asm_handler_SetLexicalBinding:
ldrb w1, [x1, x0]
b .Lasm_SetLexicalBinding.ssa_block_10
.Lasm_SetLexicalBinding.ssa_block_9:
- ldr x4, [x2, #24]
+ ldr w4, [x2, #24]
cmp x4, x0
b.hi .Lasm_SetLexicalBinding.ssa_block_12
ldr x1, [x1, #48]
@@ -3730,7 +3730,7 @@ asm_handler_SetVariableBinding:
ldrb w1, [x1, x0]
b .Lasm_SetVariableBinding.ssa_block_10
.Lasm_SetVariableBinding.ssa_block_9:
- ldr x4, [x2, #24]
+ ldr w4, [x2, #24]
cmp x4, x0
b.hi .Lasm_SetVariableBinding.ssa_block_12
ldr x1, [x1, #48]
@@ -3805,7 +3805,7 @@ asm_handler_DynamicSetLexicalBinding:
ldrb w0, [x0, x1]
b .Lasm_DynamicSetLexicalBinding.ssa_block_14
.Lasm_DynamicSetLexicalBinding.ssa_block_13:
- ldr x4, [x2, #24]
+ ldr w4, [x2, #24]
cmp x4, x1
b.hi .Lasm_DynamicSetLexicalBinding.ssa_block_16
ldr x0, [x0, #48]
@@ -3880,7 +3880,7 @@ asm_handler_DynamicSetVariableBinding:
ldrb w0, [x0, x1]
b .Lasm_DynamicSetVariableBinding.ssa_block_14
.Lasm_DynamicSetVariableBinding.ssa_block_13:
- ldr x4, [x2, #24]
+ ldr w4, [x2, #24]
cmp x4, x1
b.hi .Lasm_DynamicSetVariableBinding.ssa_block_16
ldr x0, [x0, #48]
@@ -5924,7 +5924,7 @@ asm_handler_SetGlobal:
ldrb w1, [x1, x0]
b .Lasm_SetGlobal.ssa_block_7
.Lasm_SetGlobal.ssa_block_6:
- ldr x4, [x2, #24]
+ ldr w4, [x2, #24]
cmp x4, x0
b.hi .Lasm_SetGlobal.ssa_block_9
ldr x1, [x1, #48]
@@ -6013,10 +6013,10 @@ asm_handler_Call:
b.hs .Lasm_Call.ssa_block_29
mov x3, x4
.Lasm_Call.ssa_block_29:
- cbz x2, .Lasm_Call.assert_predicate_failure_352
+ cbz x2, .Lasm_Call.assert_predicate_failure_353
ldp w0, w4, [x2, #12]
cmp x4, x0
- b.lo .Lasm_Call.assert_predicate_failure_358
+ b.lo .Lasm_Call.assert_predicate_failure_359
movn w0, #0
subs x0, x0, x4
cmp x0, x3
@@ -6031,7 +6031,7 @@ asm_handler_Call:
add x5, x5, #128
adds x5, x5, x0
cmp x5, x0
- b.lo .Lasm_Call.assert_predicate_failure_373
+ b.lo .Lasm_Call.assert_predicate_failure_374
cmp x5, x8
b.hi .Lasm_Call.ssa_block_1
mov x8, x20
@@ -6050,7 +6050,7 @@ asm_handler_Call:
add x9, x24, w5, uxtw #3
cmp w5, #0
csel x5, x9, xzr, ne
- cbz x5, .Lasm_Call.assert_predicate_failure_399
+ cbz x5, .Lasm_Call.assert_predicate_failure_400
stp x5, x5, [x0, #32]
str xzr, [x0, #48]
ldrb w9, [x1, #15]
@@ -6071,10 +6071,8 @@ asm_handler_Call:
ldr w1, [x1, #68]
cbz x1, .Lasm_Call.assert_failure_8
add x1, x24, w1, uxtw #3
- add x2, x0, #16
- add x1, x1, #40
- ldp x1, x5, [x1, #0]
- stp x1, x5, [x2, #0]
+ ldr x1, [x1, #40]
+ str x1, [x0, #16]
str wzr, [x0, #64]
mov x2, x20
ldr x1, [x2, #32]
@@ -6099,7 +6097,7 @@ asm_handler_Call:
stp w2, w5, [x0, #108]
ldr w2, [x21, #24]
cmp x3, x2
- b.lo .Lasm_Call.assert_predicate_failure_265
+ b.lo .Lasm_Call.assert_predicate_failure_266
add x6, x28, #128
add x7, x21, #32
add x5, x0, #128
@@ -6125,7 +6123,7 @@ asm_handler_Call:
b .Lasm_Call.ssa_block_22
.Lasm_Call.ssa_block_21:
ldr x1, [x0, #88]
- cbz x1, .Lasm_Call.assert_predicate_failure_288
+ cbz x1, .Lasm_Call.assert_predicate_failure_289
ldr x26, [x1, #40]
cbz x26, .Lasm_Call.assert_failure_10
mov x1, x20
@@ -6181,9 +6179,7 @@ asm_handler_Call:
ldr w2, [x21, #20]
ldr x2, [x27, x2, lsl #3]
str x2, [x0, #80]
- mov x2, #0
- add x4, x0, #16
- stp x2, x2, [x4, #0]
+ str xzr, [x0, #16]
str xzr, [x0, #88]
str wzr, [x0, #64]
mov x4, x20
@@ -6232,7 +6228,7 @@ asm_handler_Call:
adds x0, x0, x1
ldr w1, [x0, #8]
cmp x1, #1
- b.hs .Lasm_Call.assert_predicate_failure_323
+ b.hs .Lasm_Call.assert_predicate_failure_324
ldr x2, [x0]
cbz x2, .Lasm_Call.assert_failure_17
mov x9, x2
@@ -6240,10 +6236,10 @@ asm_handler_Call:
blr x9
and x1, x1, #0xff
cmp x1, #2
- b.hs .Lasm_Call.assert_predicate_failure_330
+ b.hs .Lasm_Call.assert_predicate_failure_331
cbnz x1, .Lasm_Call.ssa_block_4
ldr x1, [x28, #96]
- cbz x1, .Lasm_Call.assert_predicate_failure_336
+ cbz x1, .Lasm_Call.assert_predicate_failure_337
mov x2, x20
str x1, [x2]
str x28, [x2, #16]
@@ -6407,11 +6403,11 @@ asm_handler_ObjectPropertyIteratorNext:
adds w3, w3, #1
b.vs .Lasm_ObjectPropertyIteratorNext.ssa_block_1
sxtw x1, w1
- ldr x4, [x0, #40]
+ ldr w4, [x0, #40]
cmp x1, x4
b.hs .Lasm_ObjectPropertyIteratorNext.ssa_block_13
ldr x0, [x0, #32]
- cbz x0, .Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_65
+ cbz x0, .Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_66
ldr x0, [x0, x1, lsl #3]
ldr w9, [x21, #4]
str x0, [x27, x9, lsl #3]
@@ -14173,9 +14169,7 @@ asm_handler_GetById_cold:
movz x1, #0xfff9, lsl #48
orr x3, x3, x1
str x3, [x0, #80]
- mov x1, #0
- add x2, x0, #16
- stp x1, x1, [x2, #0]
+ str xzr, [x0, #16]
str xzr, [x0, #88]
str wzr, [x0, #64]
str wzr, [x0, #68]
@@ -20888,29 +20882,29 @@ asm_assertion_failure_traps:
brk #0
.Lasm_Call.assert_failure_3:
brk #0
-.Lasm_Call.assert_predicate_failure_352:
+.Lasm_Call.assert_predicate_failure_353:
brk #0
-.Lasm_Call.assert_predicate_failure_358:
+.Lasm_Call.assert_predicate_failure_359:
brk #0
.Lasm_Call.assert_failure_4:
brk #0
.Lasm_Call.assert_failure_5:
brk #0
-.Lasm_Call.assert_predicate_failure_373:
+.Lasm_Call.assert_predicate_failure_374:
brk #0
.Lasm_Call.assert_failure_6:
brk #0
.Lasm_Call.assert_failure_7:
brk #0
-.Lasm_Call.assert_predicate_failure_399:
+.Lasm_Call.assert_predicate_failure_400:
brk #0
.Lasm_Call.assert_failure_8:
brk #0
.Lasm_Call.assert_failure_9:
brk #0
-.Lasm_Call.assert_predicate_failure_265:
+.Lasm_Call.assert_predicate_failure_266:
brk #0
-.Lasm_Call.assert_predicate_failure_288:
+.Lasm_Call.assert_predicate_failure_289:
brk #0
.Lasm_Call.assert_failure_10:
brk #0
@@ -20934,13 +20928,13 @@ asm_assertion_failure_traps:
brk #0
.Lasm_Call.assert_failure_16:
brk #0
-.Lasm_Call.assert_predicate_failure_323:
+.Lasm_Call.assert_predicate_failure_324:
brk #0
.Lasm_Call.assert_failure_17:
brk #0
-.Lasm_Call.assert_predicate_failure_330:
+.Lasm_Call.assert_predicate_failure_331:
brk #0
-.Lasm_Call.assert_predicate_failure_336:
+.Lasm_Call.assert_predicate_failure_337:
brk #0
.Lasm_Call.assert_predicate_failure_11:
brk #0
@@ -20960,7 +20954,7 @@ asm_assertion_failure_traps:
brk #0
.Lasm_ObjectPropertyIteratorNext.assert_failure_0:
brk #0
-.Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_65:
+.Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_66:
brk #0
.Lasm_IteratorClose.assert_failure_0:
brk #0
diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S
index 235743c57fe..62aa24efb60 100644
--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S
+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S
@@ -3647,7 +3647,7 @@ asm_handler_SetLexicalBinding:
movzx ecx, BYTE PTR [rcx + rax]
jmp .Lasm_SetLexicalBinding.ssa_block_10
.Lasm_SetLexicalBinding.ssa_block_9:
- mov rdi, QWORD PTR [rdx + 24]
+ mov edi, DWORD PTR [rdx + 24]
cmp rdi, rax
ja .Lasm_SetLexicalBinding.ssa_block_12
mov rcx, QWORD PTR [rcx + 48]
@@ -3718,7 +3718,7 @@ asm_handler_SetVariableBinding:
movzx ecx, BYTE PTR [rcx + rax]
jmp .Lasm_SetVariableBinding.ssa_block_10
.Lasm_SetVariableBinding.ssa_block_9:
- mov rdi, QWORD PTR [rdx + 24]
+ mov edi, DWORD PTR [rdx + 24]
cmp rdi, rax
ja .Lasm_SetVariableBinding.ssa_block_12
mov rcx, QWORD PTR [rcx + 48]
@@ -3802,7 +3802,7 @@ asm_handler_DynamicSetLexicalBinding:
movzx eax, BYTE PTR [rax + rcx]
jmp .Lasm_DynamicSetLexicalBinding.ssa_block_14
.Lasm_DynamicSetLexicalBinding.ssa_block_13:
- mov rdi, QWORD PTR [rdx + 24]
+ mov edi, DWORD PTR [rdx + 24]
cmp rdi, rcx
ja .Lasm_DynamicSetLexicalBinding.ssa_block_16
mov rax, QWORD PTR [rax + 48]
@@ -3886,7 +3886,7 @@ asm_handler_DynamicSetVariableBinding:
movzx eax, BYTE PTR [rax + rcx]
jmp .Lasm_DynamicSetVariableBinding.ssa_block_14
.Lasm_DynamicSetVariableBinding.ssa_block_13:
- mov rdi, QWORD PTR [rdx + 24]
+ mov edi, DWORD PTR [rdx + 24]
cmp rdi, rcx
ja .Lasm_DynamicSetVariableBinding.ssa_block_16
mov rax, QWORD PTR [rax + 48]
@@ -6008,7 +6008,7 @@ asm_handler_SetGlobal:
movzx ecx, BYTE PTR [rcx + rax]
jmp .Lasm_SetGlobal.ssa_block_7
.Lasm_SetGlobal.ssa_block_6:
- mov rdi, QWORD PTR [rdx + 24]
+ mov edi, DWORD PTR [rdx + 24]
cmp rdi, rax
ja .Lasm_SetGlobal.ssa_block_9
mov rcx, QWORD PTR [rcx + 48]
@@ -6105,11 +6105,11 @@ asm_handler_Call:
mov rsi, rdi
.Lasm_Call.ssa_block_29:
test rdx, rdx
- jz .Lasm_Call.assert_predicate_failure_352
+ jz .Lasm_Call.assert_predicate_failure_353
mov eax, DWORD PTR [rdx + 12]
mov edi, DWORD PTR [rdx + 16]
cmp rdi, rax
- jb .Lasm_Call.assert_predicate_failure_358
+ jb .Lasm_Call.assert_predicate_failure_359
mov eax, 4294967295
sub rax, rdi
cmp rax, rsi
@@ -6128,7 +6128,7 @@ asm_handler_Call:
lea r8, [r8 + 128]
add r8, rax
cmp r8, rax
- jb .Lasm_Call.assert_predicate_failure_373
+ jb .Lasm_Call.assert_predicate_failure_374
cmp r8, r11
ja .Lasm_Call.ssa_block_1
mov r11, QWORD PTR [rbp - 48]
@@ -6152,7 +6152,7 @@ asm_handler_Call:
test r8d, r8d
cmovnz r8, r11
test r8, r8
- jz .Lasm_Call.assert_predicate_failure_399
+ jz .Lasm_Call.assert_predicate_failure_400
mov QWORD PTR [rax + 32], r8
mov QWORD PTR [rax + 40], r8
mov QWORD PTR [rax + 48], 0
@@ -6176,12 +6176,8 @@ asm_handler_Call:
test rcx, rcx
jz .Lasm_Call.assert_failure_8
lea rcx, [r15 + rcx * 8]
- lea rdx, [rax + 16]
- lea rcx, [rcx + 40]
- mov r8, QWORD PTR [rcx + 8]
- mov rcx, QWORD PTR [rcx]
- mov QWORD PTR [rdx], rcx
- mov QWORD PTR [rdx + 8], r8
+ mov rcx, QWORD PTR [rcx + 40]
+ mov QWORD PTR [rax + 16], rcx
mov DWORD PTR [rax + 64], 0
mov rdx, QWORD PTR [rbp - 48]
mov rcx, QWORD PTR [rdx + 32]
@@ -6209,7 +6205,7 @@ asm_handler_Call:
mov DWORD PTR [rax + 112], r8d
mov edx, DWORD PTR [r14 + r13 + 24]
cmp rsi, rdx
- jb .Lasm_Call.assert_predicate_failure_265
+ jb .Lasm_Call.assert_predicate_failure_266
lea r9, [rbx]
lea r10, [r14 + r13 + 32]
lea r8, [rax + 128]
@@ -6236,7 +6232,7 @@ asm_handler_Call:
.Lasm_Call.ssa_block_21:
mov rcx, QWORD PTR [rax + 88]
test rcx, rcx
- jz .Lasm_Call.assert_predicate_failure_288
+ jz .Lasm_Call.assert_predicate_failure_289
mov r14, QWORD PTR [rcx + 40]
test r14, r14
jz .Lasm_Call.assert_failure_10
@@ -6301,10 +6297,7 @@ asm_handler_Call:
mov edx, DWORD PTR [r14 + r13 + 20]
mov rdx, QWORD PTR [rbx + rdx * 8]
mov QWORD PTR [rax + 80], rdx
- xor rdx, rdx
- lea rdi, [rax + 16]
- mov QWORD PTR [rdi], rdx
- mov QWORD PTR [rdi + 8], rdx
+ mov QWORD PTR [rax + 16], 0
mov QWORD PTR [rax + 88], 0
mov DWORD PTR [rax + 64], 0
mov rdi, QWORD PTR [rbp - 48]
@@ -6356,7 +6349,7 @@ asm_handler_Call:
add rax, rcx
mov ecx, DWORD PTR [rax + 8]
cmp rcx, 1
- jae .Lasm_Call.assert_predicate_failure_323
+ jae .Lasm_Call.assert_predicate_failure_324
mov rdx, QWORD PTR [rax]
test rdx, rdx
jz .Lasm_Call.assert_failure_17
@@ -6366,12 +6359,12 @@ asm_handler_Call:
mov rcx, rdx
and rcx, 255
cmp rcx, 2
- jae .Lasm_Call.assert_predicate_failure_330
+ jae .Lasm_Call.assert_predicate_failure_331
test rcx, rcx
jnz .Lasm_Call.ssa_block_4
mov rcx, QWORD PTR [rbx - 32]
test rcx, rcx
- jz .Lasm_Call.assert_predicate_failure_336
+ jz .Lasm_Call.assert_predicate_failure_337
mov rdx, QWORD PTR [rbp - 48]
mov QWORD PTR [rdx], rcx
lea r11, [rbx - 128]
@@ -6541,12 +6534,12 @@ asm_handler_ObjectPropertyIteratorNext:
inc esi
jo .Lasm_ObjectPropertyIteratorNext.ssa_block_1
movsxd rcx, ecx
- mov rdi, QWORD PTR [rax + 40]
+ mov edi, DWORD PTR [rax + 40]
cmp rcx, rdi
jae .Lasm_ObjectPropertyIteratorNext.ssa_block_13
mov rax, QWORD PTR [rax + 32]
test rax, rax
- jz .Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_65
+ jz .Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_66
mov rax, QWORD PTR [rax + rcx * 8]
mov r11d, DWORD PTR [r14 + r13 + 4]
mov QWORD PTR [rbx + r11 * 8], rax
@@ -13837,10 +13830,7 @@ asm_handler_GetById_cold:
movabs rcx, -1970324836974592
or rsi, rcx
mov QWORD PTR [rax + 80], rsi
- xor rcx, rcx
- lea rdx, [rax + 16]
- mov QWORD PTR [rdx], rcx
- mov QWORD PTR [rdx + 8], rcx
+ mov QWORD PTR [rax + 16], 0
mov QWORD PTR [rax + 88], 0
mov DWORD PTR [rax + 64], 0
mov DWORD PTR [rax + 68], 0
@@ -20334,29 +20324,29 @@ asm_assertion_failure_traps:
ud2
.Lasm_Call.assert_failure_3:
ud2
-.Lasm_Call.assert_predicate_failure_352:
+.Lasm_Call.assert_predicate_failure_353:
ud2
-.Lasm_Call.assert_predicate_failure_358:
+.Lasm_Call.assert_predicate_failure_359:
ud2
.Lasm_Call.assert_failure_4:
ud2
.Lasm_Call.assert_failure_5:
ud2
-.Lasm_Call.assert_predicate_failure_373:
+.Lasm_Call.assert_predicate_failure_374:
ud2
.Lasm_Call.assert_failure_6:
ud2
.Lasm_Call.assert_failure_7:
ud2
-.Lasm_Call.assert_predicate_failure_399:
+.Lasm_Call.assert_predicate_failure_400:
ud2
.Lasm_Call.assert_failure_8:
ud2
.Lasm_Call.assert_failure_9:
ud2
-.Lasm_Call.assert_predicate_failure_265:
+.Lasm_Call.assert_predicate_failure_266:
ud2
-.Lasm_Call.assert_predicate_failure_288:
+.Lasm_Call.assert_predicate_failure_289:
ud2
.Lasm_Call.assert_failure_10:
ud2
@@ -20380,13 +20370,13 @@ asm_assertion_failure_traps:
ud2
.Lasm_Call.assert_failure_16:
ud2
-.Lasm_Call.assert_predicate_failure_323:
+.Lasm_Call.assert_predicate_failure_324:
ud2
.Lasm_Call.assert_failure_17:
ud2
-.Lasm_Call.assert_predicate_failure_330:
+.Lasm_Call.assert_predicate_failure_331:
ud2
-.Lasm_Call.assert_predicate_failure_336:
+.Lasm_Call.assert_predicate_failure_337:
ud2
.Lasm_Call.assert_predicate_failure_11:
ud2
@@ -20406,7 +20396,7 @@ asm_assertion_failure_traps:
ud2
.Lasm_ObjectPropertyIteratorNext.assert_failure_0:
ud2
-.Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_65:
+.Lasm_ObjectPropertyIteratorNext.assert_predicate_failure_66:
ud2
.Lasm_IteratorClose.assert_failure_0:
ud2
diff --git a/Libraries/LibJS/Flap/tests/interpreter-layout.conf b/Libraries/LibJS/Flap/tests/interpreter-layout.conf
index 03e82576bdd..42504030106 100644
--- a/Libraries/LibJS/Flap/tests/interpreter-layout.conf
+++ b/Libraries/LibJS/Flap/tests/interpreter-layout.conf
@@ -179,7 +179,7 @@ field ExecutionContext.function Object EXECUTION_CONTEXT_FUNCTION nullable cell
const EXECUTION_CONTEXT_REALM = 8
field ExecutionContext.realm Realm EXECUTION_CONTEXT_REALM nullable cell function_and_realm
const EXECUTION_CONTEXT_SCRIPT_OR_MODULE = 16
-field ExecutionContext.script_or_module ScriptOrModule EXECUTION_CONTEXT_SCRIPT_OR_MODULE nullable scalar
+field ExecutionContext.script_or_module u64 EXECUTION_CONTEXT_SCRIPT_OR_MODULE nullable scalar
const EXECUTION_CONTEXT_LEXICAL_ENVIRONMENT = 32
field ExecutionContext.lexical_environment Environment EXECUTION_CONTEXT_LEXICAL_ENVIRONMENT nullable cell environments
const EXECUTION_CONTEXT_VARIABLE_ENVIRONMENT = 40
@@ -236,7 +236,7 @@ field ExecutionContext.return_value Value EXECUTION_CONTEXT_RETURN_VALUE nullabl
field ExecutionContext.saved_lexical_environment Value EXECUTION_CONTEXT_SAVED_LEXICAL_ENVIRONMENT nullable scalar return_and_saved_environment
const ALIGNOF_EXECUTION_CONTEXT = 8
const EXECUTION_CONTEXT_NO_YIELD_CONTINUATION = 4294967295
-const SIZEOF_SCRIPT_OR_MODULE = 16
+const SIZEOF_SCRIPT_OR_MODULE = 8
const SIZEOF_VALUE = 8
# InterpreterStack layout
@@ -316,7 +316,7 @@ const EXECUTABLE_CONSTANTS_SIZE = 136
const OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_DATA = 32
const OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_SIZE = 40
field ObjectPropertyIteratorCacheData.property_values Sequence<Value> OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_DATA nullable scalar
-field ObjectPropertyIteratorCacheData.property_value_count u64 OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_SIZE nullable scalar
+field ObjectPropertyIteratorCacheData.property_value_count u32 OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_SIZE nullable scalar
# PutKind enum
const PUT_KIND_NORMAL = 0
@@ -382,16 +382,11 @@ const ECMASCRIPT_FUNCTION_FLAG_HAS_RARE_DATA = 8
# SharedFunctionInstanceData layout
const SHARED_FUNCTION_INSTANCE_DATA_SCRIPT_OR_MODULE = 40
-field SharedFunctionInstanceData.script_or_module ScriptOrModule SHARED_FUNCTION_INSTANCE_DATA_SCRIPT_OR_MODULE nullable scalar
+field SharedFunctionInstanceData.script_or_module u64 SHARED_FUNCTION_INSTANCE_DATA_SCRIPT_OR_MODULE nullable scalar
const SHARED_FUNCTION_INSTANCE_DATA_EXECUTABLE = 12
field SharedFunctionInstanceData.executable Executable SHARED_FUNCTION_INSTANCE_DATA_EXECUTABLE nullable compressed
const SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA = 16
field SharedFunctionInstanceData.asm_call_metadata u64 SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA nullable scalar
-const SHARED_FUNCTION_INSTANCE_DATA_FORMAL_PARAMETER_COUNT = 24
-const SHARED_FUNCTION_INSTANCE_DATA_STRICT = 28
-const SHARED_FUNCTION_INSTANCE_DATA_FUNCTION_ENVIRONMENT_NEEDED = 29
-const SHARED_FUNCTION_INSTANCE_DATA_USES_THIS = 30
-const SHARED_FUNCTION_INSTANCE_DATA_CAN_INLINE_CALL = 31
const SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA_CAN_INLINE_CALL = 4294967296
const SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA_NEEDS_ENVIRONMENT_OR_THIS_VALUE_RESOLUTION = 8589934592
const SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA_USES_THIS = 17179869184
@@ -459,7 +454,7 @@ const BINDING_FLAGS_DATA_PTR = 0
field DeclarativeEnvironmentRareData.binding_flags BindingFlags BINDING_FLAGS_DATA_PTR nonnull scalar
const ENVIRONMENT_SHAPE_BINDING_FLAGS_DATA_PTR = 16
const ENVIRONMENT_SHAPE_BINDING_FLAGS_SIZE = 24
-field EnvironmentShape.binding_flags_size u64 ENVIRONMENT_SHAPE_BINDING_FLAGS_SIZE nullable scalar
+field EnvironmentShape.binding_flags_size u32 ENVIRONMENT_SHAPE_BINDING_FLAGS_SIZE nullable scalar
field EnvironmentShape.binding_flags BindingFlags ENVIRONMENT_SHAPE_BINDING_FLAGS_DATA_PTR nonnull scalar
# EnvironmentCoordinate layout
diff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flap
index a0c39505ced..c199fe26dd3 100644
--- a/Libraries/LibJS/Interpreter/interpreter.flap
+++ b/Libraries/LibJS/Interpreter/interpreter.flap
@@ -303,7 +303,7 @@ inline fn load_binding_flag(
if binding_shape == 0 {
environment.rare_data.binding_flags[binding_index]
} else {
- let shape_size = binding_shape.binding_flags_size;
+ let shape_size: u64 = alias(binding_shape.binding_flags_size);
if shape_size <= alias(binding_index) {
let local_index: u64 = alias(binding_index) - shape_size;
environment.rare_data.binding_flags[local_index]
@@ -3221,7 +3221,7 @@ handler GetById(
native_frame.private_environment = exec_ctx.private_environment;
let receiver: Value = alias(box_object(receiver_object));
native_frame.this_value = receiver;
- native_frame.script_or_module = zeroed();
+ native_frame.script_or_module = 0;
native_frame.executable = null;
native_frame.program_counter = 0;
native_frame.skip_when_determining_incumbent_counter = 0;
@@ -4020,7 +4020,7 @@ handler Call(
native_frame.private_environment = private_environment;
let receiver = load(this_value);
native_frame.this_value = receiver;
- native_frame.script_or_module = zeroed();
+ native_frame.script_or_module = 0;
# Raw native frames deliberately have no executable.
native_frame.executable = null;
native_frame.program_counter = 0;
@@ -4158,7 +4158,7 @@ handler ObjectPropertyIteratorNext(
guard let next_cursor_index = checked_add(cursor_index, 1) else slow;
let cursor_wide: i64 = i64(cursor_index);
let unsigned_cursor: u64 = alias(cursor_wide);
- let property_value_count = cache.property_value_count;
+ let property_value_count: u64 = alias(cache.property_value_count);
if unsigned_cursor < property_value_count {
let property_values = cache.property_values;
assert(property_values != 0);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
index ad020f26666..428cf491fef 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
@@ -610,16 +610,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
4,
u64::from(header.argument_count),
),
- (
- offsets.execution_context_script_or_module,
- 8,
- fields.script_or_module[0],
- ),
- (
- offsets.execution_context_script_or_module + 8,
- 8,
- fields.script_or_module[1],
- ),
+ (offsets.execution_context_script_or_module, 8, fields.script_or_module),
(offsets.execution_context_lexical_environment, 8, fields.environment),
(offsets.execution_context_variable_environment, 8, fields.environment),
(
@@ -1423,7 +1414,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let mut constants = self.new_frame_constants(false);
constants.extend([
(offsets.execution_context_script_or_module, 8, 0),
- (offsets.execution_context_script_or_module + 8, 8, 0),
(offsets.execution_context_executable, 8, 0),
(offsets.execution_context_slot_count, 4, u64::from(argument_count)),
(offsets.execution_context_argument_count, 4, u64::from(argument_count)),
@@ -1547,7 +1537,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
constants.extend([
(offsets.execution_context_function, 8, header.function.function.0),
(offsets.execution_context_script_or_module, 8, 0),
- (offsets.execution_context_script_or_module + 8, 8, 0),
// NB: Frames get their id when the debugger first needs it.
(offsets.execution_context_frame_id, 8, 0),
]);
@@ -1559,16 +1548,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
);
constants.extend([
(offsets.execution_context_function, 8, header.function.function.0),
- (
- offsets.execution_context_script_or_module,
- 8,
- fields.script_or_module[0],
- ),
- (
- offsets.execution_context_script_or_module + 8,
- 8,
- fields.script_or_module[1],
- ),
+ (offsets.execution_context_script_or_module, 8, fields.script_or_module),
(offsets.execution_context_lexical_environment, 8, fields.environment),
(offsets.execution_context_variable_environment, 8, fields.environment),
(
@@ -1620,15 +1600,13 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
.store64(&field(offsets.execution_context_function), function_register);
let function_field = |offset: u32| Address::new(function_register, offset as i32);
let shared_data_field = function_field(self.runtime.dynamic_calls.ecmascript_function_shared_data);
- for word in [0, 8] {
- self.emit_load_compressed_cell(temp, &shared_data_field);
- self.masm.load64(
- temp,
- &Address::new(temp, (offsets.shared_function_script_or_module + word) as i32),
- );
- self.masm
- .store64(&field(offsets.execution_context_script_or_module + word), temp);
- }
+ self.emit_load_compressed_cell(temp, &shared_data_field);
+ self.masm.load64(
+ temp,
+ &Address::new(temp, offsets.shared_function_script_or_module as i32),
+ );
+ self.masm
+ .store64(&field(offsets.execution_context_script_or_module), temp);
// NB: ECMAScript functions always have an environment.
self.emit_load_compressed_cell(temp, &function_field(offsets.ecmascript_function_environment));
self.masm
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
index 16406588aba..c2f51f571be 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
@@ -45,6 +45,7 @@ use crate::ir::BlockId;
use crate::ir::Graph;
use crate::ir::value;
use crate::regalloc::Allocation;
+use crate::snapshot::COMPRESSED_POINTER_SHIFT;
use crate::snapshot::RuntimeInfo;
/// Where the stub keeps its inputs and what must survive calls into the
@@ -236,8 +237,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
&at(function, self.runtime.offsets.ecmascript_function_environment),
);
self.masm.store32(&at(cell, layout.function_environment_outer), scratch);
+ self.masm.shr64_imm(scratch, function, COMPRESSED_POINTER_SHIFT);
self.masm
- .store64(&at(cell, layout.function_environment_function_object), function);
+ .store32(&at(cell, layout.function_environment_function_object), scratch);
let no_this = self.masm.new_label();
self.masm
.load64(scratch, &at(template, layout.call_environment_template_binds_this));
@@ -799,7 +801,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let mut constants = self.emit_stub_call_site_fields(native_frame, temp, false);
constants.extend([
(offsets.execution_context_script_or_module, 8, 0),
- (offsets.execution_context_script_or_module + 8, 8, 0),
(offsets.execution_context_executable, 8, 0),
]);
self.emit_constant_fields_with_vector(native_frame, temp, &mut constants, Some(M::ARGUMENT_FPRS[0]), &[])?;
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs b/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs
index b6bbfda6864..dce0a2cf646 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs
@@ -54,7 +54,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
rare_at_index,
);
// Flags past the shape's are in the rare data, after the shape's.
- self.masm.load64(
+ self.masm.load32(
temp,
&Address::new(scratch, layout.environment_shape_binding_flags_size as i32),
);
@@ -122,11 +122,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
&Address::new(shape, layout.environment_shape_has_unique_binding_names as i32),
);
self.masm.branch_test32(Condition::Zero, scratch, 0xFF, fail);
- self.masm.load64(
+ self.masm.load32(
index,
&Address::new(environment, layout.declarative_environment_binding_values_size as i32),
);
- self.masm.load64(
+ self.masm.load32(
scratch,
&Address::new(shape, layout.environment_shape_binding_flags_size as i32),
);
@@ -149,7 +149,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.branch64(Condition::NotEqual, scratch, shape, fail);
// Values that do not fit in their storage move first.
- self.masm.load64(
+ self.masm.load32(
scratch,
&Address::new(
environment,
@@ -165,7 +165,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let scratch = self.pinned.scratch;
let layout = self.runtime.layout;
let index = self.temp(node, 0);
- self.masm.load64(
+ self.masm.load32(
index,
&Address::new(environment, layout.declarative_environment_binding_values_size as i32),
);
@@ -176,7 +176,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm
.store_imm64(&Address::indexed(scratch, index, Scale::Eight, 0), value::EMPTY);
self.masm.add64_imm(index, index, 1);
- self.masm.store64(
+ self.masm.store32(
&Address::new(environment, layout.declarative_environment_binding_values_size as i32),
index,
);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rs b/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rs
index ba0dcf019a4..e650751cc74 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/property_iterator.rs
@@ -115,7 +115,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let layout = self.runtime.layout;
let small = self.masm.new_label();
self.emit_unbox_cell(output, keys);
- self.masm.load64(
+ self.masm.load32(
output,
&Address::new(output, layout.property_iterator_property_value_count as i32),
);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
index 73e06cf2aa9..0d6663572a7 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
@@ -2876,7 +2876,7 @@ mod inlining {
executable.feedback.arith = vec![NUMBERS_AND_STRINGS_FEEDBACK];
// NB: The words of a function its frames start with are constants in code.
executable.function_fields = Some(FunctionFrameFields {
- script_or_module: [FUNCTION_WORDS[2], FUNCTION_WORDS[3]],
+ script_or_module: FUNCTION_WORDS[2],
environment: FUNCTION_WORDS[0],
private_environment: FUNCTION_WORDS[1],
});
@@ -3363,7 +3363,7 @@ mod direct_calls {
registers_and_locals_and_constants_count: 9,
// NB: The fake function's words (see `offsets()`).
function_fields: FunctionFrameFields {
- script_or_module: [self.function[2], self.function[3]],
+ script_or_module: self.function[2],
environment: self.function[0],
private_environment: self.function[1],
},
@@ -3472,7 +3472,7 @@ mod direct_calls {
let byte = |offset: usize| (frame[offset / 8] >> (8 * (offset % 8))) as u8;
assert_eq!(word(64), callee.function.as_ptr() as u64, "function");
assert_eq!(word(72), REALM);
- assert_eq!((word(80), word(88)), (FUNCTION_WORDS[2], FUNCTION_WORDS[3]));
+ assert_eq!(word(80), FUNCTION_WORDS[2]);
assert_eq!(
(word(8), word(96), word(16)),
(FUNCTION_WORDS[0], FUNCTION_WORDS[0], FUNCTION_WORDS[1])
@@ -3869,7 +3869,7 @@ mod direct_calls {
let byte = |offset: usize| (frame[offset / 8] >> (8 * (offset % 8))) as u8;
assert_eq!(word(64), callee.function.as_ptr() as u64, "function");
assert_eq!(word(72), callee.realm);
- assert_eq!((word(80), word(88)), (FUNCTION_WORDS[2], FUNCTION_WORDS[3]));
+ assert_eq!(word(80), FUNCTION_WORDS[2]);
assert_eq!(
(word(8), word(96), word(16)),
(
@@ -4161,7 +4161,11 @@ mod direct_calls {
assert_eq!(&cell[..2], &[0x1000, 0x1001]);
assert_eq!(cell[2], if in_cell { address + 48 } else { 0 });
assert_eq!(cell[3] as u32, FUNCTION_WORDS[0] as u32, "compressed outer environment");
- assert_eq!(cell[4], callee.function.as_ptr() as u64, "function object");
+ assert_eq!(
+ cell[4] as u32,
+ (callee.function.as_ptr() as u64 >> 3) as u32,
+ "compressed function object"
+ );
assert_eq!(cell[5], if binds_this { value::int32(3) } else { 0 });
assert_eq!(heap, [164, 10_000, 1064]);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index ca0fcc854ec..48a93ae8236 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -578,18 +578,15 @@ pub struct EnvironmentTemplateSnapshot {
/// what they point to lives as long as the function.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FunctionFrameFields {
- pub script_or_module: [u64; 2],
+ pub script_or_module: u64,
pub environment: u64,
pub private_environment: u64,
}
impl FunctionFrameFields {
- /// Whether the functions have the same `[[ScriptOrModule]]`: the tag in
- /// the low byte of the first word (whose other bytes are padding) and
- /// the record in the second.
+ /// Whether the functions have the same `[[ScriptOrModule]]`.
pub fn has_script_or_module_of(&self, other: &FunctionFrameFields) -> bool {
- self.script_or_module[0] as u8 == other.script_or_module[0] as u8
- && self.script_or_module[1] == other.script_or_module[1]
+ self.script_or_module == other.script_or_module
}
}
@@ -1507,7 +1504,7 @@ pub struct RuntimeOffsets {
pub execution_context_function: u32,
/// `ExecutionContext::realm` (cell pointer).
pub execution_context_realm: u32,
- /// `ExecutionContext::script_or_module` (16 bytes).
+ /// `ExecutionContext::script_or_module` (8 bytes).
pub execution_context_script_or_module: u32,
/// `ExecutionContext::variable_environment` (cell pointer).
pub execution_context_variable_environment: u32,
@@ -1546,7 +1543,7 @@ pub struct RuntimeOffsets {
/// `EcmascriptFunctionObjectWithRareData::private_environment` (cell
/// pointer), of functions with the flag for it.
pub ecmascript_function_private_environment: u32,
- /// `SharedFunctionInstanceData::script_or_module` (16 bytes, as in `ExecutionContext`).
+ /// `SharedFunctionInstanceData::script_or_module` (8 bytes, as in `ExecutionContext`).
pub shared_function_script_or_module: u32,
/// `Object::function_bits` (u8).
pub object_function_bits: u32,
@@ -1823,9 +1820,9 @@ pub struct RuntimeLayout {
/// `GeneratorObject::pending_completion_type` (u32): the type of that
/// completion, as `GetCompletionFields` writes it.
pub generator_object_pending_completion_type: u32,
- /// `DeclarativeEnvironment::binding_values.size` (u64).
+ /// `DeclarativeEnvironment::binding_values.size` (u32).
pub declarative_environment_binding_values_size: u32,
- /// The capacity (u64) of `DeclarativeEnvironment::binding_values`.
+ /// The capacity (u32) of `DeclarativeEnvironment::binding_values`.
pub declarative_environment_binding_values_capacity: u32,
/// The pointer to the first binding name (a `Utf16FlyString`, one
/// word) of an `EnvironmentShape`.
diff --git a/Libraries/LibJS/Runtime/ExecutionContext.h b/Libraries/LibJS/Runtime/ExecutionContext.h
index 832fa2f20a4..460a478ce83 100644
--- a/Libraries/LibJS/Runtime/ExecutionContext.h
+++ b/Libraries/LibJS/Runtime/ExecutionContext.h
@@ -9,6 +9,7 @@
#pragma once
+#include <AK/BitCast.h>
#include <AK/Checked.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/Optional.h>
@@ -27,23 +28,21 @@
namespace JS {
-// [[ScriptOrModule]]: null, a Script Record or a Module Record. The Rust runtime puts the tag before the record, so
-// this type keeps that layout rather than being a Variant<Empty, GC::Ref<Script>, GC::Ref<Module>>, whose index
-// follows its storage, and offers the part of Variant's interface that LibJS's users call.
+// [[ScriptOrModule]]: null, a Script Record or a Module Record, in the one word the Rust runtime keeps it in: zero for
+// null, otherwise the pointer to the record with its lowest bit set for a module. It offers the part of
+// Variant<Empty, GC::Ref<Script>, GC::Ref<Module>>'s interface that LibJS's users call.
class ScriptOrModule {
public:
ScriptOrModule() { }
ScriptOrModule(Empty) { }
ScriptOrModule(GC::Ref<Script> script)
- : m_tag(Tag::Script)
- , m_script(script)
+ : m_bits(bit_cast<FlatPtr>(script.ptr()))
{
}
ScriptOrModule(GC::Ref<Module> module)
- : m_tag(Tag::Module)
- , m_module(module)
+ : m_bits(bit_cast<FlatPtr>(module.ptr()) | JS_LAYOUT_SCRIPT_OR_MODULE_MODULE_BIT)
{
}
@@ -51,111 +50,40 @@ public:
bool has() const
{
if constexpr (IsSame<T, Empty>)
- return m_tag == Tag::Empty;
+ return m_bits == 0;
else if constexpr (IsSame<T, GC::Ref<Script>>)
- return m_tag == Tag::Script;
+ return m_bits != 0 && !(m_bits & JS_LAYOUT_SCRIPT_OR_MODULE_MODULE_BIT);
else if constexpr (IsSame<T, GC::Ref<Module>>)
- return m_tag == Tag::Module;
+ return m_bits & JS_LAYOUT_SCRIPT_OR_MODULE_MODULE_BIT;
else
static_assert(DependentFalse<T>, "A ScriptOrModule holds Empty, GC::Ref<Script> or GC::Ref<Module>");
}
- template<typename T>
- T& get()
- {
- VERIFY(has<T>());
- return alternative<T>();
- }
-
- template<typename T>
- T const& get() const
- {
- VERIFY(has<T>());
- return const_cast<ScriptOrModule&>(*this).alternative<T>();
- }
-
- template<typename T>
- T* get_pointer()
- {
- return has<T>() ? &alternative<T>() : nullptr;
- }
-
- template<typename T>
- T const* get_pointer() const
- {
- return has<T>() ? &const_cast<ScriptOrModule&>(*this).alternative<T>() : nullptr;
- }
-
- template<typename... Functions>
- decltype(auto) visit(Functions&&... functions)
- {
- return visit_alternative(*this, OverloadedVisitor<RemoveCVReference<Functions>...> { forward<Functions>(functions)... });
- }
-
template<typename... Functions>
decltype(auto) visit(Functions&&... functions) const
{
- return visit_alternative(*this, OverloadedVisitor<RemoveCVReference<Functions>...> { forward<Functions>(functions)... });
+ OverloadedVisitor<RemoveCVReference<Functions>...> visitor { forward<Functions>(functions)... };
+ if (has<GC::Ref<Script>>()) {
+ GC::Ref<Script> script = *bit_cast<Script*>(m_bits);
+ return visitor(script);
+ }
+ if (has<GC::Ref<Module>>()) {
+ GC::Ref<Module> module = *bit_cast<Module*>(m_bits & ~static_cast<FlatPtr>(JS_LAYOUT_SCRIPT_OR_MODULE_MODULE_BIT));
+ return visitor(module);
+ }
+ Empty empty;
+ return visitor(empty);
}
- bool operator==(ScriptOrModule const& other) const
- {
- return m_tag == other.m_tag && m_cell_or_null == other.m_cell_or_null;
- }
+ bool operator==(ScriptOrModule const&) const = default;
private:
- enum class Tag : u8 {
- Empty = JS_LAYOUT_SCRIPT_OR_MODULE_TAG_EMPTY,
- Script = JS_LAYOUT_SCRIPT_OR_MODULE_TAG_SCRIPT,
- Module = JS_LAYOUT_SCRIPT_OR_MODULE_TAG_MODULE,
- };
-
template<typename... Functions>
struct AK_COMPACT_EMPTY_BASES OverloadedVisitor : Functions... {
using Functions::operator()...;
};
- template<typename T>
- T& alternative()
- {
- if constexpr (IsSame<T, Empty>)
- return m_empty;
- else if constexpr (IsSame<T, GC::Ref<Script>>)
- return m_script;
- else
- return m_module;
- }
-
- template<typename Self, typename Visitor>
- static decltype(auto) visit_alternative(Self& self, Visitor&& visitor)
- {
- auto& mutable_self = const_cast<ScriptOrModule&>(self);
- switch (self.m_tag) {
- case Tag::Script:
- return visitor(static_cast<CopyConst<Self, GC::Ref<Script>>&>(mutable_self.m_script));
- case Tag::Module:
- return visitor(static_cast<CopyConst<Self, GC::Ref<Module>>&>(mutable_self.m_module));
- case Tag::Empty:
- break;
- }
- return visitor(static_cast<CopyConst<Self, Empty>&>(mutable_self.m_empty));
- }
-
- Tag m_tag { Tag::Empty };
- // The payload is the cell for a script or a module, and null for an empty one.
- union {
- void* m_cell_or_null { nullptr };
- GC::Ref<Script> m_script;
- GC::Ref<Module> m_module;
- };
- // Empty has no bits, so it lives outside the payload, which the runtime reads.
- NO_UNIQUE_ADDRESS Empty m_empty;
-
- static constexpr void assert_layout_matches_the_runtime()
- {
- static_assert(__builtin_offsetof(ScriptOrModule, m_tag) == JS_LAYOUT_SCRIPT_OR_MODULE_TAG_OFFSET);
- static_assert(__builtin_offsetof(ScriptOrModule, m_cell_or_null) == JS_LAYOUT_SCRIPT_OR_MODULE_PAYLOAD_OFFSET);
- }
+ FlatPtr m_bits { 0 };
};
static_assert(sizeof(ScriptOrModule) == JS_LAYOUT_SCRIPT_OR_MODULE_SIZE);
diff --git a/Libraries/LibJS/Rust/generate/layout_header.rs b/Libraries/LibJS/Rust/generate/layout_header.rs
index 5d63d347828..6003d4ef635 100644
--- a/Libraries/LibJS/Rust/generate/layout_header.rs
+++ b/Libraries/LibJS/Rust/generate/layout_header.rs
@@ -243,13 +243,6 @@ macro_rules! check_host_object_abi_constants {
};
}
-/// The C layout that #[repr(C, u8)] gives ScriptOrModule: the tag, then the payload of the variant.
-#[repr(C)]
-struct ScriptOrModuleRepresentation {
- tag: u8,
- payload: usize,
-}
-
/// Spells a class name such as RawJSONObject the way C spells constants, RAW_JSON_OBJECT.
fn screaming_snake_case(name: &str) -> String {
let characters: Vec<char> = name.chars().collect();
@@ -359,15 +352,9 @@ pub fn generate() -> LayoutHeader {
size!(w, "EXECUTION_CONTEXT", ExecutionContext);
w.define("EXECUTION_CONTEXT_ALIGN", align_of::<ExecutionContext>());
- w.section("ScriptOrModule, a tag and the script or module cell it names");
- assert_eq!(size_of::<ScriptOrModuleRepresentation>(), size_of::<ScriptOrModule>());
- assert_eq!(align_of::<ScriptOrModuleRepresentation>(), align_of::<ScriptOrModule>());
- w.define("SCRIPT_OR_MODULE_TAG_OFFSET", offset_of!(ScriptOrModuleRepresentation, tag));
- w.define("SCRIPT_OR_MODULE_PAYLOAD_OFFSET", offset_of!(ScriptOrModuleRepresentation, payload));
- size!(w, "SCRIPT_OR_MODULE", ScriptOrModule);
- w.define("SCRIPT_OR_MODULE_TAG_EMPTY", SCRIPT_OR_MODULE_TAG_EMPTY);
- w.define("SCRIPT_OR_MODULE_TAG_SCRIPT", SCRIPT_OR_MODULE_TAG_SCRIPT);
- w.define("SCRIPT_OR_MODULE_TAG_MODULE", SCRIPT_OR_MODULE_TAG_MODULE);
+ w.section("ScriptOrModule, the script or module cell it names in one word");
+ size!(w, "SCRIPT_OR_MODULE", ScriptOrModuleSlot);
+ w.define("SCRIPT_OR_MODULE_MODULE_BIT", SCRIPT_OR_MODULE_SLOT_MODULE_BIT);
w.section("VM, whose head is at its start");
offset!(w, "VM_RUNNING_EXECUTION_CONTEXT", VmHead, running_execution_context);
diff --git a/Libraries/LibJS/Rust/generate/layout_table.rs b/Libraries/LibJS/Rust/generate/layout_table.rs
index 4ac1fb18543..1bd2b92b17d 100644
--- a/Libraries/LibJS/Rust/generate/layout_table.rs
+++ b/Libraries/LibJS/Rust/generate/layout_table.rs
@@ -330,7 +330,7 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {
assert_eq!(align_of::<ExecutionContext>(), value_size);
field!(w, "EXECUTION_CONTEXT_FUNCTION", "ExecutionContext.function", "Object", ExecutionContext, function, 8, "nullable", "cell", "function_and_realm");
field!(w, "EXECUTION_CONTEXT_REALM", "ExecutionContext.realm", "Realm", ExecutionContext, realm, 8, "nullable", "cell", "function_and_realm");
- field!(w, "EXECUTION_CONTEXT_SCRIPT_OR_MODULE", "ExecutionContext.script_or_module", "ScriptOrModule", ExecutionContext, script_or_module, 16, "nullable", "scalar");
+ field!(w, "EXECUTION_CONTEXT_SCRIPT_OR_MODULE", "ExecutionContext.script_or_module", "u64", ExecutionContext, script_or_module, 8, "nullable", "scalar");
field!(w, "EXECUTION_CONTEXT_LEXICAL_ENVIRONMENT", "ExecutionContext.lexical_environment", "Environment", ExecutionContext, lexical_environment, 8, "nullable", "cell", "environments");
field!(w, "EXECUTION_CONTEXT_VARIABLE_ENVIRONMENT", "ExecutionContext.variable_environment", "Environment", ExecutionContext, variable_environment, 8, "nullable", "cell", "environments");
field!(w, "EXECUTION_CONTEXT_PRIVATE_ENVIRONMENT", "ExecutionContext.private_environment", "PrivateEnvironment", ExecutionContext, private_environment, 8, "nullable", "cell");
@@ -367,7 +367,7 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {
w.line("field ExecutionContext.saved_lexical_environment Value EXECUTION_CONTEXT_SAVED_LEXICAL_ENVIRONMENT nullable scalar return_and_saved_environment");
w.constant("ALIGNOF_EXECUTION_CONTEXT", align_of::<ExecutionContext>());
w.constant("EXECUTION_CONTEXT_NO_YIELD_CONTINUATION", ExecutionContext::NO_YIELD_CONTINUATION);
- size!(w, "SIZEOF_SCRIPT_OR_MODULE", ScriptOrModule);
+ size!(w, "SIZEOF_SCRIPT_OR_MODULE", ScriptOrModuleSlot);
size!(w, "SIZEOF_VALUE", Value);
w.section("InterpreterStack layout");
@@ -441,7 +441,7 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {
offset!(w, "OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_DATA", ObjectPropertyIteratorCacheData, property_values.data);
offset!(w, "OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_SIZE", ObjectPropertyIteratorCacheData, property_values.size);
w.line("field ObjectPropertyIteratorCacheData.property_values Sequence<Value> OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_DATA nullable scalar");
- w.line("field ObjectPropertyIteratorCacheData.property_value_count u64 OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_SIZE nullable scalar");
+ w.line("field ObjectPropertyIteratorCacheData.property_value_count u32 OBJECT_PROPERTY_ITERATOR_CACHE_DATA_PROPERTY_VALUES_SIZE nullable scalar");
w.section("PutKind enum");
w.constant("PUT_KIND_NORMAL", PutKind::Normal as u8);
@@ -451,7 +451,7 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {
w.section("DeclarativeEnvironment layout");
field!(w, "DECLARATIVE_ENVIRONMENT_RARE_DATA", "DeclarativeEnvironment.rare_data", "DeclarativeEnvironmentRareData", DeclarativeEnvironment, rare_data, 8, "nullable", "scalar");
- field!(w, "DECLARATIVE_ENVIRONMENT_SERIAL", "DeclarativeEnvironment.serial_number", "u64", DeclarativeEnvironment, serial_number, 8, "nullable", "scalar");
+ field!(w, "DECLARATIVE_ENVIRONMENT_SERIAL", "DeclarativeEnvironment.serial_number", "u64", GlobalDeclarativeEnvironment, serial_number, 8, "nullable", "scalar");
w.section("GlobalVariableCache layout");
offset!(w, "GLOBAL_VARIABLE_CACHE_ENTRY", GlobalVariableCache, entry);
@@ -498,14 +498,9 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {
w.constant("ECMASCRIPT_FUNCTION_FLAG_HAS_RARE_DATA", ecmascript_function_flags::HAS_RARE_DATA);
w.section("SharedFunctionInstanceData layout");
- field!(w, "SHARED_FUNCTION_INSTANCE_DATA_SCRIPT_OR_MODULE", "SharedFunctionInstanceData.script_or_module", "ScriptOrModule", SharedFunctionInstanceData, script_or_module, 16, "nullable", "scalar");
+ field!(w, "SHARED_FUNCTION_INSTANCE_DATA_SCRIPT_OR_MODULE", "SharedFunctionInstanceData.script_or_module", "u64", SharedFunctionInstanceData, script_or_module, 8, "nullable", "scalar");
field!(w, "SHARED_FUNCTION_INSTANCE_DATA_EXECUTABLE", "SharedFunctionInstanceData.executable", "Executable", SharedFunctionInstanceData, executable, 4, "nullable", "compressed");
field!(w, "SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA", "SharedFunctionInstanceData.asm_call_metadata", "u64", SharedFunctionInstanceData, asm_call_metadata, 8, "nullable", "scalar");
- offset!(w, "SHARED_FUNCTION_INSTANCE_DATA_FORMAL_PARAMETER_COUNT", SharedFunctionInstanceData, formal_parameter_count);
- offset!(w, "SHARED_FUNCTION_INSTANCE_DATA_STRICT", SharedFunctionInstanceData, strict);
- offset!(w, "SHARED_FUNCTION_INSTANCE_DATA_FUNCTION_ENVIRONMENT_NEEDED", SharedFunctionInstanceData, function_environment_needed);
- offset!(w, "SHARED_FUNCTION_INSTANCE_DATA_USES_THIS", SharedFunctionInstanceData, uses_this);
- offset!(w, "SHARED_FUNCTION_INSTANCE_DATA_CAN_INLINE_CALL", SharedFunctionInstanceData, can_inline_call);
w.constant("SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA_CAN_INLINE_CALL", asm_call_metadata::CAN_INLINE_CALL);
w.constant("SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA_NEEDS_ENVIRONMENT_OR_THIS_VALUE_RESOLUTION", asm_call_metadata::NEEDS_ENVIRONMENT_OR_THIS_VALUE_RESOLUTION);
w.constant("SHARED_FUNCTION_INSTANCE_DATA_ASM_CALL_METADATA_USES_THIS", asm_call_metadata::USES_THIS);
@@ -569,7 +564,7 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {
w.line("field DeclarativeEnvironmentRareData.binding_flags BindingFlags BINDING_FLAGS_DATA_PTR nonnull scalar");
offset!(w, "ENVIRONMENT_SHAPE_BINDING_FLAGS_DATA_PTR", EnvironmentShape, binding_flags.data);
offset!(w, "ENVIRONMENT_SHAPE_BINDING_FLAGS_SIZE", EnvironmentShape, binding_flags.size);
- w.line("field EnvironmentShape.binding_flags_size u64 ENVIRONMENT_SHAPE_BINDING_FLAGS_SIZE nullable scalar");
+ w.line("field EnvironmentShape.binding_flags_size u32 ENVIRONMENT_SHAPE_BINDING_FLAGS_SIZE nullable scalar");
w.line("field EnvironmentShape.binding_flags BindingFlags ENVIRONMENT_SHAPE_BINDING_FLAGS_DATA_PTR nonnull scalar");
w.section("EnvironmentCoordinate layout");
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index ff9be2772d1..e47b0c650df 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -1098,7 +1098,7 @@ pub struct ObjectPropertyIteratorCacheDataStorage {
define_cell!(ObjectPropertyIteratorCacheData, Other, finalize: finalize);
-const _: () = assert!(size_of::<ObjectPropertyIteratorCacheData>() == 72);
+const _: () = assert!(size_of::<ObjectPropertyIteratorCacheData>() == 64);
// SAFETY: Visits the shape, the validity, the materialized key values and the keys.
unsafe impl Trace for ObjectPropertyIteratorCacheData {
@@ -1345,10 +1345,11 @@ struct ExecutableParts {
}
fn interpreter_buffer<T>(elements: &[T]) -> InterpreterBuffer<T> {
+ let size = u32::try_from(elements.len()).expect("the number of elements fits in u32");
InterpreterBuffer {
data: Cell::new(elements.as_ptr().cast_mut()),
- size: Cell::new(elements.len()),
- capacity: Cell::new(elements.len()),
+ size: Cell::new(size),
+ capacity: Cell::new(size),
}
}
@@ -1468,10 +1469,13 @@ impl Executable {
property_lookup_caches: interpreter_buffer(&property_lookup_caches),
global_variable_caches: interpreter_buffer(&global_variable_caches),
// The interpreter only reads the caches, which slow paths update through their cells.
- environment_coordinate_caches: InterpreterBuffer {
- data: Cell::new(environment_coordinate_caches.as_ptr().cast_mut().cast()),
- size: Cell::new(environment_coordinate_caches.len()),
- capacity: Cell::new(environment_coordinate_caches.len()),
+ environment_coordinate_caches: {
+ let size = u32::try_from(environment_coordinate_caches.len()).expect("the cache count fits in u32");
+ InterpreterBuffer {
+ data: Cell::new(environment_coordinate_caches.as_ptr().cast_mut().cast()),
+ size: Cell::new(size),
+ capacity: Cell::new(size),
+ }
},
};
Self {
diff --git a/Libraries/LibJS/Rust/src/embedding/execution_context.rs b/Libraries/LibJS/Rust/src/embedding/execution_context.rs
index 1c8527ea942..9f78b083771 100644
--- a/Libraries/LibJS/Rust/src/embedding/execution_context.rs
+++ b/Libraries/LibJS/Rust/src/embedding/execution_context.rs
@@ -23,57 +23,32 @@ use crate::embedding::abi_types::{JSOwnedUtf16String, owned_utf16_string_into_ab
use crate::gc::capi::GCVisitor;
use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::execution_context::OwnedExecutionContext;
-use crate::layout::cell::Gc;
-use crate::layout::execution_context::{
- ExecutionContext, SCRIPT_OR_MODULE_TAG_EMPTY, SCRIPT_OR_MODULE_TAG_MODULE, SCRIPT_OR_MODULE_TAG_SCRIPT,
- ScriptOrModule,
-};
+use crate::layout::execution_context::{ExecutionContext, ScriptOrModule, ScriptOrModuleSlot};
use crate::layout::host_class::JSVM;
-use crate::runtime::module::Module;
-use crate::script::Script;
/// An execution context, laid out as the JS_LAYOUT_EXECUTION_CONTEXT_* values of LibJS/Embedding/Layout.h describe.
pub struct JSExecutionContext {
_opaque: [u8; 0],
}
-/// A ScriptOrModule, laid out like the field of an execution context. The tag is one of the
-/// JS_LAYOUT_SCRIPT_OR_MODULE_TAG_* values of LibJS/Embedding/Layout.h, and the cell is the Script or the Module, or
-/// null for an empty one.
-#[repr(C)]
-pub struct JSScriptOrModule {
- pub tag: u8,
- pub cell: *mut c_void,
-}
+/// A ScriptOrModule, laid out like the field of an execution context: zero for null, otherwise the pointer to the
+/// Script or the Module, with JS_LAYOUT_SCRIPT_OR_MODULE_MODULE_BIT set for a module.
+#[repr(transparent)]
+pub struct JSScriptOrModule(u64);
-const _: () = assert!(size_of::<JSScriptOrModule>() == size_of::<ScriptOrModule>());
-const _: () = assert!(align_of::<JSScriptOrModule>() == align_of::<ScriptOrModule>());
+const _: () = assert!(size_of::<JSScriptOrModule>() == size_of::<ScriptOrModuleSlot>());
impl From<ScriptOrModule> for JSScriptOrModule {
fn from(script_or_module: ScriptOrModule) -> Self {
- let (tag, cell) = match script_or_module {
- ScriptOrModule::Empty => (SCRIPT_OR_MODULE_TAG_EMPTY, core::ptr::null_mut()),
- ScriptOrModule::Script(script) => (SCRIPT_OR_MODULE_TAG_SCRIPT, script.as_ptr().cast()),
- ScriptOrModule::Module(module) => (SCRIPT_OR_MODULE_TAG_MODULE, module.as_ptr().cast()),
- };
- Self { tag, cell }
+ Self(ScriptOrModuleSlot::new(script_or_module).word())
}
}
/// # Safety
///
-/// The cell of `script_or_module` must be a live Script or Module, as its tag says, unless the tag is the empty one.
+/// `script_or_module` must be empty or name a live Script or Module.
pub unsafe fn script_or_module_from_abi(script_or_module: JSScriptOrModule) -> ScriptOrModule {
- let cell = || NonNull::new(script_or_module.cell).expect("a script or module has its cell");
- // SAFETY: The caller guarantees that the cell is a live record of the kind the tag names.
- unsafe {
- match script_or_module.tag {
- SCRIPT_OR_MODULE_TAG_EMPTY => ScriptOrModule::Empty,
- SCRIPT_OR_MODULE_TAG_SCRIPT => ScriptOrModule::Script(Gc::from_non_null(cell().cast::<Script>())),
- SCRIPT_OR_MODULE_TAG_MODULE => ScriptOrModule::Module(Gc::from_non_null(cell().cast::<Module>())),
- tag => panic!("{tag} is not the tag of a script or module"),
- }
- }
+ ScriptOrModuleSlot::from_word(script_or_module.0).get()
}
fn execution_context_from_abi(execution_context: *mut JSExecutionContext) -> NonNull<ExecutionContext> {
diff --git a/Libraries/LibJS/Rust/src/gc/class.rs b/Libraries/LibJS/Rust/src/gc/class.rs
index da4ccd888af..4bd1b46dce2 100644
--- a/Libraries/LibJS/Rust/src/gc/class.rs
+++ b/Libraries/LibJS/Rust/src/gc/class.rs
@@ -9,7 +9,7 @@ use core::ffi::{c_char, c_void};
use super::capi::GCVisitor;
use super::class_id::ClassId;
use super::visitor::{Trace, Visitor};
-use crate::layout::cell::{CellHeader, CellKind, CellState};
+use crate::layout::cell::{CellHeader, CellHeaderTail, CellKind, CellState};
use crate::runtime::object::ObjectMethods;
#[cfg(feature = "address-sanitizer")]
@@ -72,7 +72,7 @@ impl Class {
object_methods: Option<&'static ObjectMethods>,
finalize: Option<unsafe extern "C" fn(cell: *mut c_void)>,
) -> Self {
- assert!(size_of::<T>() >= MIN_CELL_SIZE);
+ // NB: Heap::allocate() checks MIN_CELL_SIZE, as a class that is only a base of others may be smaller.
assert!(size_of::<T>().is_multiple_of(8));
assert!(align_of::<T>() <= MAX_CELL_ALIGNMENT);
assert!(
@@ -397,6 +397,17 @@ impl<T> crate::layout::cell::Gc<T> {
}
}
+impl CellHeaderTail {
+ /// The header of a cell of `class` that keeps fields of its own in the first word, like `CellHeader::for_class()`.
+ pub fn for_class(class: &'static Class) -> Self {
+ Self {
+ mark: false.into(),
+ state: CellState::Live.into(),
+ kind: class.kind(),
+ }
+ }
+}
+
impl CellHeader {
/// The header of a cell of `class`, which must also be the class of the allocator the cell comes from.
pub fn for_class(class: &'static Class) -> Self {
diff --git a/Libraries/LibJS/Rust/src/gc/class_id.rs b/Libraries/LibJS/Rust/src/gc/class_id.rs
index bbeda4afb6d..234d6647b05 100644
--- a/Libraries/LibJS/Rust/src/gc/class_id.rs
+++ b/Libraries/LibJS/Rust/src/gc/class_id.rs
@@ -42,6 +42,7 @@ define_class_ids! {
ProxyObject,
Environment,
DeclarativeEnvironment,
+ GlobalDeclarativeEnvironment,
FunctionEnvironment,
ModuleEnvironment,
EnvironmentShape,
diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rs
index 95631308249..2625b1a6150 100644
--- a/Libraries/LibJS/Rust/src/gc/heap.rs
+++ b/Libraries/LibJS/Rust/src/gc/heap.rs
@@ -11,7 +11,7 @@ use core::ptr::NonNull;
use std::collections::HashMap;
use super::capi::{self, GCAllocator, GCGatherRootsCallback, GCHeap, GCLayout};
-use super::class::{BLOCK_CLASS_OFFSET, BLOCK_CLASS_TAIL_TAG, BLOCK_SIZE, CellTypeInfo, Class, GcCell};
+use super::class::{BLOCK_CLASS_OFFSET, BLOCK_CLASS_TAIL_TAG, BLOCK_SIZE, CellTypeInfo, Class, GcCell, MIN_CELL_SIZE};
use super::class_id::{CLASS_COUNT, ClassId};
use super::defer_gc::DeferGc;
use super::weak::WEAK_IMPL_POINTER_OFFSET;
@@ -240,6 +240,7 @@ impl Heap {
/// Moves the cell that `build` returns into the heap, with collections deferred from before `build` runs until
/// the cell is in the heap.
pub fn allocate<T: GcCell>(&self, build: impl FnOnce(&DeferGc<'_>) -> T) -> Gc<T> {
+ const { assert!(size_of::<T>() >= MIN_CELL_SIZE) };
let allocator = self.allocator_for(T::CLASS);
// SAFETY: The allocator is the one of the cell's static class, whose cells have the size and alignment of a T.
unsafe { self.allocate_with(allocator, size_of::<T>(), AllocationKind::Cell, build, |_| {}) }
diff --git a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs
index aea0a0e76d5..1341520b812 100644
--- a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs
+++ b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs
@@ -38,11 +38,21 @@ impl<T: Copy> InterpreterBuffer<T> {
}
pub fn size(&self) -> usize {
- self.size.get()
+ self.size.get() as usize
}
pub fn capacity(&self) -> usize {
- self.capacity.get()
+ self.capacity.get() as usize
+ }
+
+ fn set_size(&self, size: usize) {
+ self.size
+ .set(u32::try_from(size).expect("the size of a buffer fits in u32"));
+ }
+
+ fn set_capacity(&self, capacity: usize) {
+ self.capacity
+ .set(u32::try_from(capacity).expect("the capacity of a buffer fits in u32"));
}
pub fn is_empty(&self) -> bool {
@@ -76,7 +86,7 @@ impl<T: Copy> InterpreterBuffer<T> {
}
// SAFETY: The buffer has room for one more element.
unsafe { self.data.get().add(size).write(value) };
- self.size.set(size + 1);
+ self.set_size(size + 1);
}
/// Makes room for `needed_capacity` elements in total, exactly like AK::Vector::ensure_capacity.
@@ -107,7 +117,7 @@ impl<T: Copy> InterpreterBuffer<T> {
pub unsafe fn use_unowned_storage(&self, data: *mut T, capacity: usize) {
assert!(self.data.get().is_null());
self.data.set(data);
- self.capacity.set(capacity);
+ self.set_capacity(capacity);
}
/// Moves the elements from storage the buffer does not own to storage of its own, with room for at least
@@ -153,7 +163,7 @@ impl<T: Copy> InterpreterBuffer<T> {
unsafe { dealloc(old_data.cast(), old_layout) };
}
self.data.set(new_data);
- self.capacity.set(new_capacity);
+ self.set_capacity(new_capacity);
}
}
diff --git a/Libraries/LibJS/Rust/src/interpreter/execution_context.rs b/Libraries/LibJS/Rust/src/interpreter/execution_context.rs
index 8f7feedc54d..7b2c6a4d2ba 100644
--- a/Libraries/LibJS/Rust/src/interpreter/execution_context.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/execution_context.rs
@@ -9,7 +9,7 @@ use core::ptr::NonNull;
use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
use crate::gc::visitor::{Trace, Visitor};
-use crate::layout::execution_context::{ExecutionContext, ScriptOrModule};
+use crate::layout::execution_context::{ExecutionContext, ScriptOrModule, ScriptOrModuleSlot};
use crate::layout::value::Value;
use libjs_abi::register::RESERVED_REGISTER_COUNT;
@@ -32,7 +32,7 @@ impl ExecutionContext {
context.write(ExecutionContext {
function: Cell::new(None),
realm: Cell::new(None),
- script_or_module: Cell::new(ScriptOrModule::Empty),
+ script_or_module: ScriptOrModuleSlot::new(ScriptOrModule::Empty),
lexical_environment: Cell::new(None),
variable_environment: Cell::new(None),
private_environment: Cell::new(None),
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 143b0e7e1e9..1ab1a3231e8 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -11,6 +11,7 @@ use core::ptr::NonNull;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
+use std::rc::Rc;
use ak::{Utf16FlyString, Utf16String};
use libjs_runtime_macros::Trace;
@@ -522,6 +523,8 @@ pub struct Vm {
roots: RootSet,
pub names: CommonPropertyNames,
+ /// What functions without parameter names share, since an empty Rc slice is an allocation of its own.
+ pub(crate) no_parameter_names: Rc<[Utf16FlyString]>,
/// The strings in these two caches are weak: the sweep callback drops the ones that die.
string_to_atom_cache: RefCell<Box<[StringToAtomCacheEntry; STRING_TO_ATOM_CACHE_SIZE]>>,
fly_string_cache: Box<[Cell<Option<Gc<PrimitiveString>>>; FLY_STRING_CACHE_SIZE]>,
@@ -678,6 +681,7 @@ impl Vm {
native_function_indices: RefCell::new(HashMap::new()),
roots: RootSet::default(),
names: CommonPropertyNames::new(),
+ no_parameter_names: Rc::from([]),
string_to_atom_cache: RefCell::new(Box::new(core::array::from_fn(|_| StringToAtomCacheEntry::default()))),
fly_string_cache: Box::new([const { Cell::new(None) }; FLY_STRING_CACHE_SIZE]),
numeric_string_cache: Box::new([const { Cell::new(None) }; NUMERIC_STRING_CACHE_SIZE]),
diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rs
index d355314a8bb..a97b0e0836a 100644
--- a/Libraries/LibJS/Rust/src/jit/allocation.rs
+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs
@@ -312,7 +312,7 @@ pub fn make_call_environment_template(vm: &Vm, function: Gc<EcmascriptFunctionOb
core::mem::offset_of!(Environment, outer),
size_of::<NullableMember<Environment>>(),
),
- (FUNCTION_ENVIRONMENT_FUNCTION_OBJECT_OFFSET, 8),
+ (FUNCTION_ENVIRONMENT_FUNCTION_OBJECT_OFFSET, 4),
(FUNCTION_ENVIRONMENT_THIS_VALUE_OFFSET, 8),
] {
clear_bytes(&mut template.words, offset, size);
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index 1b868264a02..d3461efbaa5 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -37,7 +37,7 @@ use crate::layout::accessor::Accessor;
use crate::layout::cell::Gc;
use crate::layout::environment::{
BINDING_FLAG_MUTABLE, DeclarativeEnvironment, DeclarativeEnvironmentRareData, Environment, EnvironmentShape,
- PrivateEnvironment,
+ GlobalDeclarativeEnvironment, PrivateEnvironment,
};
use crate::layout::executable::ExecutableHead;
use crate::layout::execution_context::ExecutionContext;
@@ -280,7 +280,7 @@ fn runtime_layout() -> RuntimeLayout {
rare_data_binding_flags: offset(offset_of!(DeclarativeEnvironmentRareData, binding_flags.data)),
environment_shape_binding_flags_size: offset(offset_of!(EnvironmentShape, binding_flags.size)),
environment_shape_binding_flags: offset(offset_of!(EnvironmentShape, binding_flags.data)),
- declarative_environment_serial: offset(offset_of!(DeclarativeEnvironment, serial_number)),
+ declarative_environment_serial: offset(offset_of!(GlobalDeclarativeEnvironment, serial_number)),
realm_global_object: offset(offset_of!(Realm, global_object)),
realm_global_declarative_environment: offset(offset_of!(Realm, global_declarative_environment)),
executable_global_variable_caches: offset(offset_of!(ExecutableHead, global_variable_caches.data)),
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index ffe0ab79422..0166a37cf68 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -7,7 +7,6 @@
//! Snapshots of executables for compile jobs, captured on the main thread straight from the runtime's structures.
//! A snapshot refers to cells only by address; the cells it captured are kept alive by whoever owns the job.
-use core::mem::offset_of;
use libjs_abi::Builtin;
use std::collections::HashMap;
@@ -37,9 +36,8 @@ use crate::gc::defer_gc::{DeferGc, Deferred};
use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, Gc};
use crate::layout::environment::DeclarativeEnvironment;
-use crate::layout::execution_context::ExecutionContext;
use crate::layout::function_object::{
- DirectGetterFunction, EcmascriptFunctionObject, FunctionObject, RawNativeFunction, SharedFunctionInstanceData,
+ DirectGetterFunction, EcmascriptFunctionObject, FunctionObject, RawNativeFunction,
};
use crate::layout::object::{Object, TYPED_ARRAY_CACHED_DATA_OFFSET_INVALID, TypedArrayBase};
use crate::layout::property_lookup_cache::{GlobalVariableCache, PropertyLookupCache, PropertyLookupCacheEntryType};
@@ -359,13 +357,7 @@ fn native_call_target(vm: &Vm, feedback: &CallFeedback) -> Option<Gc<RawNativeFu
fn function_frame_fields(function: Gc<EcmascriptFunctionObject>) -> FunctionFrameFields {
let shared_data = function.shared_data();
FunctionFrameFields {
- script_or_module: [
- word_of(shared_data, offset_of!(SharedFunctionInstanceData, script_or_module)),
- word_of(
- shared_data,
- offset_of!(SharedFunctionInstanceData, script_or_module) + 8,
- ),
- ],
+ script_or_module: shared_data.script_or_module.word(),
environment: function
.environment()
.map_or(0, |environment| environment.as_ptr() as u64),
@@ -375,19 +367,6 @@ fn function_frame_fields(function: Gc<EcmascriptFunctionObject>) -> FunctionFram
}
}
-/// The words of the `[[ScriptOrModule]]` of a frame, like `function_frame_fields()` has them of a function.
-fn script_or_module_words(frame: &ExecutionContext) -> [u64; 2] {
- let address = core::ptr::from_ref(&frame.script_or_module).cast::<u64>();
- // SAFETY: The field is two words.
- unsafe { [address.read_unaligned(), address.add(1).read_unaligned()] }
-}
-
-/// The words at `offset` of a cell.
-fn word_of<T>(cell: Gc<T>, offset: usize) -> u64 {
- // SAFETY: The callers read fields of the cell that are words.
- unsafe { cell.as_ptr().cast::<u8>().add(offset).cast::<u64>().read_unaligned() }
-}
-
impl SnapshotBuilder<'_> {
fn cell<T: Extends<CellHeader>>(&mut self, cell: Gc<T>) -> CellId {
let header = cell.upcast::<CellHeader>();
@@ -1274,7 +1253,7 @@ pub fn capture_snapshot<'d>(
let compiled_function_fields = match function {
Some(function) => function_frame_fields(function),
None => FunctionFrameFields {
- script_or_module: script_or_module_words(vm.running_execution_context_ref()),
+ script_or_module: vm.running_execution_context_ref().script_or_module.word(),
..FunctionFrameFields::default()
},
};
diff --git a/Libraries/LibJS/Rust/src/layout/buffer.rs b/Libraries/LibJS/Rust/src/layout/buffer.rs
index de0308aac2b..3931ed08ec8 100644
--- a/Libraries/LibJS/Rust/src/layout/buffer.rs
+++ b/Libraries/LibJS/Rust/src/layout/buffer.rs
@@ -11,6 +11,8 @@ use core::cell::Cell;
#[repr(C)]
pub struct InterpreterBuffer<T> {
pub data: Cell<*mut T>,
- pub size: Cell<usize>,
- pub capacity: Cell<usize>,
+ pub size: Cell<u32>,
+ pub capacity: Cell<u32>,
}
+
+const _: () = assert!(size_of::<InterpreterBuffer<u8>>() == 16);
diff --git a/Libraries/LibJS/Rust/src/layout/cell.rs b/Libraries/LibJS/Rust/src/layout/cell.rs
index 6b39319f9f2..bb6703c52a6 100644
--- a/Libraries/LibJS/Rust/src/layout/cell.rs
+++ b/Libraries/LibJS/Rust/src/layout/cell.rs
@@ -91,6 +91,16 @@ pub struct CellHeader {
const _: () = assert!(size_of::<CellHeader>() == 11);
+/// The header of a cell that keeps fields of its own in the first word, which comes right after those fields.
+#[repr(C, packed)]
+pub struct CellHeaderTail {
+ pub mark: Cell<bool>,
+ pub state: Cell<CellState>,
+ pub kind: CellKind,
+}
+
+const _: () = assert!(size_of::<CellHeaderTail>() == 3);
+
/// Added to the class that the block of an allocator holds when the classes that extend it share the allocator, whose
/// cells each keep their own class in the word after the cell_size bytes of that class.
pub const BLOCK_CLASS_TAIL_TAG: usize = 1;
diff --git a/Libraries/LibJS/Rust/src/layout/environment.rs b/Libraries/LibJS/Rust/src/layout/environment.rs
index a8439d275cf..68b41519009 100644
--- a/Libraries/LibJS/Rust/src/layout/environment.rs
+++ b/Libraries/LibJS/Rust/src/layout/environment.rs
@@ -7,7 +7,7 @@
use core::cell::Cell;
use super::buffer::InterpreterBuffer;
-use super::cell::{CellHeader, Gc};
+use super::cell::{CellHeader, CellHeaderTail, Gc};
use super::member::NullableMember;
use super::object::Object;
use super::value::Value;
@@ -20,28 +20,35 @@ pub const BINDING_FLAG_MUTABLE: u8 = 1 << 1;
#[repr(C)]
pub struct Environment {
- pub header: CellHeader,
+ pub outer: NullableMember<Environment>,
+ /// The shape of a declarative environment (null for other environments).
+ pub shape: NullableMember<EnvironmentShape>,
+ pub header: CellHeaderTail,
pub this_binding_status: Cell<u8>,
pub permanently_screwed_by_eval: Cell<bool>,
pub declarative: Cell<bool>,
/// Whether the binding values of a declarative environment are stored in its cell, after the fields of its class.
pub binding_values_are_inline: Cell<bool>,
- pub outer: NullableMember<Environment>,
- /// The shape of a declarative environment, in what would otherwise be padding (null for other environments).
- pub shape: NullableMember<EnvironmentShape>,
}
-const _: () = assert!(size_of::<Environment>() == 24);
+const _: () = assert!(size_of::<Environment>() == 16);
#[repr(C)]
pub struct DeclarativeEnvironment {
pub base: Environment,
pub binding_values: InterpreterBuffer<Value>,
pub rare_data: Cell<*mut DeclarativeEnvironmentRareData>,
- pub serial_number: Cell<u64>,
}
-const _: () = assert!(size_of::<DeclarativeEnvironment>() == 64);
+const _: () = assert!(size_of::<DeclarativeEnvironment>() == 40);
+
+/// The declarative environment of a global environment. Caches of global variables hold on to its serial number, which
+/// changes when the bindings do.
+#[repr(C)]
+pub struct GlobalDeclarativeEnvironment {
+ pub base: DeclarativeEnvironment,
+ pub serial_number: Cell<u64>,
+}
#[repr(C)]
pub struct DeclarativeEnvironmentRareData {
diff --git a/Libraries/LibJS/Rust/src/layout/execution_context.rs b/Libraries/LibJS/Rust/src/layout/execution_context.rs
index 25ad65c344b..9284c78cc03 100644
--- a/Libraries/LibJS/Rust/src/layout/execution_context.rs
+++ b/Libraries/LibJS/Rust/src/layout/execution_context.rs
@@ -5,6 +5,7 @@
*/
use core::cell::Cell;
+use core::ptr::NonNull;
use super::cell::Gc;
use super::environment::{Environment, PrivateEnvironment};
@@ -14,20 +15,61 @@ use super::realm::Realm;
use super::value::Value;
use crate::layout_forward::{Module, Script};
-pub const SCRIPT_OR_MODULE_TAG_EMPTY: u8 = 0;
-pub const SCRIPT_OR_MODULE_TAG_SCRIPT: u8 = 1;
-pub const SCRIPT_OR_MODULE_TAG_MODULE: u8 = 2;
-
-/// Mirrors JS::ScriptOrModule. The interpreter clears the field by zeroing it, so all-zero bytes must mean Empty.
+/// [[ScriptOrModule]]: null, a Script Record or a Module Record.
#[derive(Clone, Copy)]
-#[repr(C, u8)]
pub enum ScriptOrModule {
- Empty = SCRIPT_OR_MODULE_TAG_EMPTY,
- Script(Gc<Script>) = SCRIPT_OR_MODULE_TAG_SCRIPT,
- Module(Gc<Module>) = SCRIPT_OR_MODULE_TAG_MODULE,
+ Empty,
+ Script(Gc<Script>),
+ Module(Gc<Module>),
}
-const _: () = assert!(size_of::<ScriptOrModule>() == 16);
+/// A ScriptOrModule in one word, which is what frames and shared function data keep: zero for Empty, otherwise the
+/// pointer to the cell with its lowest bit set for a module. The interpreter copies it around and clears it by zeroing.
+#[repr(transparent)]
+pub struct ScriptOrModuleSlot(Cell<u64>);
+
+pub const SCRIPT_OR_MODULE_SLOT_MODULE_BIT: u64 = 1;
+
+impl ScriptOrModuleSlot {
+ pub fn new(value: ScriptOrModule) -> Self {
+ Self(Cell::new(Self::encode(value)))
+ }
+
+ fn encode(value: ScriptOrModule) -> u64 {
+ match value {
+ ScriptOrModule::Empty => 0,
+ ScriptOrModule::Script(script) => script.as_ptr() as u64,
+ ScriptOrModule::Module(module) => module.as_ptr() as u64 | SCRIPT_OR_MODULE_SLOT_MODULE_BIT,
+ }
+ }
+
+ pub fn get(&self) -> ScriptOrModule {
+ let word = self.0.get();
+ let Some(pointer) = NonNull::new((word & !SCRIPT_OR_MODULE_SLOT_MODULE_BIT) as *mut u8) else {
+ return ScriptOrModule::Empty;
+ };
+ // SAFETY: A slot holds what encode() made of a live script or module, which whoever holds the slot traces.
+ unsafe {
+ if word & SCRIPT_OR_MODULE_SLOT_MODULE_BIT != 0 {
+ ScriptOrModule::Module(Gc::from_non_null(pointer.cast()))
+ } else {
+ ScriptOrModule::Script(Gc::from_non_null(pointer.cast()))
+ }
+ }
+ }
+
+ pub fn set(&self, value: ScriptOrModule) {
+ self.0.set(Self::encode(value));
+ }
+
+ pub fn word(&self) -> u64 {
+ self.0.get()
+ }
+
+ pub fn from_word(word: u64) -> Self {
+ Self(Cell::new(word))
+ }
+}
/// Mirrors JS::ExecutionContext field for field: the interpreter builds whole frames inline, so a field it does not
/// know about would be left uninitialized in those frames. The frame's value slots follow it directly.
@@ -35,7 +77,7 @@ const _: () = assert!(size_of::<ScriptOrModule>() == 16);
pub struct ExecutionContext {
pub function: Cell<Option<Gc<FunctionObject>>>,
pub realm: Cell<Option<Gc<Realm>>>,
- pub script_or_module: Cell<ScriptOrModule>,
+ pub script_or_module: ScriptOrModuleSlot,
pub lexical_environment: Cell<Option<Gc<Environment>>>,
pub variable_environment: Cell<Option<Gc<Environment>>>,
pub private_environment: Cell<Option<Gc<PrivateEnvironment>>>,
diff --git a/Libraries/LibJS/Rust/src/layout/function_object.rs b/Libraries/LibJS/Rust/src/layout/function_object.rs
index b40a78d141b..35f0b187300 100644
--- a/Libraries/LibJS/Rust/src/layout/function_object.rs
+++ b/Libraries/LibJS/Rust/src/layout/function_object.rs
@@ -6,10 +6,10 @@
use core::cell::Cell;
-use super::cell::CellHeader;
+use super::cell::{CellHeader, CellHeaderTail};
use super::environment::{DeclarativeEnvironment, Environment, PrivateEnvironment};
use super::executable::ExecutableHead;
-use super::execution_context::ScriptOrModule;
+use super::execution_context::ScriptOrModuleSlot;
use super::member::{Member, NullableMember};
use super::object::Object;
use super::realm::Realm;
@@ -115,33 +115,48 @@ pub mod ecmascript_function_flags {
pub const HAS_CUSTOM_NAME: u8 = 1 << 4;
}
-/// Bits of SharedFunctionInstanceData::asm_call_metadata above the formal parameter count in its low 32 bits.
+/// Bits of SharedFunctionInstanceData::asm_call_metadata above the formal parameter count in its low 32 bits. The first
+/// four are what the interpreter and JIT code decide calls by, and the rest is what else there is to know about the
+/// function in few bits.
pub mod asm_call_metadata {
pub const CAN_INLINE_CALL: u64 = 1 << 32;
pub const NEEDS_ENVIRONMENT_OR_THIS_VALUE_RESOLUTION: u64 = 1 << 33;
pub const USES_THIS: u64 = 1 << 34;
pub const STRICT: u64 = 1 << 35;
+ pub const FUNCTION_ENVIRONMENT_NEEDED: u64 = 1 << 36;
+ pub const THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION: u64 = 1 << 37;
+ pub const MIGHT_NEED_ARGUMENTS_OBJECT: u64 = 1 << 38;
+ pub const CONTAINS_DIRECT_CALL_TO_EVAL: u64 = 1 << 39;
+ pub const IS_ARROW_FUNCTION: u64 = 1 << 40;
+ pub const HAS_SIMPLE_PARAMETER_LIST: u64 = 1 << 41;
+ pub const IS_MODULE_WRAPPER: u64 = 1 << 42;
+ pub const IS_CLASS_CONSTRUCTOR: u64 = 1 << 43;
+ pub const IS_DERIVED_CONSTRUCTOR: u64 = 1 << 44;
+ pub const CLOSURE_COUNT_SHIFT: u32 = 45;
+ pub const CLOSURE_COUNT_MASK: u64 = 0b11;
+ pub const FUNCTION_KIND_SHIFT: u32 = 47;
+ pub const FUNCTION_KIND_MASK: u64 = 0b11;
+ pub const CONSTRUCT_COUNT_SHIFT: u32 = 49;
+ pub const CONSTRUCT_COUNT_MASK: u64 = (1 << 15) - 1;
}
#[repr(C)]
pub struct SharedFunctionInstanceData {
- pub header: CellHeader,
pub executable: NullableMember<ExecutableHead>,
- pub asm_call_metadata: Cell<u64>,
- pub formal_parameter_count: Cell<u32>,
- pub strict: Cell<bool>,
- pub function_environment_needed: Cell<bool>,
- pub uses_this: Cell<bool>,
- pub can_inline_call: Cell<bool>,
/// How JIT code allocates the function environments of calls of the functions, once the runtime made one.
pub call_environment_template: NullableMember<CallEnvironmentTemplate>,
+ pub header: CellHeaderTail,
+ /// How many properties the objects constructions of the function create get, as far as known.
+ pub construct_reserve: Cell<u8>,
+ pub function_length: i32,
+ pub asm_call_metadata: Cell<u64>,
/// The [[ScriptOrModule]] of the functions, which is the same for all of them.
- pub script_or_module: Cell<ScriptOrModule>,
+ pub script_or_module: ScriptOrModuleSlot,
pub storage: SharedFunctionInstanceDataStorage,
}
-/// The number of words of a FunctionEnvironment: a DeclarativeEnvironment and three more fields.
-pub const FUNCTION_ENVIRONMENT_WORDS: usize = size_of::<DeclarativeEnvironment>() / 8 + 3;
+/// The number of words of a FunctionEnvironment: a DeclarativeEnvironment and two more words of fields.
+pub const FUNCTION_ENVIRONMENT_WORDS: usize = size_of::<DeclarativeEnvironment>() / 8 + 2;
/// A function environment like the ones the calls of a function get, with its final shape and room for its binding
/// values in its cell, for JIT code to allocate from the local free list of its `size_class` (cells of `cell_size`
diff --git a/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs b/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
index 4aa58d3b672..876eb440ea2 100644
--- a/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
+++ b/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
@@ -24,7 +24,9 @@ use crate::interpreter::vm::Vm;
use crate::jit::dependencies::{CellId, Dependency};
use crate::layout::buffer::InterpreterBuffer;
use crate::layout::cell::Gc;
-pub use crate::layout::environment::{DeclarativeEnvironment, DeclarativeEnvironmentRareData};
+pub use crate::layout::environment::{
+ DeclarativeEnvironment, DeclarativeEnvironmentRareData, GlobalDeclarativeEnvironment,
+};
use crate::layout::value::Value;
use crate::runtime::abstract_operations::{DisposeCapability, add_disposable_resource};
use crate::runtime::completion::ThrowCompletionOr;
@@ -251,6 +253,40 @@ pub fn allocate_environment<T: GcCell>(
environment
}
+define_cell!(GlobalDeclarativeEnvironment, Other, extends: [DeclarativeEnvironment, Environment], finalize: finalize);
+
+impl Finalize for GlobalDeclarativeEnvironment {
+ fn finalize(&self) {
+ self.base.finalize();
+ }
+}
+
+// SAFETY: Visits what the declarative environment holds. The serial number is no cell.
+unsafe impl Trace for GlobalDeclarativeEnvironment {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.base.trace(visitor);
+ }
+}
+
+impl Deref for GlobalDeclarativeEnvironment {
+ type Target = DeclarativeEnvironment;
+
+ fn deref(&self) -> &DeclarativeEnvironment {
+ &self.base
+ }
+}
+
+impl GlobalDeclarativeEnvironment {
+ pub fn create(vm: &Vm) -> Gc<DeclarativeEnvironment> {
+ vm.heap()
+ .allocate(|_| Self {
+ base: DeclarativeEnvironment::new(Self::CLASS, None),
+ serial_number: Cell::new(0),
+ })
+ .upcast()
+ }
+}
+
/// The cell sizes of the size classes of declarative environments.
pub const DECLARATIVE_ENVIRONMENT_CELL_SIZES: [u32; INLINE_BINDING_CAPACITIES.len()] =
inline_binding_cell_sizes(size_of::<DeclarativeEnvironment>());
@@ -301,7 +337,6 @@ impl DeclarativeEnvironment {
base: Environment::new(class, outer_environment, true),
binding_values: InterpreterBuffer::new(),
rare_data: Cell::new(core::ptr::null_mut()),
- serial_number: Cell::new(0),
}
}
@@ -366,8 +401,11 @@ impl DeclarativeEnvironment {
{
return;
}
- let serial = self.serial_number.get();
- self.serial_number.set(serial + 1);
+ let Some(global_environment) = self.downcast_ref::<GlobalDeclarativeEnvironment>() else {
+ return;
+ };
+ let serial = global_environment.serial_number.get();
+ global_environment.serial_number.set(serial + 1);
if self.has_dependent_code() {
crate::jit::dependencies::invalidate_dependents(
vm,
@@ -454,7 +492,10 @@ impl DeclarativeEnvironment {
}
pub fn environment_serial_number(&self) -> u64 {
- self.serial_number.get()
+ self.downcast_ref::<GlobalDeclarativeEnvironment>()
+ .expect("only global declarative environments have a serial number")
+ .serial_number
+ .get()
}
pub fn dispose_capability(&self) -> &GcRefCell<DisposeCapability> {
diff --git a/Libraries/LibJS/Rust/src/runtime/environment.rs b/Libraries/LibJS/Rust/src/runtime/environment.rs
index 1e23b756fd8..0af98220c7c 100644
--- a/Libraries/LibJS/Rust/src/runtime/environment.rs
+++ b/Libraries/LibJS/Rust/src/runtime/environment.rs
@@ -22,7 +22,7 @@ use crate::gc::class::{Class, Extends, GcCell, class_of, define_cell};
use crate::gc::class_id::ClassId;
use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::vm::Vm;
-use crate::layout::cell::{CellHeader, Gc};
+use crate::layout::cell::{CellHeaderTail, Gc};
use crate::layout::environment::DeclarativeEnvironment;
pub use crate::layout::environment::Environment;
use crate::layout::member::NullableMember;
@@ -124,23 +124,23 @@ impl Environment {
/// The Environment part of a new environment of `class`.
pub fn new(class: &'static Class, outer_environment: Option<Gc<Environment>>, is_declarative: bool) -> Self {
Self {
- header: CellHeader::for_class(class),
+ outer: NullableMember::new(outer_environment),
+ shape: NullableMember::null(),
+ header: CellHeaderTail::for_class(class),
this_binding_status: (ThisBindingStatus::Uninitialized as u8).into(),
permanently_screwed_by_eval: false.into(),
declarative: is_declarative.into(),
binding_values_are_inline: false.into(),
- outer: NullableMember::new(outer_environment),
- shape: NullableMember::null(),
}
}
pub fn class(&self) -> &'static Class {
- self.header.class()
+ class_of(Gc::from_ref(self))
}
fn methods(&self) -> &'static EnvironmentMethods {
match self.class().id {
- ClassId::DeclarativeEnvironment => &DECLARATIVE_ENVIRONMENT_METHODS,
+ ClassId::DeclarativeEnvironment | ClassId::GlobalDeclarativeEnvironment => &DECLARATIVE_ENVIRONMENT_METHODS,
ClassId::FunctionEnvironment => &FUNCTION_ENVIRONMENT_METHODS,
ClassId::ModuleEnvironment => &MODULE_ENVIRONMENT_METHODS,
ClassId::GlobalEnvironment => &GLOBAL_ENVIRONMENT_METHODS,
diff --git a/Libraries/LibJS/Rust/src/runtime/function_environment.rs b/Libraries/LibJS/Rust/src/runtime/function_environment.rs
index 73ceed08c1c..c0abced68a4 100644
--- a/Libraries/LibJS/Rust/src/runtime/function_environment.rs
+++ b/Libraries/LibJS/Rust/src/runtime/function_environment.rs
@@ -13,6 +13,8 @@ use crate::gc::class::{Finalize, GcCell, define_cell};
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::function_object::{FUNCTION_ENVIRONMENT_WORDS, FunctionObject};
+use crate::layout::member::NullableMember;
+use crate::layout::object::Object;
use crate::layout::value::Value;
use crate::runtime::completion::ThrowCompletionOr;
use crate::runtime::declarative_environment::{
@@ -28,9 +30,10 @@ use crate::runtime::error_types::ErrorType;
#[derive(Trace)]
pub struct FunctionEnvironment {
base: DeclarativeEnvironment,
- this_value: Cell<Value>, // [[ThisValue]]
- function_object: Cell<Option<Gc<FunctionObject>>>, // [[FunctionObject]]
- new_target: Cell<Value>, // [[NewTarget]]
+ this_value: Cell<Value>, // [[ThisValue]]
+ function_object: NullableMember<FunctionObject>, // [[FunctionObject]]
+ /// [[NewTarget]], which is undefined if null.
+ new_target: NullableMember<Object>,
}
define_cell!(FunctionEnvironment, Other, extends: [DeclarativeEnvironment, Environment], finalize: finalize);
@@ -88,8 +91,8 @@ impl FunctionEnvironment {
FunctionEnvironment {
base: DeclarativeEnvironment::new(Self::CLASS, outer_environment),
this_value: Cell::new(Value::UNDEFINED),
- function_object: Cell::new(None),
- new_target: Cell::new(Value::UNDEFINED),
+ function_object: NullableMember::null(),
+ new_target: NullableMember::null(),
},
binding_capacity,
&FUNCTION_ENVIRONMENT_CELL_SIZES,
@@ -116,12 +119,13 @@ impl FunctionEnvironment {
}
pub fn new_target(&self) -> Value {
- self.new_target.get()
+ self.new_target.get().map_or(Value::UNDEFINED, Value::from_object)
}
pub fn set_new_target(&self, new_target: Value) {
assert!(!new_target.is_empty());
- self.new_target.set(new_target);
+ self.new_target
+ .set(new_target.is_object().then(|| new_target.as_object()));
}
// 9.1.1.3.5 GetSuperBase ( ), https://tc39.es/ecma262/#sec-getsuperbase
diff --git a/Libraries/LibJS/Rust/src/runtime/global_environment.rs b/Libraries/LibJS/Rust/src/runtime/global_environment.rs
index a3ccd94d08f..533ad7bc6b7 100644
--- a/Libraries/LibJS/Rust/src/runtime/global_environment.rs
+++ b/Libraries/LibJS/Rust/src/runtime/global_environment.rs
@@ -17,7 +17,7 @@ pub use crate::layout::environment::GlobalEnvironment;
use crate::layout::object::Object;
use crate::layout::value::Value;
use crate::runtime::completion::{Must, ThrowCompletionOr};
-use crate::runtime::declarative_environment::DeclarativeEnvironment;
+use crate::runtime::declarative_environment::{DeclarativeEnvironment, GlobalDeclarativeEnvironment};
use crate::runtime::environment::{ENVIRONMENT_METHODS, Environment, EnvironmentMethods, InitializeBindingHint};
use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
@@ -81,7 +81,7 @@ impl GlobalEnvironment {
// 9.1.2.5 NewGlobalEnvironment ( G, thisValue ), https://tc39.es/ecma262/#sec-newglobalenvironment
pub fn create(vm: &Vm, global_object: Gc<Object>, this_value: Gc<Object>) -> Gc<GlobalEnvironment> {
let object_record = ObjectEnvironment::create(vm, global_object, IsWithEnvironment::No, None);
- let declarative_record = DeclarativeEnvironment::create(vm, None);
+ let declarative_record = GlobalDeclarativeEnvironment::create(vm);
declarative_record.track_binding_assignments();
vm.heap().allocate(|_| GlobalEnvironment {
base: Environment::new(Self::CLASS, None, false),
diff --git a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
index 7301f297436..14479061bbd 100644
--- a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use core::cell::{Cell, RefCell};
+use core::cell::{Cell, OnceCell, RefCell};
use std::collections::HashSet;
use std::rc::Rc;
@@ -20,13 +20,14 @@ use crate::bytecode_cache::{DecodedCachedExecutableRecord, DecodedFunctionRecord
use crate::compile::FunctionPrecompileMode;
use crate::compile::SharedFunctionDescription;
use crate::gc::class::{GcCell, define_cell};
+use crate::gc::defer_gc::DeferGc;
use crate::gc::gc_ref_cell::GcRefCell;
use crate::gc::root::MarkedVec;
use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::run::should_dump_bytecode;
use crate::interpreter::vm::Vm;
-use crate::layout::cell::{CellHeader, Gc};
-use crate::layout::execution_context::ScriptOrModule;
+use crate::layout::cell::{CellHeaderTail, Gc};
+use crate::layout::execution_context::{ScriptOrModule, ScriptOrModuleSlot};
use crate::layout::function_object::CallEnvironmentTemplate;
pub use crate::layout::function_object::{SharedFunctionInstanceData, asm_call_metadata};
use crate::layout::member::NullableMember;
@@ -44,6 +45,7 @@ pub enum ThisMode {
/// How many closures of a function were created.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
pub enum ClosureCount {
None,
One,
@@ -66,85 +68,132 @@ pub enum ClassFieldInitializerName {
Empty,
}
-/// The parts of the shared data of a function that the interpreter does not read.
-#[derive(Trace)]
-pub struct SharedFunctionInstanceDataStorage {
- name: Utf16FlyString,
+/// What a function's executable is made from when it is first called, which only one thing can be at a time.
+enum CompileInput {
+ None,
+ /// The function's AST, which its bytecode is compiled from.
+ FunctionAst(Box<FunctionPayload>),
+ /// Freshly compiled bytecode.
+ PrecompiledBytecode(Box<PrecompiledFunction>),
+ /// The function's executable in a bytecode cache blob.
+ CachedBytecode(Box<DecodedCachedExecutableRecord>),
+}
- // NB: source_text_offset and source_text_length normally refer to
- // ranges within the underlying SourceCode we parsed the AST from,
- // kept alive by source_code. source_text_owner is used if the
- // source text needs to be owned by the function data (e.g. for
- // dynamically created functions via Function constructor).
- #[gc(untraced)]
- source_code: RefCell<Option<Rc<SourceCode>>>,
- #[gc(untraced)]
- source_text_owner: RefCell<Utf16String>,
- source_text_offset: Cell<usize>,
- source_text_length: Cell<usize>, // [[SourceText]]
+/// A CompileInput in one word: the pointer, with what it points at in its lowest bits.
+struct CompileInputSlot(Cell<*mut ()>);
+
+// NB: The pointers in a slot leave room for its tag.
+const _: () = assert!(
+ align_of::<FunctionPayload>() > CompileInputSlot::TAG_MASK
+ && align_of::<PrecompiledFunction>() > CompileInputSlot::TAG_MASK
+ && align_of::<DecodedCachedExecutableRecord>() > CompileInputSlot::TAG_MASK
+);
+
+impl CompileInputSlot {
+ const TAG_MASK: usize = 0b11;
+ const TAG_FUNCTION_AST: usize = 1;
+ const TAG_PRECOMPILED_BYTECODE: usize = 2;
+ const TAG_CACHED_BYTECODE: usize = 3;
+
+ fn new(input: CompileInput) -> Self {
+ let slot = Self(Cell::new(core::ptr::null_mut()));
+ slot.set(input);
+ slot
+ }
+
+ fn set(&self, input: CompileInput) {
+ drop(self.take());
+ self.0.set(match input {
+ CompileInput::None => core::ptr::null_mut(),
+ CompileInput::FunctionAst(ast) => Self::tagged(Box::into_raw(ast), Self::TAG_FUNCTION_AST),
+ CompileInput::PrecompiledBytecode(precompiled) => {
+ Self::tagged(Box::into_raw(precompiled), Self::TAG_PRECOMPILED_BYTECODE)
+ }
+ CompileInput::CachedBytecode(cached) => Self::tagged(Box::into_raw(cached), Self::TAG_CACHED_BYTECODE),
+ });
+ }
+
+ fn tagged<T>(pointer: *mut T, tag: usize) -> *mut () {
+ pointer.cast::<()>().map_addr(|address| address | tag)
+ }
+
+ fn take(&self) -> CompileInput {
+ let word = self.0.replace(core::ptr::null_mut());
+ let pointer = word.map_addr(|address| address & !Self::TAG_MASK);
+ // SAFETY: set() made the word from a box of the type its tag says, which nothing else owns now that the word
+ // is gone from the slot.
+ unsafe {
+ match word.addr() & Self::TAG_MASK {
+ Self::TAG_FUNCTION_AST => CompileInput::FunctionAst(Box::from_raw(pointer.cast())),
+ Self::TAG_PRECOMPILED_BYTECODE => CompileInput::PrecompiledBytecode(Box::from_raw(pointer.cast())),
+ Self::TAG_CACHED_BYTECODE => CompileInput::CachedBytecode(Box::from_raw(pointer.cast())),
+ _ => CompileInput::None,
+ }
+ }
+ }
- function_length: i32,
+ fn tag(&self) -> usize {
+ self.0.get().addr() & Self::TAG_MASK
+ }
+}
+
+impl Drop for CompileInputSlot {
+ fn drop(&mut self) {
+ drop(self.take());
+ }
+}
+
+/// The names of the parameters of a function with a simple parameter list that has any.
+struct ParameterNames {
/// The name each argument index of a mapped arguments object maps to, which is empty where a later parameter has
/// the same name.
- #[gc(untraced)]
mapped_argument_names: Rc<[Utf16FlyString]>,
/// The names of the parameters without the ones that repeat, in the order the bindings of the parameters are
/// created in the function environment.
- #[gc(untraced)]
parameter_binding_names: Rc<[Utf16FlyString]>,
+}
+/// The parts of the shared data of a function that few functions need.
+#[derive(Default, Trace)]
+struct SharedFunctionInstanceDataRareData {
+ /// Owns the source text if it is not simply a range of the source code the function was parsed from, as for
+ /// dynamically created functions via the Function constructor, or once something asked for it.
#[gc(untraced)]
- this_mode: ThisMode, // [[ThisMode]]
+ source_text_owner: RefCell<Utf16String>,
+ class_field_initializer_name: GcRefCell<ClassFieldInitializerName>, // [[ClassFieldInitializerName]]
+ /// The source text range the function was created with, which a bytecode cache blob identifies the function by,
+ /// once the source text range of the function no longer is that, as when a class constructor's grows to the whole
+ /// class.
#[gc(untraced)]
- kind: FunctionKind,
-
- might_need_arguments_object: Cell<bool>,
- contains_direct_call_to_eval: Cell<bool>,
- is_arrow_function: bool,
- has_simple_parameter_list: bool,
- is_module_wrapper: Cell<bool>,
-
- this_value_needs_environment_resolution: Cell<bool>,
-
- function_environment_bindings_count: Cell<usize>,
- var_environment_bindings_count: Cell<usize>,
- function_environment_shape: NullableMember<EnvironmentShape>,
+ bytecode_cache_source_text_range: Cell<Option<(u32, u32)>>,
+ /// Functions with parameter expressions may have a separate var environment.
+ var_environment_bindings_count: Cell<u32>,
var_environment_shape: NullableMember<EnvironmentShape>,
+}
- class_field_initializer_name: GcRefCell<ClassFieldInitializerName>, // [[ClassFieldInitializerName]]
- #[gc(untraced)]
- constructor_kind: Cell<ConstructorKind>, // [[ConstructorKind]]
- is_class_constructor: Cell<bool>, // [[IsClassConstructor]]
+/// The parts of the shared data of a function that the interpreter does not read.
+#[derive(Trace)]
+pub struct SharedFunctionInstanceDataStorage {
+ name: Utf16FlyString,
- // NB: When present, the function's AST, which its bytecode is compiled from when it is first called.
- #[gc(untraced)]
- rust_function_ast: RefCell<Option<Box<FunctionPayload>>>,
- // NB: When present, freshly compiled bytecode that becomes the function's executable when it is first called.
+ // NB: source_text_offset and source_text_length are a range of the source code we parsed the AST from.
#[gc(untraced)]
- precompiled_bytecode_executable: RefCell<Option<Box<PrecompiledFunction>>>,
- // NB: When present, the function's executable in a bytecode cache blob, which becomes its executable when it is
- // first called.
+ source_code: Cell<Option<Rc<SourceCode>>>,
+ source_text_offset: Cell<u32>,
+ source_text_length: Cell<u32>, // [[SourceText]]
+
#[gc(untraced)]
- cached_bytecode_executable: RefCell<Option<Box<DecodedCachedExecutableRecord>>>,
- // NB: The source text range the function was created with, which a bytecode cache blob identifies the function
- // by, even after the range of a class constructor grew to the whole class.
- bytecode_cache_source_text_offset: Cell<usize>,
- bytecode_cache_source_text_length: Cell<usize>,
- use_rust_compilation: bool,
-
- /// How many properties the objects constructions of the function create get, as far as known (see
- /// construct_reserve()), and how many constructions asked.
- construct_reserve: Cell<u32>,
- construct_count: Cell<u32>,
-
- /// How many closures of the function were created. JIT code may only treat the bindings of a closure's
- /// environment as the bindings of every frame running the function while it is the only closure.
+ parameter_names: Option<Box<ParameterNames>>,
#[gc(untraced)]
- closure_count: Cell<ClosureCount>,
+ compile_input: CompileInputSlot,
+ rare_data: OnceCell<Box<SharedFunctionInstanceDataRareData>>,
+
+ function_environment_bindings_count: Cell<u32>,
+ function_environment_shape: NullableMember<EnvironmentShape>,
}
// NB: Every function has these bytes.
-const _: () = assert!(size_of::<SharedFunctionInstanceData>() == 280);
+const _: () = assert!(size_of::<SharedFunctionInstanceData>() == 88);
/// The most properties that constructions make room for ahead (the largest inline capacity of plain objects).
const MAX_CONSTRUCT_RESERVE: u32 = 16;
@@ -152,6 +201,9 @@ const MAX_CONSTRUCT_RESERVE: u32 = 16;
/// The last construction that follows the transitions again (see SharedFunctionInstanceData::construct_reserve()).
const MAX_CONSTRUCT_RESERVE_UPDATES: u32 = 1024;
+const _: () = assert!(MAX_CONSTRUCT_RESERVE <= u8::MAX as u32);
+const _: () = assert!(MAX_CONSTRUCT_RESERVE_UPDATES as u64 <= asm_call_metadata::CONSTRUCT_COUNT_MASK);
+
define_cell!(SharedFunctionInstanceData, Other);
// SAFETY: Visits the executable, the call environment template and every cell the storage holds.
@@ -176,38 +228,56 @@ unsafe impl Trace for CallEnvironmentTemplate {
fn trace(&self, _visitor: &mut Visitor) {}
}
-fn parameter_binding_names(parameter_names: &[Utf16FlyString]) -> Rc<[Utf16FlyString]> {
- let mut seen_names = HashSet::with_capacity(parameter_names.len());
- let mut names: Vec<Utf16FlyString> = Vec::with_capacity(parameter_names.len());
- for name in parameter_names {
- if seen_names.insert(name) {
- names.push(name.clone());
- }
- }
- names.into()
-}
-
/// OPTIMIZATION: Precompute the argument indices that alias parameter bindings. Only the last occurrence of each
/// parameter name is eligible; each arguments object also limits the mapping to its argument count.
/// https://tc39.es/ecma262/#sec-createmappedargumentsobject
-fn mapped_argument_names(parameter_names: Vec<Utf16FlyString>) -> Rc<[Utf16FlyString]> {
+fn parameter_names_of(parameter_names: Vec<Utf16FlyString>) -> Option<Box<ParameterNames>> {
+ if parameter_names.is_empty() {
+ return None;
+ }
let mut seen_names = HashSet::with_capacity(parameter_names.len());
let mut mapped_names: Vec<Utf16FlyString> = vec![Utf16FlyString::default(); parameter_names.len()];
+ let mut has_repeated_name = false;
for index in (0..parameter_names.len()).rev() {
let name = &parameter_names[index];
// OPTIMIZATION: A hash set avoids scanning later parameters for every name.
if !seen_names.insert(name) {
+ has_repeated_name = true;
continue;
}
mapped_names[index] = name.clone();
}
- mapped_names.into()
+ let mapped_argument_names: Rc<[Utf16FlyString]> = mapped_names.into();
+
+ // NB: Without repeated names, both lists are the parameter names.
+ let parameter_binding_names = if has_repeated_name {
+ let mut seen_names = HashSet::with_capacity(parameter_names.len());
+ let mut names: Vec<Utf16FlyString> = Vec::with_capacity(parameter_names.len());
+ for name in &parameter_names {
+ if seen_names.insert(name) {
+ names.push(name.clone());
+ }
+ }
+ names.into()
+ } else {
+ mapped_argument_names.clone()
+ };
+
+ Some(Box::new(ParameterNames {
+ mapped_argument_names,
+ parameter_binding_names,
+ }))
+}
+
+fn source_text_offset_or_length(offset_or_length: usize) -> u32 {
+ u32::try_from(offset_or_length).expect("a source code fits u32 code units")
}
impl SharedFunctionInstanceData {
#[allow(clippy::too_many_arguments)]
fn new(
+ _: &DeferGc<'_>,
kind: FunctionKind,
name: Utf16FlyString,
function_length: i32,
@@ -216,65 +286,71 @@ impl SharedFunctionInstanceData {
is_arrow_function: bool,
has_simple_parameter_list: bool,
parameter_names_for_mapped_arguments: Vec<Utf16FlyString>,
- rust_function_ast: Option<Box<FunctionPayload>>,
+ function_ast: Option<Box<FunctionPayload>>,
) -> Self {
// NB: initialize_after_construction()
- let this_mode = if is_arrow_function {
- ThisMode::Lexical
- } else if strict {
- ThisMode::Strict
- } else {
- ThisMode::Global
- };
+ let mut metadata = u64::from(formal_parameter_count)
+ | asm_call_metadata::MIGHT_NEED_ARGUMENTS_OBJECT
+ | asm_call_metadata::CONTAINS_DIRECT_CALL_TO_EVAL
+ | (kind as u64) << asm_call_metadata::FUNCTION_KIND_SHIFT;
+ if strict {
+ metadata |= asm_call_metadata::STRICT;
+ }
+ if is_arrow_function {
+ metadata |= asm_call_metadata::IS_ARROW_FUNCTION;
+ }
+ if has_simple_parameter_list {
+ metadata |= asm_call_metadata::HAS_SIMPLE_PARAMETER_LIST;
+ }
Self {
- header: CellHeader::for_class(Self::CLASS),
executable: NullableMember::null(),
- asm_call_metadata: Cell::new(0),
- formal_parameter_count: Cell::new(formal_parameter_count),
- strict: Cell::new(strict),
- function_environment_needed: Cell::new(false),
- uses_this: Cell::new(false),
- can_inline_call: Cell::new(false),
call_environment_template: NullableMember::null(),
- script_or_module: Cell::new(ScriptOrModule::Empty),
+ header: CellHeaderTail::for_class(Self::CLASS),
+ construct_reserve: Cell::new(0),
+ function_length,
+ asm_call_metadata: Cell::new(metadata),
+ script_or_module: ScriptOrModuleSlot::new(ScriptOrModule::Empty),
storage: SharedFunctionInstanceDataStorage {
name,
- source_code: RefCell::new(None),
- source_text_owner: RefCell::new(Utf16String::default()),
+ source_code: Cell::new(None),
source_text_offset: Cell::new(0),
source_text_length: Cell::new(0),
- function_length,
- parameter_binding_names: parameter_binding_names(&parameter_names_for_mapped_arguments),
- mapped_argument_names: mapped_argument_names(parameter_names_for_mapped_arguments),
- this_mode,
- kind,
- might_need_arguments_object: Cell::new(true),
- contains_direct_call_to_eval: Cell::new(true),
- is_arrow_function,
- has_simple_parameter_list,
- is_module_wrapper: Cell::new(false),
- this_value_needs_environment_resolution: Cell::new(false),
+ parameter_names: parameter_names_of(parameter_names_for_mapped_arguments),
+ compile_input: CompileInputSlot::new(
+ function_ast.map_or(CompileInput::None, CompileInput::FunctionAst),
+ ),
+ rare_data: OnceCell::new(),
function_environment_bindings_count: Cell::new(0),
- var_environment_bindings_count: Cell::new(0),
function_environment_shape: NullableMember::null(),
- var_environment_shape: NullableMember::null(),
- class_field_initializer_name: GcRefCell::new(ClassFieldInitializerName::Empty),
- constructor_kind: Cell::new(ConstructorKind::Base),
- is_class_constructor: Cell::new(false),
- rust_function_ast: RefCell::new(rust_function_ast),
- precompiled_bytecode_executable: RefCell::new(None),
- cached_bytecode_executable: RefCell::new(None),
- bytecode_cache_source_text_offset: Cell::new(0),
- bytecode_cache_source_text_length: Cell::new(0),
- use_rust_compilation: true,
- construct_reserve: Cell::new(0),
- construct_count: Cell::new(0),
- closure_count: Cell::new(ClosureCount::None),
},
}
}
+ fn rare_data(&self) -> &SharedFunctionInstanceDataRareData {
+ self.storage.rare_data.get_or_init(Box::default)
+ }
+
+ fn metadata_bit(&self, bit: u64) -> bool {
+ self.asm_call_metadata.get() & bit != 0
+ }
+
+ fn set_metadata_bit(&self, bit: u64, value: bool) {
+ let mut metadata = self.asm_call_metadata.get() & !bit;
+ if value {
+ metadata |= bit;
+ }
+ metadata &= !asm_call_metadata::NEEDS_ENVIRONMENT_OR_THIS_VALUE_RESOLUTION;
+ if metadata
+ & (asm_call_metadata::FUNCTION_ENVIRONMENT_NEEDED
+ | asm_call_metadata::THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION)
+ != 0
+ {
+ metadata |= asm_call_metadata::NEEDS_ENVIRONMENT_OR_THIS_VALUE_RESOLUTION;
+ }
+ self.asm_call_metadata.set(metadata);
+ }
+
/// Creates the shared data of a function the frontend described.
pub fn create(
vm: &Vm,
@@ -293,8 +369,9 @@ impl SharedFunctionInstanceData {
Vec::new()
};
- let shared = vm.heap().allocate(|_| {
+ let shared = vm.heap().allocate(|defer| {
Self::new(
+ defer,
description.function_kind,
name,
description.function_length,
@@ -309,24 +386,17 @@ impl SharedFunctionInstanceData {
shared.update_can_inline_call();
// Set parsing insights that must be available before lazy compilation.
- shared.uses_this.set(description.uses_this);
- shared
- .storage
- .this_value_needs_environment_resolution
- .set(description.uses_this_from_environment);
+ shared.set_uses_this(description.uses_this);
+ shared.set_metadata_bit(
+ asm_call_metadata::THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION,
+ description.uses_this_from_environment,
+ );
if description.uses_this_from_environment && !description.is_arrow {
- shared.function_environment_needed.set(true);
+ shared.set_function_environment_needed(true);
}
- shared.update_asm_call_metadata();
-
- if let Some(source_code) = source_code {
- shared.set_source_text_range(
- source_code,
- description.source_text_offset,
- description.source_text_length,
- );
- }
- shared.set_bytecode_cache_source_text_range(description.source_text_offset, description.source_text_length);
+
+ shared.storage.source_code.set(source_code.cloned());
+ shared.initialize_source_text_range(description.source_text_offset, description.source_text_length);
shared
}
@@ -347,8 +417,9 @@ impl SharedFunctionInstanceData {
let source_text_length = source_text_range.end.saturating_sub(source_text_range.start);
let is_arrow_function = function.is_arrow();
- let shared = vm.heap().allocate(|_| {
+ let shared = vm.heap().allocate(|defer| {
Self::new(
+ defer,
function.function_kind(),
name,
function.length(),
@@ -364,40 +435,61 @@ impl SharedFunctionInstanceData {
// Set parsing insights that must be available before lazy compilation.
let (uses_this, uses_this_from_environment) = function.parsing_insights_about_this();
- shared.uses_this.set(uses_this);
- shared
- .storage
- .this_value_needs_environment_resolution
- .set(uses_this_from_environment);
+ shared.set_uses_this(uses_this);
+ shared.set_metadata_bit(
+ asm_call_metadata::THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION,
+ uses_this_from_environment,
+ );
if uses_this_from_environment && !is_arrow_function {
- shared.function_environment_needed.set(true);
+ shared.set_function_environment_needed(true);
}
- shared.update_asm_call_metadata();
- shared.set_source_text_range(source_code, source_text_range.start, source_text_length);
- shared.set_bytecode_cache_source_text_range(source_text_range.start, source_text_length);
+ shared.storage.source_code.set(Some(source_code.clone()));
+ shared.initialize_source_text_range(source_text_range.start, source_text_length);
if let Some((name, is_private)) = function.field_initializer_name() {
shared.set_class_field_initializer_name_from_utf16(&name, is_private);
}
shared.set_metadata(function.scope_metadata());
shared
.storage
- .cached_bytecode_executable
- .replace(Some(Box::new(function.cached_executable())));
+ .compile_input
+ .set(CompileInput::CachedBytecode(Box::new(function.cached_executable())));
shared
}
- fn set_bytecode_cache_source_text_range(&self, source_text_offset: usize, source_text_length: usize) {
- self.storage.bytecode_cache_source_text_offset.set(source_text_offset);
- self.storage.bytecode_cache_source_text_length.set(source_text_length);
+ fn initialize_source_text_range(&self, source_text_offset: usize, source_text_length: usize) {
+ self.storage
+ .source_text_offset
+ .set(source_text_offset_or_length(source_text_offset));
+ self.storage
+ .source_text_length
+ .set(source_text_offset_or_length(source_text_length));
}
/// The offset and length of the source text the function was created with.
pub fn bytecode_cache_source_text_range(&self) -> (usize, usize) {
- (
- self.storage.bytecode_cache_source_text_offset.get(),
- self.storage.bytecode_cache_source_text_length.get(),
- )
+ let (offset, length) = self
+ .storage
+ .rare_data
+ .get()
+ .and_then(|rare_data| rare_data.bytecode_cache_source_text_range.get())
+ .unwrap_or((
+ self.storage.source_text_offset.get(),
+ self.storage.source_text_length.get(),
+ ));
+ (offset as usize, length as usize)
+ }
+
+ /// Keeps the range a bytecode cache blob identifies the function by, as the source text range is about to change.
+ fn preserve_bytecode_cache_source_text_range(&self) {
+ let range = (
+ self.storage.source_text_offset.get(),
+ self.storage.source_text_length.get(),
+ );
+ let slot = &self.rare_data().bytecode_cache_source_text_range;
+ if slot.get().is_none() {
+ slot.set(Some(range));
+ }
}
/// Whether `function`, a function of a bytecode cache blob nested in code that is strict if `outer_strict` is, is
@@ -409,12 +501,12 @@ impl SharedFunctionInstanceData {
source_text_range.start,
source_text_range.end.saturating_sub(source_text_range.start),
)
- && self.storage.function_length == function.length()
- && self.formal_parameter_count.get() == function.parameter_count()
- && self.storage.kind == function.function_kind()
- && self.strict.get() == (function.has_strict_code() || outer_strict)
- && self.storage.is_arrow_function == function.is_arrow()
- && self.storage.has_simple_parameter_list == function.simple_parameter_names().is_some()
+ && self.function_length == function.length()
+ && self.formal_parameter_count() == function.parameter_count()
+ && self.kind() == function.function_kind()
+ && self.strict() == (function.has_strict_code() || outer_strict)
+ && self.is_arrow_function() == function.is_arrow()
+ && self.has_simple_parameter_list() == function.simple_parameter_names().is_some()
}
/// Replaces how the function compiles with its executable in a bytecode cache blob, which becomes its executable
@@ -424,11 +516,10 @@ impl SharedFunctionInstanceData {
cached_executable: DecodedCachedExecutableRecord,
metadata: &FunctionSfdMetadata,
) {
- self.clear_compile_inputs();
self.set_metadata(metadata);
self.storage
- .cached_bytecode_executable
- .replace(Some(Box::new(cached_executable)));
+ .compile_input
+ .set(CompileInput::CachedBytecode(Box::new(cached_executable)));
}
/// Replaces the executable of a function that already ran with one materialized from a bytecode cache blob, which
@@ -459,8 +550,9 @@ impl SharedFunctionInstanceData {
has_simple_parameter_list: bool,
parameter_names_for_mapped_arguments: Vec<Utf16FlyString>,
) -> Gc<SharedFunctionInstanceData> {
- let shared = vm.heap().allocate(|_| {
+ let shared = vm.heap().allocate(|defer| {
Self::new(
+ defer,
kind,
name,
function_length,
@@ -504,72 +596,56 @@ impl SharedFunctionInstanceData {
}
pub fn set_is_class_constructor(&self) {
- self.storage.is_class_constructor.set(true);
+ self.set_metadata_bit(asm_call_metadata::IS_CLASS_CONSTRUCTOR, true);
self.update_can_inline_call();
}
- pub fn update_asm_call_metadata(&self) {
- let mut metadata = u64::from(self.formal_parameter_count.get());
- if self.can_inline_call.get() {
- metadata |= asm_call_metadata::CAN_INLINE_CALL;
- }
- if self.function_environment_needed.get() || self.storage.this_value_needs_environment_resolution.get() {
- metadata |= asm_call_metadata::NEEDS_ENVIRONMENT_OR_THIS_VALUE_RESOLUTION;
- }
- if self.uses_this.get() {
- metadata |= asm_call_metadata::USES_THIS;
- }
- if self.strict.get() {
- metadata |= asm_call_metadata::STRICT;
- }
- self.asm_call_metadata.set(metadata);
- }
-
pub fn can_inline_call(&self) -> bool {
- self.can_inline_call.get()
+ self.metadata_bit(asm_call_metadata::CAN_INLINE_CALL)
}
fn update_can_inline_call(&self) {
- self.can_inline_call.set(
- self.executable.get().is_some()
- && self.storage.kind == FunctionKind::Normal
- && !self.storage.is_class_constructor.get(),
+ self.set_metadata_bit(
+ asm_call_metadata::CAN_INLINE_CALL,
+ self.executable.get().is_some() && self.kind() == FunctionKind::Normal && !self.is_class_constructor(),
);
- self.update_asm_call_metadata();
}
pub fn name(&self) -> Utf16FlyString {
self.storage.name.clone()
}
+ pub fn source_text_owner(&self) -> Option<Utf16String> {
+ let source_text_owner = self.storage.rare_data.get()?.source_text_owner.borrow();
+ (!source_text_owner.is_empty()).then(|| source_text_owner.clone())
+ }
+
pub fn source_text(&self) -> Utf16String {
- {
- let source_text_owner = self.storage.source_text_owner.borrow();
- if !source_text_owner.is_empty() {
- return source_text_owner.clone();
- }
+ if let Some(source_text_owner) = self.source_text_owner() {
+ return source_text_owner;
}
- let Some(source_code) = self.storage.source_code.borrow().clone() else {
+ let Some(source_code) = self.source_code() else {
return Utf16String::default();
};
let source_text = source_code.source_text_from_offsets(
- self.storage.source_text_offset.get(),
- self.storage.source_text_length.get(),
+ self.storage.source_text_offset.get() as usize,
+ self.storage.source_text_length.get() as usize,
);
- self.storage.source_text_owner.replace(source_text.clone());
+ self.rare_data().source_text_owner.replace(source_text.clone());
source_text
}
/// Makes `source_text` the [[SourceText]] while keeping the source code the function compiles from.
pub fn set_source_text_owner(&self, source_text: Utf16String) {
- self.storage.source_text_owner.replace(source_text);
+ self.rare_data().source_text_owner.replace(source_text);
}
pub fn set_source_text(&self, source_text: Utf16String) {
- self.storage.source_text_owner.replace(source_text);
- self.storage.source_code.replace(None);
+ self.preserve_bytecode_cache_source_text_range();
+ self.rare_data().source_text_owner.replace(source_text);
+ self.storage.source_code.set(None);
self.storage.source_text_offset.set(0);
self.storage.source_text_length.set(0);
}
@@ -580,39 +656,41 @@ impl SharedFunctionInstanceData {
source_text_offset: usize,
source_text_length: usize,
) {
- self.storage.source_text_owner.replace(Utf16String::default());
- self.storage.source_code.replace(Some(source_code.clone()));
- self.storage.source_text_offset.set(source_text_offset);
- self.storage.source_text_length.set(source_text_length);
+ self.preserve_bytecode_cache_source_text_range();
+ self.rare_data().source_text_owner.replace(Utf16String::default());
+ self.storage.source_code.set(Some(source_code.clone()));
+ self.initialize_source_text_range(source_text_offset, source_text_length);
}
pub fn source_code(&self) -> Option<Rc<SourceCode>> {
- self.storage.source_code.borrow().clone()
+ let source_code = self.storage.source_code.take();
+ self.storage.source_code.set(source_code.clone());
+ source_code
}
pub fn clear_compile_inputs(&self) {
- self.clear_non_bytecode_cache_compile_inputs();
- drop(self.storage.cached_bytecode_executable.take());
+ self.storage.compile_input.set(CompileInput::None);
}
pub fn clear_non_bytecode_cache_compile_inputs(&self) {
- drop(self.storage.rust_function_ast.take());
- drop(self.storage.precompiled_bytecode_executable.take());
+ if self.storage.compile_input.tag() != CompileInputSlot::TAG_CACHED_BYTECODE {
+ self.clear_compile_inputs();
+ }
}
/// Whether the function still has the AST it compiles from when it is first called.
pub fn has_function_ast(&self) -> bool {
- self.storage.rust_function_ast.borrow().is_some()
+ self.storage.compile_input.tag() == CompileInputSlot::TAG_FUNCTION_AST
}
/// Whether the function still has bytecode compiled ahead of its first call, apart from that of a bytecode cache.
pub fn has_precompiled_bytecode(&self) -> bool {
- self.storage.precompiled_bytecode_executable.borrow().is_some()
+ self.storage.compile_input.tag() == CompileInputSlot::TAG_PRECOMPILED_BYTECODE
}
/// Whether the function's executable is still in a bytecode cache blob, waiting for its first call.
pub fn has_cached_bytecode(&self) -> bool {
- self.storage.cached_bytecode_executable.borrow().is_some()
+ self.storage.compile_input.tag() == CompileInputSlot::TAG_CACHED_BYTECODE
}
/// Appends the functions that `executable` creates and that have not been compiled yet to `functions`, and returns
@@ -628,42 +706,52 @@ impl SharedFunctionInstanceData {
if shared_data.executable().is_some() {
continue;
}
- let Some(function_ast) = shared_data.storage.rust_function_ast.borrow().clone() else {
+ if !shared_data.has_function_ast() {
continue;
+ }
+ let CompileInput::FunctionAst(function_ast) = shared_data.storage.compile_input.take() else {
+ unreachable!("the function has its AST");
};
functions.push(shared_data);
- function_asts.push(function_ast);
+ function_asts.push(function_ast.clone());
+ shared_data
+ .storage
+ .compile_input
+ .set(CompileInput::FunctionAst(function_ast));
}
function_asts
}
/// Records what scope analysis found out about the function's body, as rust_sfd_set_metadata does.
pub fn set_metadata(&self, metadata: &FunctionSfdMetadata) {
- self.uses_this.set(metadata.uses_this);
- self.storage
- .this_value_needs_environment_resolution
- .set(metadata.this_value_needs_environment_resolution);
- self.function_environment_needed
- .set(metadata.function_environment_needed);
- self.update_asm_call_metadata();
+ self.set_uses_this(metadata.uses_this);
+ self.set_metadata_bit(
+ asm_call_metadata::THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION,
+ metadata.this_value_needs_environment_resolution,
+ );
+ self.set_function_environment_needed(metadata.function_environment_needed);
self.storage
.function_environment_bindings_count
- .set(metadata.function_environment_bindings_count);
- self.storage
- .var_environment_bindings_count
- .set(metadata.var_environment_bindings_count);
- self.storage
- .might_need_arguments_object
- .set(metadata.might_need_arguments);
- self.storage.contains_direct_call_to_eval.set(metadata.contains_eval);
+ .set(u32::try_from(metadata.function_environment_bindings_count).expect("the count fits in u32"));
+ if metadata.var_environment_bindings_count != 0 || self.storage.rare_data.get().is_some() {
+ self.rare_data()
+ .var_environment_bindings_count
+ .set(u32::try_from(metadata.var_environment_bindings_count).expect("the count fits in u32"));
+ }
+ self.set_metadata_bit(
+ asm_call_metadata::MIGHT_NEED_ARGUMENTS_OBJECT,
+ metadata.might_need_arguments,
+ );
+ self.set_metadata_bit(asm_call_metadata::CONTAINS_DIRECT_CALL_TO_EVAL, metadata.contains_eval);
}
/// Keeps bytecode the frontend compiled ahead of the first call, as rust_sfd_set_precompiled_bytecode_executable
/// does.
pub fn set_precompiled_bytecode_executable(&self, precompiled: Box<PrecompiledFunction>) {
- self.clear_compile_inputs();
self.set_metadata(&precompiled.metadata);
- self.storage.precompiled_bytecode_executable.replace(Some(precompiled));
+ self.storage
+ .compile_input
+ .set(CompileInput::PrecompiledBytecode(precompiled));
}
/// Sets [[ClassFieldInitializerName]] to a name the frontend found, as rust_sfd_set_class_field_initializer_name
@@ -678,75 +766,110 @@ impl SharedFunctionInstanceData {
}
pub fn class_field_initializer_name(&self) -> ClassFieldInitializerName {
- self.storage.class_field_initializer_name.borrow().clone()
+ self.storage
+ .rare_data
+ .get()
+ .map_or(ClassFieldInitializerName::Empty, |rare_data| {
+ rare_data.class_field_initializer_name.borrow().clone()
+ })
}
pub fn set_class_field_initializer_name(&self, name: ClassFieldInitializerName) {
- self.storage.class_field_initializer_name.replace(name);
+ self.rare_data().class_field_initializer_name.replace(name);
}
pub fn kind(&self) -> FunctionKind {
- self.storage.kind
+ let kind = self.asm_call_metadata.get() >> asm_call_metadata::FUNCTION_KIND_SHIFT
+ & asm_call_metadata::FUNCTION_KIND_MASK;
+ match kind {
+ 0 => FunctionKind::Normal,
+ 1 => FunctionKind::Generator,
+ 2 => FunctionKind::Async,
+ _ => FunctionKind::AsyncGenerator,
+ }
}
pub fn this_mode(&self) -> ThisMode {
- self.storage.this_mode
+ if self.is_arrow_function() {
+ ThisMode::Lexical
+ } else if self.strict() {
+ ThisMode::Strict
+ } else {
+ ThisMode::Global
+ }
}
pub fn function_length(&self) -> i32 {
- self.storage.function_length
+ self.function_length
}
pub fn formal_parameter_count(&self) -> u32 {
- self.formal_parameter_count.get()
+ self.asm_call_metadata.get() as u32
}
pub fn mapped_argument_names(&self) -> Rc<[Utf16FlyString]> {
- self.storage.mapped_argument_names.clone()
+ self.storage.parameter_names.as_ref().map_or_else(
+ || Vm::of_cell(self).no_parameter_names.clone(),
+ |names| names.mapped_argument_names.clone(),
+ )
}
pub fn parameter_binding_names(&self) -> Rc<[Utf16FlyString]> {
- self.storage.parameter_binding_names.clone()
+ self.storage.parameter_names.as_ref().map_or_else(
+ || Vm::of_cell(self).no_parameter_names.clone(),
+ |names| names.parameter_binding_names.clone(),
+ )
}
pub fn strict(&self) -> bool {
- self.strict.get()
+ self.metadata_bit(asm_call_metadata::STRICT)
}
pub fn is_arrow_function(&self) -> bool {
- self.storage.is_arrow_function
+ self.metadata_bit(asm_call_metadata::IS_ARROW_FUNCTION)
}
pub fn has_simple_parameter_list(&self) -> bool {
- self.storage.has_simple_parameter_list
+ self.metadata_bit(asm_call_metadata::HAS_SIMPLE_PARAMETER_LIST)
}
pub fn is_module_wrapper(&self) -> bool {
- self.storage.is_module_wrapper.get()
+ self.metadata_bit(asm_call_metadata::IS_MODULE_WRAPPER)
}
pub fn set_is_module_wrapper(&self, is_module_wrapper: bool) {
- self.storage.is_module_wrapper.set(is_module_wrapper);
+ self.set_metadata_bit(asm_call_metadata::IS_MODULE_WRAPPER, is_module_wrapper);
}
pub fn is_class_constructor(&self) -> bool {
- self.storage.is_class_constructor.get()
+ self.metadata_bit(asm_call_metadata::IS_CLASS_CONSTRUCTOR)
}
pub fn constructor_kind(&self) -> ConstructorKind {
- self.storage.constructor_kind.get()
+ if self.metadata_bit(asm_call_metadata::IS_DERIVED_CONSTRUCTOR) {
+ ConstructorKind::Derived
+ } else {
+ ConstructorKind::Base
+ }
}
pub fn set_constructor_kind(&self, constructor_kind: ConstructorKind) {
- self.storage.constructor_kind.set(constructor_kind);
+ self.set_metadata_bit(
+ asm_call_metadata::IS_DERIVED_CONSTRUCTOR,
+ constructor_kind == ConstructorKind::Derived,
+ );
}
pub fn uses_this(&self) -> bool {
- self.uses_this.get()
+ self.metadata_bit(asm_call_metadata::USES_THIS)
+ }
+
+ pub fn set_uses_this(&self, uses_this: bool) {
+ self.set_metadata_bit(asm_call_metadata::USES_THIS, uses_this);
}
pub fn this_value_needs_environment_resolution(&self) -> bool {
- self.storage.this_value_needs_environment_resolution.get()
+ self.metadata_bit(asm_call_metadata::THIS_VALUE_NEEDS_ENVIRONMENT_RESOLUTION)
}
/// How many properties to make room for in an object that a construction of the function creates with `shape`:
@@ -754,52 +877,75 @@ impl SharedFunctionInstanceData {
/// shape tells (every object a constructor builds the same way follows one). The transitions are looked at again
/// on the first, second, fourth and so on construction, up to the 1024th.
pub fn construct_reserve(&self, shape: Gc<Shape>) -> u32 {
- let storage = &self.storage;
- let count = storage.construct_count.get();
- if count <= MAX_CONSTRUCT_RESERVE_UPDATES && count.is_power_of_two() {
- let reserve = shape.property_count() + shape.longest_forward_transition_chain(MAX_CONSTRUCT_RESERVE);
- storage.construct_reserve.set(reserve.min(MAX_CONSTRUCT_RESERVE));
+ let metadata = self.asm_call_metadata.get();
+ let count =
+ (metadata >> asm_call_metadata::CONSTRUCT_COUNT_SHIFT & asm_call_metadata::CONSTRUCT_COUNT_MASK) as u32;
+ if count <= MAX_CONSTRUCT_RESERVE_UPDATES {
+ if count.is_power_of_two() {
+ let reserve = shape.property_count() + shape.longest_forward_transition_chain(MAX_CONSTRUCT_RESERVE);
+ self.construct_reserve.set(reserve.min(MAX_CONSTRUCT_RESERVE) as u8);
+ }
+ self.asm_call_metadata
+ .set(metadata + (1 << asm_call_metadata::CONSTRUCT_COUNT_SHIFT));
}
- storage.construct_count.set(count.saturating_add(1));
- storage.construct_reserve.get()
+ u32::from(self.construct_reserve.get())
}
pub fn closure_count(&self) -> ClosureCount {
- self.storage.closure_count.get()
+ let count = self.asm_call_metadata.get() >> asm_call_metadata::CLOSURE_COUNT_SHIFT
+ & asm_call_metadata::CLOSURE_COUNT_MASK;
+ match count {
+ 0 => ClosureCount::None,
+ 1 => ClosureCount::One,
+ _ => ClosureCount::Many,
+ }
}
/// Counts a new closure of the function.
pub fn note_closure_created(&self) {
- let count = match self.storage.closure_count.get() {
+ let count = match self.closure_count() {
ClosureCount::None => ClosureCount::One,
ClosureCount::One | ClosureCount::Many => ClosureCount::Many,
};
- self.storage.closure_count.set(count);
+ let metadata = self.asm_call_metadata.get()
+ & !(asm_call_metadata::CLOSURE_COUNT_MASK << asm_call_metadata::CLOSURE_COUNT_SHIFT);
+ self.asm_call_metadata
+ .set(metadata | (count as u64) << asm_call_metadata::CLOSURE_COUNT_SHIFT);
}
/// The reserve of the last construct_reserve(), without asking for it.
pub fn current_construct_reserve(&self) -> u32 {
- self.storage.construct_reserve.get()
+ u32::from(self.construct_reserve.get())
}
pub fn function_environment_needed(&self) -> bool {
- self.function_environment_needed.get()
+ self.metadata_bit(asm_call_metadata::FUNCTION_ENVIRONMENT_NEEDED)
+ }
+
+ pub fn set_function_environment_needed(&self, function_environment_needed: bool) {
+ self.set_metadata_bit(
+ asm_call_metadata::FUNCTION_ENVIRONMENT_NEEDED,
+ function_environment_needed,
+ );
}
pub fn might_need_arguments_object(&self) -> bool {
- self.storage.might_need_arguments_object.get()
+ self.metadata_bit(asm_call_metadata::MIGHT_NEED_ARGUMENTS_OBJECT)
}
pub fn contains_direct_call_to_eval(&self) -> bool {
- self.storage.contains_direct_call_to_eval.get()
+ self.metadata_bit(asm_call_metadata::CONTAINS_DIRECT_CALL_TO_EVAL)
}
pub fn function_environment_bindings_count(&self) -> usize {
- self.storage.function_environment_bindings_count.get()
+ self.storage.function_environment_bindings_count.get() as usize
}
pub fn var_environment_bindings_count(&self) -> usize {
- self.storage.var_environment_bindings_count.get()
+ self.storage
+ .rare_data
+ .get()
+ .map_or(0, |rare_data| rare_data.var_environment_bindings_count.get() as usize)
}
/// Where the function environments of calls to the function find their shape.
@@ -817,7 +963,7 @@ impl SharedFunctionInstanceData {
}
pub(crate) fn var_environment_shape_slot(&self) -> &NullableMember<EnvironmentShape> {
- &self.storage.var_environment_shape
+ &self.rare_data().var_environment_shape
}
/// RustIntegration::compile_function(): the function's executable, from the bytecode compiled ahead of time if
@@ -829,28 +975,21 @@ impl SharedFunctionInstanceData {
) -> Option<Gc<Executable>> {
let source_code = shared_data.source_code();
- if let Some(precompiled) = shared_data.storage.precompiled_bytecode_executable.take() {
- return Some(Executable::create_with_source_code(
- vm,
- precompiled.executable,
- source_code.as_ref(),
- ));
- }
-
- if let Some(cached_executable) = shared_data.storage.cached_bytecode_executable.take() {
- let source_code = source_code.expect("a function of a bytecode cache blob has its source code");
- return materialize_cached_function_executable(vm, &cached_executable, &source_code);
- }
-
- if !shared_data.storage.use_rust_compilation {
- return None;
- }
-
- let payload = shared_data
- .storage
- .rust_function_ast
- .take()
- .expect("a function that was not compiled yet has its AST");
+ let payload = match shared_data.storage.compile_input.take() {
+ CompileInput::PrecompiledBytecode(precompiled) => {
+ return Some(Executable::create_with_source_code(
+ vm,
+ precompiled.executable,
+ source_code.as_ref(),
+ ));
+ }
+ CompileInput::CachedBytecode(cached_executable) => {
+ let source_code = source_code.expect("a function of a bytecode cache blob has its source code");
+ return materialize_cached_function_executable(vm, &cached_executable, &source_code);
+ }
+ CompileInput::FunctionAst(payload) => payload,
+ CompileInput::None => panic!("a function that was not compiled yet has its AST"),
+ };
// NB: The frontend checks that nested functions lie within the source, which is unknown without a source code.
let source_length = source_code
.as_ref()
diff --git a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
index c8574c32679..e3d48dcddc4 100644
--- a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
+++ b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
@@ -499,9 +499,8 @@ impl SourceTextModule {
Vec::new(),
);
tla_shared_data.set_is_module_wrapper(true);
- tla_shared_data.uses_this.set(true);
- tla_shared_data.function_environment_needed.set(true);
- tla_shared_data.update_asm_call_metadata();
+ tla_shared_data.set_uses_this(true);
+ tla_shared_data.set_function_environment_needed(true);
tla_shared_data.set_executable(Some(top_level_await_executable));
tla_shared_data
}