Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
use crate::bytecode::instruction::OpCode;
use core::cell::{Cell, OnceCell, RefCell};
use core::ptr::NonNull;
use std::collections::HashMap;
use std::io::Write;
use std::rc::Rc;
use std::sync::Arc;
use ak::Utf16FlyString;
use crate::breakpoint::BreakpointID;
use crate::bytecode::class_blueprint::ClassBlueprint;
use crate::bytecode::constant::{AbstractOperationKind, WellKnownSymbolKind};
use crate::bytecode::dump::{count_basic_blocks, dump_bytecode};
use crate::bytecode::encoding::{IdentifierTableIndex, PropertyKeyTableIndex, StringTableIndex};
use crate::bytecode::executable_data::{ConstantValue, ExceptionHandler, MAXIMUM_INTERNED_CONSTANT_LENGTH};
use crate::bytecode::executable_data::{ExecutableData, LocalVariableMetadata};
use crate::bytecode::feedback::{ExecutableFeedback, FeedbackSlotCounts};
use crate::bytecode::operand::UNCACHED_SITE;
use crate::bytecode::source_map::{SourceMapEntries, SourceMapEntry, SourceOffset};
use crate::gc::class::{ExternalMemorySize, Finalize, GcCell, define_cell};
use crate::gc::defer_gc::DeferGc;
use crate::gc::root::MarkedVec;
use crate::gc::sweep::Sweep;
use crate::gc::visitor::{Trace, Visitor};
use crate::gc::weak::SweptAfterCollection;
use crate::interpreter::vm::Vm;
use crate::jit::InterpreterTier;
use crate::jit::code::ExecutableJitState;
use crate::layout::buffer::{BlockSlice, InterpreterBuffer, ThinSlice};
use crate::layout::cell::{CellHeader, CellHeaderTail, Gc};
use crate::layout::executable::{
CALL_CACHE_EMPTY_CALLEE, CALL_CACHE_TARGET_EXECUTABLE, CALL_CACHE_TARGET_TAG_MASK, CallCache, ExecutableHead,
};
use crate::layout::feedback::ExecutableFeedbackHead;
use crate::layout::function_object::FunctionObject;
use crate::layout::member::NullableMember;
use crate::layout::object::Object;
use crate::layout::property_lookup_cache::KeyedPropertyLookupCacheEntryLayout;
pub use crate::layout::property_lookup_cache::{
EnvironmentCoordinate, GlobalVariableCache, ObjectPropertyIteratorCache, ObjectPropertyIteratorCacheData,
ObjectPropertyIteratorFastPath, PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK, PROPERTY_LOOKUP_CACHE_KEYED_GENERIC_DATA,
PROPERTY_LOOKUP_CACHE_POLYMORPHIC_DATA_TAG, PropertyLookupCache, PropertyLookupCacheEntry,
PropertyLookupCacheEntryType,
};
use crate::layout::shape::{Shape, WatchpointSet};
use crate::layout::value::Value;
use crate::layout_forward::FlyStringSlot;
use crate::runtime::array::Array;
use crate::runtime::big_int::{BigInt, SignedBigInteger};
use crate::runtime::environment_shape::{EnvironmentShape, EnvironmentShapeCache};
use crate::runtime::primitive_string::PrimitiveString;
use crate::runtime::property_key::PropertyKey;
use crate::runtime::shape::ShapeKey;
use crate::runtime::shared_function_instance_data::{FlushedCode, SharedFunctionInstanceData};
use crate::runtime::value::number_to_string;
use crate::slice_block::{SliceBlock, SliceBlockBuilder};
use crate::source_code::SourceCode;
use crate::source_range::{Position, SourceRange};
use crate::utf16::Utf16View;
use crate::utf16::to_utf16_fly_string;
use libjs_runtime_macros::Trace;
/// The contents of a cache entry, copied out of the cache so that no reference into its storage outlives a call that
/// may update the cache and free that storage.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PropertyLookupCacheEntryData {
pub entry_type: PropertyLookupCacheEntryType,
pub property_offset: u32,
pub writes_data_property: bool,
pub new_shape: Option<Gc<Shape>>,
pub shape: Option<ShapeKey>,
pub prototype: Option<Gc<Object>>,
pub prototype_chain_validity: Option<Gc<WatchpointSet>>,
/// See PropertyLookupCacheEntry::key.
pub key: u64,
pub getter: Option<Gc<FunctionObject>>,
}
impl Default for PropertyLookupCacheEntryData {
fn default() -> Self {
Self {
entry_type: PropertyLookupCacheEntryType::Empty,
property_offset: 0,
writes_data_property: false,
new_shape: None,
shape: None,
prototype: None,
prototype_chain_validity: None,
key: 0,
getter: None,
}
}
}
impl PropertyLookupCacheEntryData {
fn has_same_cache_key_as(&self, other: &Self) -> bool {
if self.entry_type == PropertyLookupCacheEntryType::Empty
|| other.entry_type == PropertyLookupCacheEntryType::Empty
{
return false;
}
if self.entry_type != other.entry_type || self.key != other.key {
return false;
}
// NB: An entry for an earlier dictionary generation of the shape is replaced too.
let same_shape = self.shape.map(|key| key.shape) == other.shape.map(|key| key.shape);
match self.entry_type {
PropertyLookupCacheEntryType::AddOwnProperty => same_shape && self.new_shape == other.new_shape,
PropertyLookupCacheEntryType::ChangeOwnProperty
| PropertyLookupCacheEntryType::GetOwnProperty
| PropertyLookupCacheEntryType::GetMissingProperty
| PropertyLookupCacheEntryType::MissingOwnProperty => same_shape,
PropertyLookupCacheEntryType::ChangePropertyInPrototypeChain
| PropertyLookupCacheEntryType::GetPropertyInPrototypeChain => {
same_shape && self.prototype == other.prototype
}
PropertyLookupCacheEntryType::Empty => unreachable!("empty entries have no cache key"),
}
}
fn has_dead_cell(&self, sweep: &Sweep<'_>) -> bool {
(self.key != 0 && sweep.is_dead_or_moving(Value::from_bits(self.key).as_cell()))
|| self.new_shape.is_some_and(|shape| sweep.is_dead_or_moving(shape))
|| self.shape.is_some_and(|key| sweep.is_dead_or_moving(key.shape))
|| self
.prototype
.is_some_and(|prototype| sweep.is_dead_or_moving(prototype))
|| self
.prototype_chain_validity
.is_some_and(|validity| sweep.is_dead_or_moving(validity))
}
}
// SAFETY: Entries live in the inline caches of executables and of the VM, which the VM sweeps after each collection (see
// Vm::remove_dead_cells_from_property_lookup_caches()).
unsafe impl SweptAfterCollection for PropertyLookupCacheEntry {}
impl PropertyLookupCacheEntry {
/// An empty entry, like the default PropertyLookupCacheEntryData.
pub const fn new() -> Self {
Self {
entry_type: Cell::new(PropertyLookupCacheEntryType::Empty),
property_offset: Cell::new(0),
shape_dictionary_generation: Cell::new(0),
writes_data_property: Cell::new(false),
new_shape: Cell::new(None),
shape: Cell::new(None),
prototype: Cell::new(None),
prototype_chain_validity: Cell::new(None),
key: Cell::new(0),
getter: Cell::new(None),
}
}
fn from_data(data: PropertyLookupCacheEntryData) -> Self {
Self {
entry_type: Cell::new(data.entry_type),
property_offset: Cell::new(data.property_offset),
shape_dictionary_generation: Cell::new(data.shape.map_or(0, |key| key.dictionary_generation)),
writes_data_property: Cell::new(data.writes_data_property),
new_shape: Cell::new(data.new_shape),
shape: Cell::new(data.shape.map(|key| key.shape)),
prototype: Cell::new(data.prototype),
prototype_chain_validity: Cell::new(data.prototype_chain_validity),
key: Cell::new(data.key),
getter: Cell::new(data.getter),
}
}
pub fn get(&self) -> PropertyLookupCacheEntryData {
PropertyLookupCacheEntryData {
entry_type: self.entry_type.get(),
property_offset: self.property_offset.get(),
writes_data_property: self.writes_data_property.get(),
new_shape: self.new_shape.get(),
shape: self.shape_key(),
prototype: self.prototype.get(),
prototype_chain_validity: self.prototype_chain_validity.get(),
key: self.key.get(),
getter: self.getter.get(),
}
}
pub fn set(&self, data: PropertyLookupCacheEntryData) {
self.entry_type.set(data.entry_type);
self.property_offset.set(data.property_offset);
self.shape_dictionary_generation
.set(data.shape.map_or(0, |key| key.dictionary_generation));
self.writes_data_property.set(data.writes_data_property);
self.new_shape.set(data.new_shape);
self.shape.set(data.shape.map(|key| key.shape));
self.prototype.set(data.prototype);
self.prototype_chain_validity.set(data.prototype_chain_validity);
self.key.set(data.key);
self.getter.set(data.getter);
}
pub fn shape_key(&self) -> Option<ShapeKey> {
self.shape.get().map(|shape| ShapeKey {
shape,
dictionary_generation: self.shape_dictionary_generation.get(),
})
}
/// Forgets the whole entry if one of its cells died in this collection, as clear_cache_entry_if_dead does.
fn clear_if_it_has_a_dead_cell(&self, sweep: &Sweep<'_>) {
if self.get().has_dead_cell(sweep) {
self.set(PropertyLookupCacheEntryData::default());
}
if self.getter.get().is_some_and(|getter| sweep.is_dead_or_moving(getter)) {
self.getter.set(None);
}
}
}
impl Default for PropertyLookupCacheEntry {
fn default() -> Self {
Self::new()
}
}
pub const MAX_NUMBER_OF_SHAPES_TO_REMEMBER: usize = 4;
// NB: GetById probes the entries of polymorphic caches unrolled.
const _: () = assert!(MAX_NUMBER_OF_SHAPES_TO_REMEMBER == 4);
pub const MEGAMORPHIC_INDEX_BITS: u32 = 4;
pub const MEGAMORPHIC_PRIMARY_CACHE_SIZE: usize = 1 << MEGAMORPHIC_INDEX_BITS;
pub const MEGAMORPHIC_SECONDARY_CACHE_SIZE: usize = 1 << MEGAMORPHIC_INDEX_BITS;
/// Fibonacci hashing (see megamorphic_hash()).
pub const MEGAMORPHIC_HASH_MULTIPLIER: u32 = 0x9e37_79b9;
const POLYMORPHIC_DATA_TAG: usize = PROPERTY_LOOKUP_CACHE_POLYMORPHIC_DATA_TAG;
pub const MEGAMORPHIC_DATA_TAG: usize = 2;
/// How many (shape, key) pairs a megamorphic cache of a keyed access may miss and learn before it gives up (see
/// PropertyLookupCache::is_keyed_generic()).
const MAX_KEYED_MEGAMORPHIC_MISSES: u32 = 1024;
/// How many entries JIT code may copy into the tables of a megamorphic cache of a named access from the VM's keyed
/// property lookup cache, where it found them after missing the tables (see
/// PropertyLookupCache::take_vm_cache_lesson()). An access whose tables keep missing sees more shapes than they hold,
/// and then only uses the VM's cache.
pub const MAX_MEGAMORPHIC_VM_CACHE_LESSONS: u32 = 16;
/// Which tier a property lookup cache is in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PropertyLookupCacheTier {
Empty,
Monomorphic,
Polymorphic,
Megamorphic,
}
const _: () = assert!(MEGAMORPHIC_PRIMARY_CACHE_SIZE.is_power_of_two());
const _: () = assert!(MEGAMORPHIC_SECONDARY_CACHE_SIZE.is_power_of_two());
// The interpreter reads the first entry at the start of each tier's data.
#[repr(C)]
struct MonomorphicData {
entry: PropertyLookupCacheEntry,
}
/// The data of the caches of the slot that the sites past the last one share, in every thread. Its entry stays empty,
/// so that their accesses go straight to their slow paths.
#[repr(transparent)]
struct UncacheableData(MonomorphicData);
// SAFETY: Nothing writes the entry, so threads only ever read it: monomorphic_data() does not hand it out, so neither
// do first_entry_slot(), entries() and entry_slots_for_shape(), update(), forget_entries() and
// remove_dead_entries() skip the caches that share it, and clear() does not free it.
unsafe impl Sync for UncacheableData {}
static UNCACHEABLE_DATA: UncacheableData = UncacheableData(MonomorphicData {
entry: PropertyLookupCacheEntry::new(),
});
/// The data pointer of the caches that share UNCACHEABLE_DATA.
fn uncacheable_data() -> usize {
core::ptr::addr_of!(UNCACHEABLE_DATA.0).expose_provenance()
}
#[repr(C)]
struct PolymorphicData {
entries: [PropertyLookupCacheEntry; MAX_NUMBER_OF_SHAPES_TO_REMEMBER],
}
// Keep the most recently used entry first so generated interpreter code can use the
// same fast path for every cache tier. Other shapes use the bounded two-level cache.
#[repr(C)]
struct MegamorphicData {
entry: PropertyLookupCacheEntry,
primary_entries: [PropertyLookupCacheEntry; MEGAMORPHIC_PRIMARY_CACHE_SIZE],
secondary_entries: [PropertyLookupCacheEntry; MEGAMORPHIC_SECONDARY_CACHE_SIZE],
/// Misses of a keyed access (see MAX_KEYED_MEGAMORPHIC_MISSES).
keyed_misses: Cell<u32>,
/// Entries JIT code copied from the VM's keyed property lookup cache (see MAX_MEGAMORPHIC_VM_CACHE_LESSONS).
vm_cache_lessons: Cell<u32>,
}
const _: () = assert!(align_of::<MonomorphicData>() > PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK);
const _: () = assert!(align_of::<PolymorphicData>() > PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK);
const _: () = assert!(align_of::<MegamorphicData>() > PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK);
const _: () = assert!(core::mem::offset_of!(MonomorphicData, entry) == 0);
const _: () = assert!(core::mem::offset_of!(PolymorphicData, entries) == 0);
const _: () = assert!(core::mem::offset_of!(MegamorphicData, entry) == 0);
/// Where the hash tables of a megamorphic cache's data are, for JIT code that probes them.
pub const MEGAMORPHIC_PRIMARY_ENTRIES_OFFSET: usize = core::mem::offset_of!(MegamorphicData, primary_entries);
pub const MEGAMORPHIC_SECONDARY_ENTRIES_OFFSET: usize = core::mem::offset_of!(MegamorphicData, secondary_entries);
pub const MEGAMORPHIC_VM_CACHE_LESSONS_OFFSET: usize = core::mem::offset_of!(MegamorphicData, vm_cache_lessons);
/// Fibonacci hashing of the low 32 bits of the shape pointer, mixed with the key of keyed caches: the indices are the
/// top bits of the product, which takes a multiply and a shift.
fn megamorphic_hash(shape: Gc<Shape>, key: u64) -> u32 {
((shape.as_ptr().addr() as u64 ^ key) as u32).wrapping_mul(MEGAMORPHIC_HASH_MULTIPLIER)
}
fn megamorphic_primary_index(shape: Gc<Shape>, key: u64) -> usize {
(megamorphic_hash(shape, key) >> (32 - MEGAMORPHIC_INDEX_BITS)) as usize
}
fn megamorphic_secondary_index(shape: Gc<Shape>, key: u64) -> usize {
(megamorphic_hash(shape, key) >> (32 - 2 * MEGAMORPHIC_INDEX_BITS)) as usize
& (MEGAMORPHIC_SECONDARY_CACHE_SIZE - 1)
}
/// The slot of a megamorphic cache's hash tables that holds the entry for `shape` and `key`, if one does.
fn megamorphic_slot_for_shape(data: &MegamorphicData, shape: Gc<Shape>, key: u64) -> Option<&PropertyLookupCacheEntry> {
let is_for_shape = |slot: &&PropertyLookupCacheEntry| {
let entry = slot.get();
entry.shape.is_some_and(|entry_shape| entry_shape.shape == shape) && entry.key == key
};
Some(&data.primary_entries[megamorphic_primary_index(shape, key)])
.filter(is_for_shape)
.or_else(|| Some(&data.secondary_entries[megamorphic_secondary_index(shape, key)]).filter(is_for_shape))
}
fn insert_megamorphic_entry(data: &MegamorphicData, entry: &PropertyLookupCacheEntryData) {
let lookup_shape = entry.shape.expect("a megamorphic entry has a shape").shape;
let primary_entry = &data.primary_entries[megamorphic_primary_index(lookup_shape, entry.key)];
let primary = primary_entry.get();
if let Some(displaced_shape) = primary.shape.map(|key| key.shape)
&& (displaced_shape != lookup_shape || primary.key != entry.key)
{
data.secondary_entries[megamorphic_secondary_index(displaced_shape, primary.key)].set(primary);
}
primary_entry.set(*entry);
}
/// The entries of a cache that may hold a shape, copied out by PropertyLookupCache::entries_for_shape().
pub struct PropertyLookupCacheEntries {
entries: [PropertyLookupCacheEntryData; MAX_NUMBER_OF_SHAPES_TO_REMEMBER],
count: usize,
}
impl PropertyLookupCacheEntries {
pub fn as_slice(&self) -> &[PropertyLookupCacheEntryData] {
&self.entries[..self.count]
}
}
// Represents one tiered inline cache used for property lookups. The tier is in the low bits of the data pointer.
impl PropertyLookupCache {
pub fn new() -> Self {
Self { data: Cell::new(0) }
}
/// The cache of the slot that the sites past the last one share.
fn new_uncacheable() -> Self {
Self {
data: Cell::new(uncacheable_data()),
}
}
fn is_uncacheable(&self) -> bool {
self.data.get() == uncacheable_data()
}
fn data_pointer<T>(&self, tag: usize) -> Option<&T> {
let data = self.data.get();
if data == 0 || data & PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK != tag {
return None;
}
let pointer = core::ptr::with_exposed_provenance::<T>(data & !PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK);
// SAFETY: The tagged pointer came from Box::into_raw of a T with this tag, and the cache owns it until clear(), or
// it is UNCACHEABLE_DATA, which is static.
Some(unsafe { &*pointer })
}
/// The data of a monomorphic cache, never UNCACHEABLE_DATA, whose entry must not be lent out.
fn monomorphic_data(&self) -> Option<&MonomorphicData> {
if self.is_uncacheable() {
return None;
}
self.data_pointer(0)
}
fn polymorphic_data(&self) -> Option<&PolymorphicData> {
self.data_pointer(POLYMORPHIC_DATA_TAG)
}
fn megamorphic_data(&self) -> Option<&MegamorphicData> {
self.data_pointer(MEGAMORPHIC_DATA_TAG)
}
/// Whether this megamorphic cache may learn one more entry from the VM's keyed property lookup cache (see
/// MAX_MEGAMORPHIC_VM_CACHE_LESSONS), counting it if so.
pub fn take_vm_cache_lesson(&self) -> bool {
let Some(data) = self.megamorphic_data() else {
return false;
};
let lessons = data.vm_cache_lessons.get();
if lessons >= MAX_MEGAMORPHIC_VM_CACHE_LESSONS {
return false;
}
data.vm_cache_lessons.set(lessons + 1);
true
}
fn set_data<T>(&self, data: Box<T>, tag: usize) {
let address = Box::into_raw(data).expose_provenance();
assert!(address & PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK == 0);
self.data.set(address | tag);
}
/// Whether this cache keeps the entries of more shapes than a polymorphic cache can hold in hash tables.
pub fn is_megamorphic(&self) -> bool {
self.megamorphic_data().is_some()
}
/// Whether this is the cache of a keyed access that saw too many (shape, key) pairs to keep track of. Such a cache
/// stays empty, so its accesses go straight to their slow paths.
pub fn is_keyed_generic(&self) -> bool {
self.data.get() == PROPERTY_LOOKUP_CACHE_KEYED_GENERIC_DATA
}
pub fn first_entry(&self) -> Option<PropertyLookupCacheEntryData> {
self.first_entry_slot().map(PropertyLookupCacheEntry::get)
}
/// The entry the interpreter consults, for updating it in place. The reference must not be held across anything
/// that may update the cache.
pub fn first_entry_slot(&self) -> Option<&PropertyLookupCacheEntry> {
if let Some(data) = self.monomorphic_data() {
return Some(&data.entry);
}
if let Some(data) = self.polymorphic_data() {
return Some(&data.entries[0]);
}
if let Some(data) = self.megamorphic_data() {
return Some(&data.entry);
}
None
}
pub fn tier(&self) -> PropertyLookupCacheTier {
let data = self.data.get();
if data == 0 {
return PropertyLookupCacheTier::Empty;
}
if self.is_keyed_generic() {
return PropertyLookupCacheTier::Megamorphic;
}
match data & PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK {
POLYMORPHIC_DATA_TAG => PropertyLookupCacheTier::Polymorphic,
MEGAMORPHIC_DATA_TAG => PropertyLookupCacheTier::Megamorphic,
_ => PropertyLookupCacheTier::Monomorphic,
}
}
/// The entries the interpreter looks through: every entry of a polymorphic cache, and the most recently used one
/// of the others.
pub fn entries(&self) -> &[PropertyLookupCacheEntry] {
if let Some(data) = self.monomorphic_data() {
return core::slice::from_ref(&data.entry);
}
if let Some(data) = self.polymorphic_data() {
return &data.entries;
}
if let Some(data) = self.megamorphic_data() {
return core::slice::from_ref(&data.entry);
}
&[]
}
fn copy_entries(entries: &[PropertyLookupCacheEntry]) -> PropertyLookupCacheEntries {
let mut copied = PropertyLookupCacheEntries {
entries: [PropertyLookupCacheEntryData::default(); MAX_NUMBER_OF_SHAPES_TO_REMEMBER],
count: entries.len(),
};
for (copy, entry) in copied.entries.iter_mut().zip(entries) {
*copy = entry.get();
}
copied
}
/// The entries that may be for `shape` and `key` (see PropertyLookupCacheEntry::key; 0 for named accesses).
/// Callers check each entry's shape and key. A megamorphic cache finds the one for the shape and key and moves it
/// first, where the interpreter looks.
pub fn entries_for_shape(&self, shape: Gc<Shape>, key: u64) -> PropertyLookupCacheEntries {
Self::copy_entries(self.entry_slots_for_shape(shape, key))
}
/// entries_for_shape() in place, for the cache-only fast paths. The entries must not be held across anything that
/// may update the cache.
#[inline]
pub fn entry_slots_for_shape(&self, shape: Gc<Shape>, key: u64) -> &[PropertyLookupCacheEntry] {
let Some(data) = self.megamorphic_data() else {
return self.entries();
};
let Some(slot) = megamorphic_slot_for_shape(data, shape, key) else {
return &[];
};
data.entry.set(slot.get());
core::slice::from_ref(&data.entry)
}
/// The entry a megamorphic cache has for `shape` and `key`, if it has one, without moving it to the front like
/// `entry_slots_for_shape()` does.
pub fn megamorphic_entry_for_shape(&self, shape: Gc<Shape>, key: u64) -> Option<&PropertyLookupCacheEntry> {
megamorphic_slot_for_shape(self.megamorphic_data()?, shape, key)
}
/// Records an entry of `entry_type`, filled in by `callback`, moving the cache to the next tier when it has no
/// room for it. Keyed sites also refresh entries after hits in the VM cache. Keep this out of line instead of
/// growing the frames of the property access paths that every access runs through.
#[inline(never)]
pub fn update(
&self,
entry_type: PropertyLookupCacheEntryType,
callback: impl FnOnce(&mut PropertyLookupCacheEntryData),
) {
if self.is_keyed_generic() || self.is_uncacheable() {
return;
}
let mut new_entry = PropertyLookupCacheEntryData {
entry_type,
..Default::default()
};
callback(&mut new_entry);
if let Some(data) = self.megamorphic_data() {
// NB: A keyed access that keeps missing cycles through more keys than the cache can hold, and filling it
// would cost more than it saves.
if new_entry.key != 0 {
let lookup_shape = new_entry.shape.expect("a megamorphic entry has a shape").shape;
let is_known = |entry: &PropertyLookupCacheEntry| {
let entry = entry.get();
entry.shape.is_some_and(|key| key.shape == lookup_shape) && entry.key == new_entry.key
};
let known = is_known(&data.primary_entries[megamorphic_primary_index(lookup_shape, new_entry.key)])
|| is_known(&data.secondary_entries[megamorphic_secondary_index(lookup_shape, new_entry.key)]);
if !known {
data.keyed_misses.set(data.keyed_misses.get() + 1);
}
if data.keyed_misses.get() > MAX_KEYED_MEGAMORPHIC_MISSES {
self.clear();
self.data.set(PROPERTY_LOOKUP_CACHE_KEYED_GENERIC_DATA);
return;
}
}
insert_megamorphic_entry(data, &new_entry);
data.entry.set(new_entry);
return;
}
if self.data.get() == 0 {
self.set_data(
Box::new(MonomorphicData {
entry: PropertyLookupCacheEntry::from_data(new_entry),
}),
0,
);
return;
}
if let Some(data) = self.monomorphic_data() {
let old_entry = data.entry.get();
if old_entry.entry_type == PropertyLookupCacheEntryType::Empty
|| old_entry.has_same_cache_key_as(&new_entry)
{
data.entry.set(new_entry);
return;
}
let new_data = Box::new(PolymorphicData {
entries: core::array::from_fn(|_| PropertyLookupCacheEntry::new()),
});
new_data.entries[0].set(new_entry);
new_data.entries[1].set(old_entry);
self.clear();
self.set_data(new_data, POLYMORPHIC_DATA_TAG);
return;
}
let entries = &self
.polymorphic_data()
.expect("a cache with data is in one of the tiers")
.entries;
let mut insertion_index = entries
.iter()
.position(|entry| entry.get().has_same_cache_key_as(&new_entry))
.unwrap_or(entries.len());
if insertion_index == entries.len()
&& entries[entries.len() - 1].entry_type.get() != PropertyLookupCacheEntryType::Empty
{
self.move_full_polymorphic_entries_to_megamorphic_tier(&new_entry);
return;
}
if insertion_index == entries.len() {
insertion_index = entries.len() - 1;
}
for index in (1..=insertion_index).rev() {
entries[index].set(entries[index - 1].get());
}
entries[0].set(new_entry);
}
/// Boxing a MegamorphicData builds it on the stack first, in a frame of a few KB, so this stays out of line from
/// update(), which runs on every miss.
#[cold]
#[inline(never)]
fn move_full_polymorphic_entries_to_megamorphic_tier(&self, new_entry: &PropertyLookupCacheEntryData) {
let entries = &self
.polymorphic_data()
.expect("only a polymorphic cache becomes megamorphic")
.entries;
let new_data = Box::new(MegamorphicData {
entry: PropertyLookupCacheEntry::new(),
primary_entries: core::array::from_fn(|_| PropertyLookupCacheEntry::new()),
secondary_entries: core::array::from_fn(|_| PropertyLookupCacheEntry::new()),
keyed_misses: Cell::new(0),
vm_cache_lessons: Cell::new(0),
});
for entry in entries.iter().rev() {
let entry = entry.get();
if entry.shape.is_some() {
insert_megamorphic_entry(&new_data, &entry);
}
}
insert_megamorphic_entry(&new_data, new_entry);
new_data.entry.set(*new_entry);
self.clear();
self.set_data(new_data, MEGAMORPHIC_DATA_TAG);
}
/// Forgets the entries, but keeps the storage of a monomorphic cache, whose next entry then takes the place of the
/// empty one.
pub fn forget_entries(&self) {
if self.is_uncacheable() {
return;
}
if let Some(data) = self.monomorphic_data() {
data.entry.set(PropertyLookupCacheEntryData::default());
return;
}
self.clear();
}
pub fn clear(&self) {
if !self.is_uncacheable() {
self.free_data();
}
}
fn free_data(&self) {
let data = self.data.get();
if data == 0 || data == PROPERTY_LOOKUP_CACHE_KEYED_GENERIC_DATA {
self.data.set(0);
return;
}
let address = data & !PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK;
// SAFETY: The tagged pointer came from Box::into_raw of the tier its tag names.
unsafe {
match data & PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK {
0 => drop(Box::from_raw(
core::ptr::with_exposed_provenance_mut::<MonomorphicData>(address),
)),
POLYMORPHIC_DATA_TAG => {
drop(Box::from_raw(
core::ptr::with_exposed_provenance_mut::<PolymorphicData>(address),
));
}
MEGAMORPHIC_DATA_TAG => {
drop(Box::from_raw(
core::ptr::with_exposed_provenance_mut::<MegamorphicData>(address),
));
}
_ => unreachable!("a cache tier tag"),
}
}
self.data.set(0);
}
/// Forgets the entries with a cell that died in this collection.
pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {
if self.is_uncacheable() {
return;
}
if let Some(data) = self.megamorphic_data() {
for entry in data
.primary_entries
.iter()
.chain(&data.secondary_entries)
.chain(core::iter::once(&data.entry))
{
entry.clear_if_it_has_a_dead_cell(sweep);
}
return;
}
for entry in self.entries() {
entry.clear_if_it_has_a_dead_cell(sweep);
}
}
}
impl Default for PropertyLookupCache {
fn default() -> Self {
Self::new()
}
}
impl Drop for PropertyLookupCache {
fn drop(&mut self) {
self.clear();
}
}
impl Default for GlobalVariableCache {
fn default() -> Self {
Self {
entry: PropertyLookupCacheEntry::new(),
environment_serial_number: Cell::new(0),
environment_binding_index: Cell::new(0),
has_environment_binding_index: Cell::new(false),
}
}
}
impl GlobalVariableCache {
/// Assigns a default GlobalVariableCache.
pub fn reset(&self) {
self.entry.set(PropertyLookupCacheEntryData::default());
self.environment_serial_number.set(0);
self.environment_binding_index.set(0);
self.has_environment_binding_index.set(false);
}
pub fn first_entry(&self) -> Option<PropertyLookupCacheEntryData> {
let entry = self.entry.get();
(entry.entry_type != PropertyLookupCacheEntryType::Empty).then_some(entry)
}
pub fn update(
&self,
entry_type: PropertyLookupCacheEntryType,
callback: impl FnOnce(&mut PropertyLookupCacheEntryData),
) {
let mut entry = PropertyLookupCacheEntryData {
entry_type,
..Default::default()
};
callback(&mut entry);
self.entry.set(entry);
}
}
/// Defines the call sites of the runtime that keep a property lookup cache of their own.
macro_rules! define_static_property_lookup_cache_sites {
($($site:ident,)*) => {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(usize)]
pub enum StaticPropertyLookupCacheSite {
$($site,)*
}
const STATIC_PROPERTY_LOOKUP_CACHE_SITE_COUNT: usize = [$(StaticPropertyLookupCacheSite::$site,)*].len();
};
}
define_static_property_lookup_cache_sites! {
ObjectOrdinaryToPrimitiveToString,
ObjectOrdinaryToPrimitiveValueOf,
LengthOfArrayLike,
SpeciesConstructorConstructor,
SpeciesConstructorSpecies,
ValueToPrimitive,
GetPrototypeFromConstructorPrototype,
ValueIsRegExp,
InstanceOfHasInstance,
OrdinaryHasInstancePrototype,
GetIteratorDirectNext,
GetIteratorFromMethodNext,
GetIteratorSyncMethod,
GetIteratorMethod,
GetIteratorFlattenableMethod,
IteratorCompleteDone,
IteratorValueValue,
IteratorCloseReturn,
ArrayAppendIteratorMethod,
ObjectPrototypeToStringToStringTag,
ArrayFromIteratorMethod,
ArraySpeciesCreateConstructor,
ArraySpeciesCreateSpecies,
JSONSerializeToJSON,
PromiseResolveConstructor,
PromiseResolveFunctionThen,
StringPrototypeMatchMatcher,
StringPrototypeMatchAllMatcher,
StringPrototypeReplaceReplacer,
StringPrototypeReplaceAllReplacer,
StringPrototypeSearchSearcher,
StringPrototypeSplitSplitter,
MapIterationIsUnobservableNextMethod,
SetIterationIsUnobservableNextMethod,
RegExpIncrementLastIndexGetLastIndex,
RegExpIncrementLastIndexSetLastIndex,
RegExpLastIndexUnobservableLastIndex,
RegExpBuiltinExecGetLastIndex,
RegExpBuiltinExecResetLastIndexPastEnd,
RegExpBuiltinExecResetLastIndexNoMatch,
RegExpBuiltinExecSetLastIndex,
RegExpBuiltinExecSetGroups,
RegExpExecExec,
RegExpPrototypeFlagsHasIndices,
RegExpPrototypeFlagsGlobal,
RegExpPrototypeFlagsIgnoreCase,
RegExpPrototypeFlagsMultiline,
RegExpPrototypeFlagsDotAll,
RegExpPrototypeFlagsUnicode,
RegExpPrototypeFlagsUnicodeSets,
RegExpPrototypeFlagsSticky,
RegExpPrototypeSymbolMatchFlags,
RegExpPrototypeSymbolMatchLastIndex,
RegExpPrototypeSymbolMatchAllFlags,
RegExpPrototypeSymbolMatchAllGetLastIndex,
RegExpPrototypeSymbolMatchAllSetLastIndex,
RegExpPrototypeSymbolReplaceFastGetLastIndex,
RegExpPrototypeSymbolReplaceFastResetLastIndex,
RegExpPrototypeSymbolReplaceFastSetLastIndex,
RegExpPrototypeSymbolReplaceFlags,
RegExpPrototypeSymbolReplaceLastIndex,
RegExpPrototypeSymbolReplaceIndex,
RegExpPrototypeSymbolReplaceGroups,
RegExpPrototypeSymbolSearchGetLastIndex,
RegExpPrototypeSymbolSearchResetLastIndex,
RegExpPrototypeSymbolSearchGetCurrentLastIndex,
RegExpPrototypeSymbolSearchRestoreLastIndex,
RegExpPrototypeSymbolSearchIndex,
RegExpPrototypeSymbolSplitFlags,
RegExpPrototypeSymbolSplitSetLastIndex,
RegExpPrototypeSymbolSplitGetLastIndex,
RegExpPrototypeToStringSource,
RegExpPrototypeToStringFlags,
IteratorConcatIteratorMethod,
}
/// The caches of the static call sites, one set per VM, which prunes them like the caches of executables.
pub struct StaticPropertyLookupCaches {
caches: [PropertyLookupCache; STATIC_PROPERTY_LOOKUP_CACHE_SITE_COUNT],
}
impl StaticPropertyLookupCaches {
pub fn new() -> Self {
Self {
caches: core::array::from_fn(|_| PropertyLookupCache::new()),
}
}
pub fn get(&self, site: StaticPropertyLookupCacheSite) -> &PropertyLookupCache {
&self.caches[site as usize]
}
pub fn contains(&self, cache: &PropertyLookupCache) -> bool {
self.caches.as_ptr_range().contains(&core::ptr::from_ref(cache))
}
pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {
for cache in &self.caches {
cache.remove_dead_entries(sweep);
}
}
}
impl Default for StaticPropertyLookupCaches {
fn default() -> Self {
Self::new()
}
}
pub const KEYED_PROPERTY_LOOKUP_CACHE_ENTRY_COUNT: usize = 1 << KEYED_PROPERTY_LOOKUP_CACHE_INDEX_BITS;
pub const KEYED_PROPERTY_LOOKUP_CACHE_INDEX_BITS: u32 = 11;
/// One remembered lookup of a property by name on a shape. Like the entries of a PropertyLookupCache, it does not keep
/// its cells alive; the VM's sweep callback clears the entries whose cells died.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct KeyedPropertyLookup {
pub entry_type: PropertyLookupCacheEntryType,
pub property_offset: u32,
pub shape_dictionary_generation: u32,
pub shape: Option<Gc<Shape>>,
pub prototype: Option<Gc<Object>>,
pub prototype_chain_validity: Option<Gc<WatchpointSet>>,
/// The shape that adding the property to an object of `shape` gives it, for `AddOwnProperty` entries of the
/// keyed property store cache.
pub new_shape: Option<Gc<Shape>>,
}
impl KeyedPropertyLookup {
pub fn for_shape(shape: ShapeKey) -> Self {
Self {
shape_dictionary_generation: shape.dictionary_generation,
shape: Some(shape.shape),
..Default::default()
}
}
pub fn shape_key(&self) -> Option<ShapeKey> {
self.shape.map(|shape| ShapeKey {
shape,
dictionary_generation: self.shape_dictionary_generation,
})
}
}
impl Default for KeyedPropertyLookup {
fn default() -> Self {
Self {
entry_type: PropertyLookupCacheEntryType::Empty,
property_offset: 0,
shape_dictionary_generation: 0,
shape: None,
prototype: None,
prototype_chain_validity: None,
new_shape: None,
}
}
}
/// A lookup with the name of the property it looked up, which the entry keeps alive so that its identity stays
/// unique. The interpreter looks up own properties in entries itself (see KeyedPropertyLookupCacheEntryLayout), which
/// are 64 bytes so that it finds them by shifting the hash.
#[derive(Default)]
#[repr(C, align(64))]
pub struct KeyedPropertyLookupCacheEntry {
lookup: KeyedPropertyLookup,
property_name: Option<Utf16FlyString>,
}
const _: () = assert!(size_of::<KeyedPropertyLookupCacheEntry>() == 64);
// SAFETY: Entries only live in the VM's keyed property lookup caches, which the VM sweeps after each collection (see
// Vm::remove_dead_cells_from_property_lookup_caches()).
unsafe impl SweptAfterCollection for KeyedPropertyLookupCacheEntry {}
// NB: The interpreter reads entries with the layout of KeyedPropertyLookupCacheEntryLayout, and finds them the way
// entry_index_for() does.
const _: () = assert!(
KEYED_PROPERTY_LOOKUP_CACHE_INDEX_BITS
== crate::layout::property_lookup_cache::KEYED_PROPERTY_LOOKUP_CACHE_INTERPRETER_INDEX_BITS
);
const _: () = assert!(
MEGAMORPHIC_HASH_MULTIPLIER
== crate::layout::property_lookup_cache::KEYED_PROPERTY_LOOKUP_CACHE_INTERPRETER_HASH_MULTIPLIER
);
const _: () = {
use core::mem::offset_of;
type Layout = KeyedPropertyLookupCacheEntryLayout;
let lookup = offset_of!(KeyedPropertyLookupCacheEntry, lookup);
assert!(size_of::<KeyedPropertyLookupCacheEntry>() == size_of::<Layout>());
assert!(lookup + offset_of!(KeyedPropertyLookup, entry_type) == offset_of!(Layout, entry_type));
assert!(lookup + offset_of!(KeyedPropertyLookup, property_offset) == offset_of!(Layout, property_offset));
assert!(
lookup + offset_of!(KeyedPropertyLookup, shape_dictionary_generation)
== offset_of!(Layout, shape_dictionary_generation)
);
assert!(lookup + offset_of!(KeyedPropertyLookup, shape) == offset_of!(Layout, shape));
assert!(offset_of!(KeyedPropertyLookupCacheEntry, property_name) == offset_of!(Layout, property_name));
};
// NB: The interpreter compares the name of an entry with the identity of a string, a word.
const _: () = assert!(size_of::<Option<Utf16FlyString>>() == size_of::<u64>());
/// Where JIT code finds the parts of the VM's keyed property lookup cache it reads.
pub struct KeyedPropertyLookupCacheLayout {
pub entries: u64,
pub index_bits: u32,
pub entry_size: u32,
pub entry_type: u32,
pub property_offset: u32,
pub shape_dictionary_generation: u32,
pub shape: u32,
pub property_name: u32,
pub prototype: u32,
pub prototype_chain_validity: u32,
pub new_shape: u32,
}
/// The VM-wide cache of string-keyed GetByValue lookups. Lookups are copied out, so that no entry is borrowed while
/// the lookup it caches runs.
pub struct KeyedPropertyLookupCache {
entries: RefCell<Box<[KeyedPropertyLookupCacheEntry]>>,
}
impl KeyedPropertyLookupCache {
pub fn new() -> Self {
Self {
entries: RefCell::new(
(0..KEYED_PROPERTY_LOOKUP_CACHE_ENTRY_COUNT)
.map(|_| KeyedPropertyLookupCacheEntry::default())
.collect(),
),
}
}
/// The index of the one entry that may hold the lookup of `property_name` on `shape`: the top bits of the
/// Fibonacci hash of the low 32 bits of the shape's address and the name's identity, which the interpreter computes
/// the same way. Fly strings are interned, so the identity of the name stands in for the hash of its contents.
pub fn entry_index_for(shape: Gc<Shape>, property_name: &Utf16FlyString) -> usize {
Self::entry_index_for_name_identity(shape, property_name.raw_identity())
}
fn entry_index_for_name_identity(shape: Gc<Shape>, name_identity: usize) -> usize {
let hash = (shape.as_ptr().addr() as u32) ^ (name_identity as u32);
(hash.wrapping_mul(MEGAMORPHIC_HASH_MULTIPLIER) >> (32 - KEYED_PROPERTY_LOOKUP_CACHE_INDEX_BITS)) as usize
}
/// Where JIT code finds the entries and their parts. The entries stay where they are for as long as the VM lives.
pub fn jit_layout(&self) -> KeyedPropertyLookupCacheLayout {
use core::mem::offset_of;
let lookup = offset_of!(KeyedPropertyLookupCacheEntry, lookup);
KeyedPropertyLookupCacheLayout {
entries: self.entries.borrow().as_ptr() as u64,
index_bits: KEYED_PROPERTY_LOOKUP_CACHE_INDEX_BITS,
entry_size: size_of::<KeyedPropertyLookupCacheEntry>() as u32,
entry_type: (lookup + offset_of!(KeyedPropertyLookup, entry_type)) as u32,
property_offset: (lookup + offset_of!(KeyedPropertyLookup, property_offset)) as u32,
shape_dictionary_generation: (lookup + offset_of!(KeyedPropertyLookup, shape_dictionary_generation)) as u32,
shape: (lookup + offset_of!(KeyedPropertyLookup, shape)) as u32,
property_name: offset_of!(KeyedPropertyLookupCacheEntry, property_name) as u32,
prototype: (lookup + offset_of!(KeyedPropertyLookup, prototype)) as u32,
prototype_chain_validity: (lookup + offset_of!(KeyedPropertyLookup, prototype_chain_validity)) as u32,
new_shape: (lookup + offset_of!(KeyedPropertyLookup, new_shape)) as u32,
}
}
/// The entries, for the interpreter, which looks up own data properties in them (see
/// KeyedPropertyLookupCacheEntryLayout). They stay where they are for as long as the VM lives.
pub fn entries_for_interpreter(&self) -> *const KeyedPropertyLookupCacheEntryLayout {
self.entries.borrow().as_ptr().cast()
}
/// The lookup entry `index` remembers for `property_name` on `shape`, if it is for them.
pub fn lookup(
&self,
index: usize,
shape: Gc<Shape>,
property_name: &Utf16FlyString,
) -> Option<KeyedPropertyLookup> {
let entries = self.entries.borrow();
let entry = &entries[index];
(entry.lookup.shape == Some(shape) && entry.property_name.as_ref() == Some(property_name))
.then_some(entry.lookup)
}
/// The entry for `shape` and the name whose identity (see Utf16FlyString::raw_identity()) is `name_identity`, as
/// JIT code finds it.
pub fn lookup_by_name_identity(&self, shape: Gc<Shape>, name_identity: usize) -> Option<KeyedPropertyLookup> {
let entries = self.entries.borrow();
let entry = &entries[Self::entry_index_for_name_identity(shape, name_identity)];
(entry.lookup.shape == Some(shape)
&& entry
.property_name
.as_ref()
.is_some_and(|name| name.raw_identity() == name_identity))
.then_some(entry.lookup)
}
pub fn set_entry(&self, index: usize, lookup: KeyedPropertyLookup, property_name: &Utf16FlyString) {
let mut entries = self.entries.borrow_mut();
let entry = &mut entries[index];
entry.lookup = lookup;
if entry.property_name.as_ref() != Some(property_name) {
entry.property_name = Some(property_name.clone());
}
}
/// Forgets the entries with a cell that died in this collection.
pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {
for entry in self.entries.borrow_mut().iter_mut() {
let lookup = &entry.lookup;
// NB: Entries of the keyed property store cache for puts it does not make have a shape but no type.
if lookup.shape.is_some_and(|shape| sweep.is_dead_or_moving(shape))
|| lookup
.prototype
.is_some_and(|prototype| sweep.is_dead_or_moving(prototype))
|| lookup
.prototype_chain_validity
.is_some_and(|validity| sweep.is_dead_or_moving(validity))
|| lookup.new_shape.is_some_and(|shape| sweep.is_dead_or_moving(shape))
{
*entry = KeyedPropertyLookupCacheEntry::default();
}
}
}
}
impl Default for KeyedPropertyLookupCache {
fn default() -> Self {
Self::new()
}
}
// https://tc39.es/ecma262/#sec-gettemplateobject
// Template objects are cached at the call site.
#[repr(C)]
#[derive(Trace)]
pub struct TemplateObjectCache {
header: CellHeader,
cached_template_object: Cell<Option<Gc<Array>>>,
}
define_cell!(TemplateObjectCache, Other);
impl TemplateObjectCache {
pub fn create(vm: &Vm) -> Gc<TemplateObjectCache> {
vm.heap().allocate(|_| TemplateObjectCache {
header: CellHeader::for_class(Self::CLASS),
cached_template_object: Cell::new(None),
})
}
pub fn cached_template_object(&self) -> Option<Gc<Array>> {
self.cached_template_object.get()
}
pub fn set_cached_template_object(&self, template_object: Gc<Array>) {
self.cached_template_object.set(Some(template_object));
}
}
// Cache for object literal shapes.
// When an object literal like {a: 1, b: 2} is instantiated, we cache the final shape
// so that subsequent instantiations can allocate the object with the correct shape directly,
// avoiding repeated shape transitions.
// We also cache the property offsets so that subsequent property writes can bypass
// shape lookups and write directly to the correct storage slot.
/// The shape is not kept alive; the VM's sweep callback forgets it when it dies.
#[derive(Default)]
pub struct ObjectShapeCache {
pub shape: Cell<Option<Gc<Shape>>>,
pub property_offsets: RefCell<Vec<u32>>,
}
/// The parts of an ObjectPropertyIteratorCacheData the interpreter does not read.
#[derive(Default, Trace)]
pub struct ObjectPropertyIteratorCacheDataStorage {
properties: Box<[PropertyKey]>,
}
define_cell!(ObjectPropertyIteratorCacheData, Other, finalize: finalize);
const _: () = assert!(size_of::<ObjectPropertyIteratorCacheData>() == 72);
// SAFETY: Visits the shape, the validity, the materialized key values and the keys.
unsafe impl Trace for ObjectPropertyIteratorCacheData {
fn trace(&self, visitor: &mut Visitor) {
self.shape.trace(visitor);
self.prototype_chain_validity.trace(visitor);
// SAFETY: The values are written once, when the cell is made, and only its finalizer frees them.
unsafe { self.property_values.trace_owned(visitor) };
self.storage.trace(visitor);
}
}
impl Finalize for ObjectPropertyIteratorCacheData {
fn finalize(&self) {
self.property_values.clear();
}
}
impl ObjectPropertyIteratorCacheData {
/// Fast-path snapshot: a cached, revalidatable key list for one shape, shared by every site that enumerates it.
pub fn create_with_fast_path(
vm: &Vm,
properties: &MarkedVec<'_, PropertyKey>,
fast_path: ObjectPropertyIteratorFastPath,
indexed_property_count: u32,
receiver_has_magical_length_property: bool,
shape: Gc<Shape>,
prototype_chain_validity: Option<Gc<WatchpointSet>>,
) -> Gc<ObjectPropertyIteratorCacheData> {
let cache_data = vm.heap().allocate(|_| Self {
header: CellHeader::for_class(Self::CLASS),
shape_is_dictionary: Cell::new(shape.is_dictionary()),
fast_path: Cell::new(fast_path),
receiver_has_magical_length: Cell::new(receiver_has_magical_length_property),
indexed_property_count: Cell::new(indexed_property_count),
shape_dictionary_generation: Cell::new(shape.dictionary_generation()),
shape: NullableMember::new(Some(shape)),
prototype_chain_validity: NullableMember::new(prototype_chain_validity),
property_values: InterpreterBuffer::new(),
property_offsets: Self::property_offsets(&shape, properties, indexed_property_count),
storage: ObjectPropertyIteratorCacheDataStorage {
properties: properties.to_vec().into_boxed_slice(),
},
});
// The iterator fast path returns JS Values directly, so materialize the
// cached key list once up front instead of converting PropertyKeys during
// every ObjectPropertyIteratorNext.
cache_data
.property_values
.ensure_capacity(indexed_property_count as usize + properties.len());
for index in 0..indexed_property_count {
let value = PropertyKey::from(index).to_value(vm);
cache_data.property_values.append(value);
}
for index in 0..properties.len() {
let value = properties.get(index).expect("the index is in bounds").to_value(vm);
cache_data.property_values.append(value);
}
cache_data
}
/// The offsets of the own properties of objects of `shape` that the keys name, after the indices (see
/// `ObjectPropertyIteratorCacheData::property_offsets`).
fn property_offsets(
shape: &Shape,
properties: &MarkedVec<'_, PropertyKey>,
indexed_property_count: u32,
) -> ThinSlice<u32> {
if shape.is_dictionary() {
return ThinSlice::empty();
}
let indices = core::iter::repeat_n(u32::MAX, indexed_property_count as usize);
let named = (0..properties.len()).map(|index| {
let key = properties.get(index).expect("the index is in bounds");
shape.lookup(&key).map_or(u32::MAX, |metadata| metadata.offset)
});
indices.chain(named).collect()
}
/// Slow-path snapshot: a plain key list with no fast path. Enumeration filters deleted keys with has_property() at
/// each step, so there is no shape to revalidate against.
pub fn create(vm: &Vm, properties: &MarkedVec<'_, PropertyKey>) -> Gc<ObjectPropertyIteratorCacheData> {
// The slow path keeps only the key list. Values are converted lazily during enumeration,
// because deleted keys have to be filtered with has_property() at each step anyway.
vm.heap().allocate(|_| Self {
header: CellHeader::for_class(Self::CLASS),
shape_is_dictionary: Cell::new(false),
fast_path: Cell::new(ObjectPropertyIteratorFastPath::None),
receiver_has_magical_length: Cell::new(false),
indexed_property_count: Cell::new(0),
shape_dictionary_generation: Cell::new(0),
shape: NullableMember::null(),
prototype_chain_validity: NullableMember::null(),
property_values: InterpreterBuffer::new(),
property_offsets: ThinSlice::empty(),
storage: ObjectPropertyIteratorCacheDataStorage {
properties: properties.to_vec().into_boxed_slice(),
},
})
}
pub fn property_count(&self) -> usize {
self.storage.properties.len()
}
pub fn property(&self, index: usize) -> PropertyKey {
self.storage.properties[index].clone()
}
pub fn fast_path(&self) -> ObjectPropertyIteratorFastPath {
self.fast_path.get()
}
pub fn indexed_property_count(&self) -> u32 {
self.indexed_property_count.get()
}
pub fn receiver_has_magical_length_property(&self) -> bool {
self.receiver_has_magical_length.get()
}
pub fn shape_key(&self) -> Option<ShapeKey> {
self.shape.get().map(|shape| ShapeKey {
shape,
dictionary_generation: self.shape_dictionary_generation.get(),
})
}
pub fn prototype_chain_validity(&self) -> Option<Gc<WatchpointSet>> {
self.prototype_chain_validity.get()
}
/// The key values the interpreter's fast path hands out, one per indexed and named key.
pub fn property_value(&self, index: usize) -> Value {
self.property_values.get(index)
}
pub fn property_value_count(&self) -> usize {
self.property_values.size()
}
}
/// The parts of an executable that few executables need.
#[derive(Default)]
struct ExecutableRareData {
/// The global variable caches of the dynamic binding accesses that found their binding in the global environment,
/// indexed like the environment coordinate caches. Made when the first such access needs one.
dynamic_global_variable_caches: OnceCell<Box<[GlobalVariableCache]>>,
/// The breakpoints of the debugger at the offsets of the instructions it pauses before.
debugger_breakpoint_sites: RefCell<HashMap<u32, DebuggerBreakpointSite, foldhash::fast::RandomState>>,
template_object_caches: ThinSlice<Gc<TemplateObjectCache>>,
object_property_iterator_caches: ThinSlice<ObjectPropertyIteratorCache>,
class_blueprints: ThinSlice<ClassBlueprint>,
environment_shape_caches: ThinSlice<NullableMember<EnvironmentShape>>,
/// Whether LIBJS_JIT=dump-feedback printed the executable's feedback already.
has_dumped_feedback: Cell<bool>,
}
/// A unit of bytecode: a script, a module, a function body or an eval, with what the interpreter needs to run it.
#[repr(C)]
pub struct Executable {
pub head: ExecutableHead,
/// What this executable runs, which other executables of the same code share.
code: Arc<ExecutableData>,
object_shape_caches: BlockSlice<ObjectShapeCache>,
/// What the interpreter observed running the bytecode, for the optimizing JIT. Only executables that left the
/// plain tier collect feedback, so it is made when the executable first does, and the part that only the profiling
/// tier collects when the executable gets there.
feedback: OnceCell<Box<ExecutableFeedback>>,
/// The executable's JIT code and what its exits taught the JIT. Made when the JIT first looks at the executable.
jit: OnceCell<Box<ExecutableJitState>>,
rare_data: OnceCell<Box<ExecutableRareData>>,
/// Which interpreter handlers the executable's frames run with, see `head.dispatch_table_index`.
interpreter_tier: Cell<InterpreterTier>,
/// The property keys, made once, since turning a string into a property key checks whether it is an array index.
property_keys: BlockSlice<PropertyKey>,
/// The functions the bytecode creates, which NewFunction and NewClass refer to by index.
shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,
/// The name of the function the executable is the body of, given when the function is first compiled. Empty for
/// other code.
name: FlyStringSlot,
pub source_code: Option<Rc<SourceCode>>,
/// The memory of the slices above, which get dropped before it.
tables: SliceBlock,
}
// NB: Every function that was called has these bytes.
const _: () = assert!(size_of::<Executable>() == 200);
define_cell!(Executable, Other, external_memory_size: external_memory_size);
// Executable::external_memory_size(): the tables of the executable, and its code while nothing else holds the code.
// Code that something else holds, like a program that gets linked again, is that holder's memory. A property lookup
// cache makes its data once its access runs, so each one counts as if it had the one entry that most caches that run
// have. The cache of the slot that the sites past the last one share has no data of its own.
impl ExternalMemorySize for Executable {
fn external_memory_size(&self) -> usize {
let code_size = if Arc::strong_count(&self.code) == 1 {
self.code.memory_size()
} else {
0
};
let cache_data_size =
self.head.property_lookup_caches.len().min(UNCACHED_SITE as usize) * size_of::<MonomorphicData>();
code_size + self.tables_memory_size() + cache_data_size + size_of_val(self.call_caches())
}
}
/// Executable::LocalVariableScopeRange: the part of the source code in which a local variable is in scope.
#[derive(Clone, Copy)]
pub struct LocalVariableScopeRange {
pub start: Position,
pub end: Position,
}
#[derive(Default)]
struct DebuggerBreakpointSite {
breakpoint_ids: Vec<BreakpointID>,
}
const _: () = assert!(core::mem::offset_of!(Executable, head) == 0);
impl CallCache {
/// Whether the callee or the executable of the entry died in this collection, or moves in it.
fn has_dead_cell(&self, sweep: &Sweep<'_>) -> bool {
let callee = self.callee.get();
if callee == CALL_CACHE_EMPTY_CALLEE {
return false;
}
if sweep.is_dead_or_moving(Value::from_bits(callee).as_cell()) {
return true;
}
let target = self.target.get();
if target & CALL_CACHE_TARGET_TAG_MASK != CALL_CACHE_TARGET_EXECUTABLE {
return false;
}
let executable = NonNull::new(core::ptr::with_exposed_provenance_mut::<ExecutableHead>(
target as usize,
))
.expect("a linked call cache has an executable");
// SAFETY: The entry was linked to a live executable, which stays intact until the sweep after it died.
sweep.is_dead_or_moving(Executable::from_head(unsafe { Gc::from_non_null(executable) }))
}
}
impl Executable {
pub fn property_lookup_cache(&self, index: usize) -> &PropertyLookupCache {
&self.head.property_lookup_caches[index]
}
pub fn template_object_cache(&self, index: u32) -> Gc<TemplateObjectCache> {
self.template_object_caches()[index as usize]
}
pub fn property_lookup_caches(&self) -> &[PropertyLookupCache] {
&self.head.property_lookup_caches
}
pub fn global_variable_caches(&self) -> &[GlobalVariableCache] {
&self.head.global_variable_caches
}
pub fn object_shape_caches(&self) -> &[ObjectShapeCache] {
&self.object_shape_caches
}
pub fn object_shape_cache(&self, index: u32) -> &ObjectShapeCache {
&self.object_shape_caches[index as usize]
}
pub fn object_property_iterator_cache(&self, index: u32) -> &ObjectPropertyIteratorCache {
&self.object_property_iterator_caches()[index as usize]
}
/// The identifier that `index`, a field of an instruction of this executable, refers to.
pub fn get_identifier(&self, index: &IdentifierTableIndex) -> &Utf16FlyString {
self.identifier(index.index_in(self.bytecode()))
}
pub fn identifier(&self, index: usize) -> &Utf16FlyString {
&self.code.identifier_table[index]
}
/// The property key that `index`, a field of an instruction of this executable, refers to.
pub fn get_property_key(&self, index: &PropertyKeyTableIndex) -> &PropertyKey {
self.property_key(index.index_in(self.bytecode()))
}
pub fn property_key(&self, index: usize) -> &PropertyKey {
&self.property_keys[index]
}
pub fn property_keys(&self) -> &[PropertyKey] {
&self.property_keys
}
/// The string that `index`, a field of an instruction of this executable, refers to.
pub fn get_string(&self, index: &StringTableIndex) -> &Utf16FlyString {
&self.code.string_table()[index.index_in(self.bytecode())]
}
/// Forgets the cells the inline caches remember that died in this collection.
pub fn remove_dead_cells(&self, sweep: &Sweep<'_>) {
for cache in &self.head.property_lookup_caches {
cache.remove_dead_entries(sweep);
}
let dynamic_global_variable_caches = self
.rare_data
.get()
.and_then(|rare_data| rare_data.dynamic_global_variable_caches.get());
for cache in self
.head
.global_variable_caches
.iter()
.chain(dynamic_global_variable_caches.into_iter().flatten())
{
cache.entry.clear_if_it_has_a_dead_cell(sweep);
}
for cache in self.call_caches() {
if cache.has_dead_cell(sweep) {
cache.clear();
}
}
for cache in &self.object_shape_caches {
if cache.shape.get().is_some_and(|shape| sweep.is_dead_or_moving(shape)) {
cache.shape.set(None);
}
}
if let Some(feedback) = self.feedback() {
feedback.remove_dead_cells(sweep);
}
}
/// An executable of `code`, with empty caches. `code` is the only thing that keeps the bytecode alive, and it lives
/// for as long as the executable, which is what makes the address of the bytecode good to hand out.
fn new_with_code(
code: Arc<ExecutableData>,
mut tables: SliceBlockBuilder,
constants: BlockSlice<Value>,
property_keys: BlockSlice<PropertyKey>,
shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,
_defer_gc: &DeferGc<'_>,
) -> Self {
let cache_counts = &code.cache_counts();
let property_lookup_caches = tables.slice((0..cache_counts.property_lookup).map(|index| {
if index == UNCACHED_SITE {
PropertyLookupCache::new_uncacheable()
} else {
PropertyLookupCache::new()
}
}));
let global_variable_caches =
tables.slice((0..cache_counts.global_variable).map(|_| GlobalVariableCache::default()));
let environment_coordinate_caches =
tables.slice((0..cache_counts.environment_coordinate).map(|_| Cell::new(EnvironmentCoordinate::invalid())));
let number_of_locals = u32::try_from(code.local_variable_metadata.len()).expect("local count fits in u32");
let registers_and_locals_count = code.number_of_registers + number_of_locals;
let constant_count = u32::try_from(constants.len()).expect("constant count fits in u32");
let head = ExecutableHead {
registers_and_locals_count: Cell::new(registers_and_locals_count),
registers_and_locals_and_constants_count: Cell::new(registers_and_locals_count + constant_count),
header: CellHeaderTail::for_class(Self::CLASS),
// The VM picks the table when it registers the executable.
dispatch_table_index: Cell::new(InterpreterTier::Plain as u8),
tier_up_budget: Cell::new(i32::MAX),
bytecode_data: Cell::new(code.bytecode.as_ptr()),
jit_entry_slot: Cell::new(0),
jit_compile_state: Cell::new(0),
idle_collection_count: Cell::new(0),
feedback: ExecutableFeedbackHead::empty(),
constants,
property_lookup_caches,
global_variable_caches,
// The interpreter only reads the caches, which slow paths update through their cells.
environment_coordinate_caches,
call_caches: Cell::new(core::ptr::null()),
call_metadata: Cell::new(0),
};
let object_shape_caches = tables.slice((0..cache_counts.object_shape).map(|_| ObjectShapeCache::default()));
Self {
head,
object_shape_caches,
feedback: OnceCell::new(),
jit: OnceCell::new(),
rare_data: OnceCell::new(),
interpreter_tier: Cell::new(InterpreterTier::Plain),
property_keys,
shared_function_data,
name: FlyStringSlot::new(None),
source_code: None,
tables: tables.finish(),
code,
}
}
/// Links what the frontend compiled from `source_code` into a new executable, with the functions and classes it
/// declares and caches of its own. While something else holds `data`, it stays as it is and can be linked again,
/// into any realm. Without another holder nothing can link it again, so what only linking reads goes away.
pub fn create_with_source_code(
vm: &Vm,
data: Arc<ExecutableData>,
source_code: Option<&Rc<SourceCode>>,
) -> Gc<Executable> {
Self::create_with_flushed_code(vm, data, source_code, None)
}
/// create_with_source_code() for the code of a function whose last executable was flushed, which takes over what
/// that executable left (see `bytecode::flushing`).
pub fn create_with_flushed_code(
vm: &Vm,
mut data: Arc<ExecutableData>,
source_code: Option<&Rc<SourceCode>>,
flushed_code: Option<&FlushedCode>,
) -> Gc<Executable> {
// NB: The code compiles the same every time, so it creates as many functions and has as many template objects.
let flushed_code = flushed_code.filter(|flushed_code| {
let fits = flushed_code.shared_function_data.len() == data.shared_function_data.len()
&& flushed_code.template_object_caches.len() == data.cache_counts().template_object as usize;
debug_assert!(fits, "flushed code compiles to the same functions and template objects");
fits
});
let executable = DeferGc::scope(vm, |_| {
// SAFETY: The slices and the block end up in the executable, which drops the slices first.
let mut tables = unsafe { SliceBlock::builder(Self::size_of_tables(&data)) };
let is_strict = data.is_strict;
let shared_function_data = if let Some(flushed_code) = flushed_code {
tables.slice(flushed_code.shared_function_data.iter().copied())
} else {
match Arc::get_mut(&mut data) {
Some(code) => tables.slice(code.shared_function_data.take_elements().map(|pending| {
SharedFunctionInstanceData::create_from_owned_pending_shared_function_data(
vm,
pending,
is_strict,
source_code,
)
})),
None => tables.slice(data.shared_function_data.iter().map(|pending| {
SharedFunctionInstanceData::create_from_pending_shared_function_data(
vm,
pending,
is_strict,
source_code,
)
})),
}
};
let template_object_caches = flushed_code.map(|flushed_code| &flushed_code.template_object_caches[..]);
vm.heap().allocate(|defer_gc| {
Self::build(
vm,
data,
tables,
shared_function_data,
template_object_caches,
source_code,
defer_gc,
)
})
});
vm.register_executable(executable);
vm.heap()
.did_allocate_external_memory(executable.external_memory_size());
if let Some(debugger) = vm.debugger() {
debugger.register_executable(vm, executable);
}
executable
}
/// The bytes of the tables in `tables`.
fn tables_memory_size(&self) -> usize {
size_of_val(&*self.head.constants)
+ size_of_val(&*self.head.property_lookup_caches)
+ size_of_val(&*self.head.global_variable_caches)
+ size_of_val(&*self.head.environment_coordinate_caches)
+ size_of_val(&*self.object_shape_caches)
+ size_of_val(&*self.property_keys)
+ size_of_val(&*self.shared_function_data)
}
/// The bytes of the tables that an executable of `code` has from the start.
fn size_of_tables(code: &ExecutableData) -> usize {
let cache_counts = &code.cache_counts();
SliceBlock::room_for::<Gc<SharedFunctionInstanceData>>(code.shared_function_data.len())
+ SliceBlock::room_for::<PropertyKey>(code.property_key_table.len())
+ SliceBlock::room_for::<Value>(code.constants.len())
+ SliceBlock::room_for::<PropertyLookupCache>(cache_counts.property_lookup as usize)
+ SliceBlock::room_for::<GlobalVariableCache>(cache_counts.global_variable as usize)
+ SliceBlock::room_for::<Cell<EnvironmentCoordinate>>(cache_counts.environment_coordinate as usize)
+ SliceBlock::room_for::<ObjectShapeCache>(cache_counts.object_shape as usize)
}
fn build(
vm: &Vm,
mut data: Arc<ExecutableData>,
mut tables: SliceBlockBuilder,
shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,
template_object_caches: Option<&[Gc<TemplateObjectCache>]>,
source_code: Option<&Rc<SourceCode>>,
defer_gc: &DeferGc<'_>,
) -> Executable {
let class_blueprints: ThinSlice<ClassBlueprint> = data
.class_blueprints
.iter()
.map(|blueprint| ClassBlueprint::create(vm, blueprint, source_code, defer_gc))
.collect();
let property_keys = match Arc::get_mut(&mut data) {
Some(code) => tables.slice(code.property_key_table.take_elements().map(PropertyKey::from)),
None => tables.slice(data.property_key_table.iter().cloned().map(PropertyKey::from)),
};
let constants = tables.slice(data.constants.iter().map(|constant| constant_value(vm, constant)));
let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = match template_object_caches {
Some(caches) => caches.iter().copied().collect(),
None => (0..data.cache_counts().template_object)
.map(|_| TemplateObjectCache::create(vm))
.collect(),
};
let object_property_iterator_caches = data.cache_counts().object_property_iterator;
let environment_shape_caches = data.cache_counts().environment_shape;
let mut executable =
Self::new_with_code(data, tables, constants, property_keys, shared_function_data, defer_gc);
if let Some(code) = Arc::get_mut(&mut executable.code) {
code.release_link_inputs();
}
if !class_blueprints.is_empty() {
executable.rare_data_mut().class_blueprints = class_blueprints;
}
if !template_object_caches.is_empty() {
executable.rare_data_mut().template_object_caches = template_object_caches;
}
if environment_shape_caches != 0 {
executable.rare_data_mut().environment_shape_caches =
(0..environment_shape_caches).map(|_| NullableMember::null()).collect();
}
if object_property_iterator_caches != 0 {
executable.rare_data_mut().object_property_iterator_caches = (0..object_property_iterator_caches)
.map(|_| ObjectPropertyIteratorCache { data: Cell::new(None) })
.collect();
}
executable.source_code = source_code.cloned();
executable
}
pub fn head(executable: Gc<Executable>) -> Gc<ExecutableHead> {
// SAFETY: An Executable starts with its head.
unsafe { Gc::from_non_null(executable.as_non_null().cast()) }
}
pub fn from_head(head: Gc<ExecutableHead>) -> Gc<Executable> {
// SAFETY: Only executables have an ExecutableHead.
unsafe { Gc::from_non_null(head.as_non_null().cast()) }
}
pub fn shared_function_data(&self, index: u32) -> Gc<SharedFunctionInstanceData> {
self.shared_function_data[index as usize]
}
pub fn shared_function_data_count(&self) -> usize {
self.shared_function_data.len()
}
/// The shared data of the functions the bytecode creates.
pub fn shared_function_data_slice(&self) -> &[Gc<SharedFunctionInstanceData>] {
&self.shared_function_data
}
/// The caches of the template objects of the bytecode's template literals.
pub fn template_object_caches_slice(&self) -> &[Gc<TemplateObjectCache>] {
self.template_object_caches()
}
/// Visits what outlives a flush of the executable, for its shared data while it leaves the executable unvisited
/// (see `bytecode::flushing`).
pub fn trace_what_outlives_a_flush(&self, visitor: &mut Visitor) {
self.shared_function_data.trace(visitor);
self.template_object_caches().trace(visitor);
}
pub fn class_blueprint(&self, index: u32) -> &ClassBlueprint {
&self.class_blueprints()[index as usize]
}
/// The handler whose range holds the instruction at `offset`.
pub fn exception_handlers_for_offset(&self, offset: u32) -> Option<&ExceptionHandler> {
self.exception_handlers()
.binary_search_by(|handler| {
if offset < handler.start_offset {
core::cmp::Ordering::Greater
} else if offset >= handler.end_offset {
core::cmp::Ordering::Less
} else {
core::cmp::Ordering::Equal
}
})
.ok()
.map(|index| &self.exception_handlers()[index])
}
pub fn source_range_at(&self, offset: u32) -> Option<SourceRange> {
if offset as usize >= self.bytecode().len() {
return None;
}
let entry = self.source_map().entry_at(offset)?;
let (line, column) = if entry.source_offset == SourceOffset::NONE {
(0, 0)
} else {
let position = self.code.position_source.lines.position(entry.source_offset.0);
(position.line, position.column)
};
Some(SourceRange {
code: self
.source_code
.clone()
.unwrap_or_else(|| SourceCode::create(ak::Utf16String::default(), ak::Utf16String::default())),
start: Position { line, column },
})
}
/// The source around the instruction at `offset`, and where in that it is.
fn source_around(&self, offset: u32) -> Option<(Vec<u16>, usize)> {
const LONGEST_TEXT: usize = 1024;
let positions = &self.code.position_source;
let source_offset = self.source_map().entry_at(offset)?.source_offset;
if source_offset == SourceOffset::NONE {
return None;
}
let source_offset = source_offset.0 as usize;
let source = positions.source.get();
let view = crate::utf16::Utf16View::of_string(&source);
let start = source_offset.saturating_sub(LONGEST_TEXT);
let end = (source_offset + LONGEST_TEXT).min(view.length_in_code_units());
let units = view.substring_view(start, end - start).code_units().collect();
Some((units, source_offset - start))
}
/// The text of what the call or `new` at `offset` calls, from the source.
pub fn callee_text_at(&self, offset: u32) -> Option<ak::Utf16FlyString> {
let (units, at) = self.source_around(offset)?;
let text = crate::bytecode::reference_text::callee_text(&units, at)?;
Some(ak::Utf16FlyString::from_utf16(&text))
}
/// The text of the base of the member access at `offset`, from the source.
pub fn base_text_at(&self, offset: u32) -> Option<ak::Utf16FlyString> {
let (units, at) = self.source_around(offset)?;
let text = crate::bytecode::reference_text::base_text(&units, at)?;
Some(ak::Utf16FlyString::from_utf16(&text))
}
/// The source range at `program_counter`, or an empty one if the source map has none.
pub fn get_source_range(&self, program_counter: u32) -> SourceRange {
self.source_range_at(program_counter).unwrap_or_else(|| SourceRange {
code: SourceCode::create(ak::Utf16String::default(), ak::Utf16String::default()),
start: Position::default(),
})
}
fn template_object_caches(&self) -> &[Gc<TemplateObjectCache>] {
self.rare_data
.get()
.map_or(&[], |rare_data| &rare_data.template_object_caches)
}
fn object_property_iterator_caches(&self) -> &[ObjectPropertyIteratorCache] {
self.rare_data
.get()
.map_or(&[], |rare_data| &rare_data.object_property_iterator_caches)
}
fn class_blueprints(&self) -> &[ClassBlueprint] {
self.rare_data
.get()
.map_or(&[], |rare_data| &rare_data.class_blueprints)
}
/// What this executable runs. Executables that link the same code have the same one.
/// This is not something to link again, as the last holder of code has nothing left to link it from.
pub fn code(&self) -> &Arc<ExecutableData> {
&self.code
}
pub fn identifier_table(&self) -> &[Utf16FlyString] {
&self.code.identifier_table
}
pub fn string_table(&self) -> &[Utf16FlyString] {
self.code.string_table()
}
pub fn exception_handlers(&self) -> &[ExceptionHandler] {
self.code.exception_handlers()
}
pub fn source_positions(&self) -> impl Iterator<Item = SourceMapEntry> + '_ {
self.code.source_positions()
}
pub fn source_map(&self) -> SourceMapEntries<'_> {
SourceMapEntries::new(&self.code.source_map)
}
pub fn local_variable_metadata(&self) -> &[LocalVariableMetadata] {
&self.code.local_variable_metadata
}
pub fn local_variable_scope_range(&self, index: usize) -> Option<LocalVariableScopeRange> {
let metadata = self.local_variable_metadata()[index];
if metadata.scope_start == SourceOffset::NONE {
return None;
}
let position = |offset: SourceOffset| {
let position = self.code.position_source.lines.position(offset.0);
Position {
line: position.line,
column: position.column,
}
};
Some(LocalVariableScopeRange {
start: position(metadata.scope_start),
end: position(metadata.scope_end),
})
}
pub fn local_variable_names(&self) -> &[Utf16FlyString] {
&self.code.variable_names[..self.local_variable_metadata().len()]
}
pub fn argument_variable_names(&self) -> &[Utf16FlyString] {
&self.code.variable_names[self.local_variable_metadata().len()..]
}
/// Whether the code at the bytecode offset `pc` is strict.
pub fn is_strict_at(&self, pc: u32) -> bool {
if self.is_strict_mode() {
return true;
}
let ranges = self.code.strict_ranges();
let index = ranges.partition_point(|range| range.end_offset <= pc);
ranges.get(index).is_some_and(|range| range.start_offset <= pc)
}
/// The index of the length in the property key table, if it is there.
pub fn length_identifier(&self) -> Option<usize> {
self.code.length_identifier().map(|index| index.0 as usize)
}
pub fn is_strict_mode(&self) -> bool {
self.code.is_strict
}
pub fn number_of_registers(&self) -> u32 {
self.code.number_of_registers
}
pub fn number_of_arguments(&self) -> u32 {
self.code.number_of_arguments
}
fn rare_data_mut(&mut self) -> &mut ExecutableRareData {
self.rare_data.get_or_init(Box::default);
self.rare_data.get_mut().expect("the rare data was just made")
}
fn rare_data(&self) -> &ExecutableRareData {
self.rare_data.get_or_init(Box::default)
}
pub fn add_debugger_breakpoint(&self, bytecode_offset: u32, breakpoint_id: BreakpointID) {
let mut sites = self.rare_data().debugger_breakpoint_sites.borrow_mut();
let site = sites.entry(bytecode_offset).or_default();
if !site.breakpoint_ids.contains(&breakpoint_id) {
site.breakpoint_ids.push(breakpoint_id);
}
}
pub fn remove_debugger_breakpoint(&self, breakpoint_id: BreakpointID) {
let Some(rare_data) = self.rare_data.get() else {
return;
};
let mut sites = rare_data.debugger_breakpoint_sites.borrow_mut();
sites.retain(|_, site| {
if let Some(index) = site.breakpoint_ids.iter().position(|&id| id == breakpoint_id) {
site.breakpoint_ids.remove(index);
}
!site.breakpoint_ids.is_empty()
});
if sites.is_empty() {
sites.shrink_to_fit();
}
}
pub fn clear_debugger_breakpoints(&self) {
if let Some(rare_data) = self.rare_data.get() {
*rare_data.debugger_breakpoint_sites.borrow_mut() = HashMap::default();
}
}
pub fn has_debugger_breakpoint_at(&self, bytecode_offset: u32) -> bool {
self.rare_data.get().is_some_and(|rare_data| {
rare_data
.debugger_breakpoint_sites
.borrow()
.contains_key(&bytecode_offset)
})
}
pub fn debugger_breakpoints_at(&self, bytecode_offset: u32) -> Vec<BreakpointID> {
self.rare_data
.get()
.and_then(|rare_data| {
rare_data
.debugger_breakpoint_sites
.borrow()
.get(&bytecode_offset)
.map(|site| site.breakpoint_ids.clone())
})
.unwrap_or_default()
}
pub fn has_debugger_breakpoint(&self, breakpoint_id: BreakpointID) -> bool {
self.rare_data.get().is_some_and(|rare_data| {
rare_data
.debugger_breakpoint_sites
.borrow()
.values()
.any(|site| site.breakpoint_ids.contains(&breakpoint_id))
})
}
pub fn bytecode(&self) -> &[u8] {
&self.code.bytecode
}
/// Whether the code makes private or variable environments, so that its frames keep their own (see
/// `ExecutionContext::keeps_private_environment()` and `ExecutionContext::keeps_variable_environment()`).
pub fn keeps_own_environments(&self) -> bool {
self.bytecode().first() == Some(&(OpCode::EnterWithOwnEnvironments as u8))
}
pub fn constants(&self) -> &[Value] {
&self.head.constants
}
pub fn registers_and_locals_count(&self) -> u32 {
self.head.registers_and_locals_count.get()
}
pub fn global_variable_cache(&self, index: u32) -> &GlobalVariableCache {
&self.head.global_variable_caches[index as usize]
}
pub fn environment_coordinate_cache(&self, index: u32) -> &Cell<EnvironmentCoordinate> {
&self.head.environment_coordinate_caches[index as usize]
}
/// The global variable cache of the dynamic binding access with the environment coordinate cache `index`.
pub fn dynamic_global_variable_cache(&self, index: u32) -> &GlobalVariableCache {
let caches = self.rare_data().dynamic_global_variable_caches.get_or_init(|| {
(0..self.head.environment_coordinate_caches.len())
.map(|_| GlobalVariableCache::default())
.collect()
});
&caches[index as usize]
}
/// The call caches, which are empty until the executable gets its feedback.
pub fn call_caches(&self) -> &[CallCache] {
self.feedback().map_or(&[], ExecutableFeedback::call_caches)
}
fn clear_call_caches(&self) {
for cache in self.call_caches() {
cache.clear();
}
}
pub fn interpreter_tier(&self) -> InterpreterTier {
self.interpreter_tier.get()
}
/// Moves the executable's frames to the handlers of `tier`, the next time the interpreter enters one of them.
pub fn set_interpreter_tier(&self, tier: InterpreterTier) {
match tier {
InterpreterTier::Plain => {}
#[cfg(feature = "jit")]
InterpreterTier::Profiling => {
self.ensure_feedback();
// NB: A call that hits its call cache records no call feedback, as the call that linked the entry did.
// The calls that linked the entries in another tier did not.
self.clear_call_caches();
}
#[cfg(feature = "jit")]
_ => {
self.ensure_feedback_without_value_buckets();
}
}
self.interpreter_tier.set(tier);
self.head.dispatch_table_index.set(tier as u8);
}
/// Gives the executable its feedback without the value buckets, which only the profiling tier writes, if it has
/// none yet, and points the interpreter at it.
fn ensure_feedback_without_value_buckets(&self) -> &ExecutableFeedback {
if let Some(feedback) = self.feedback.get() {
return feedback;
}
let property_lookup_cache_count =
u32::try_from(self.head.property_lookup_caches.len()).expect("property lookup cache indices are 16-bit");
let cache_counts = self.code.cache_counts();
let slot_counts = FeedbackSlotCounts {
arith: cache_counts.arith_feedback,
value: cache_counts.value_feedback,
call: cache_counts.call_feedback,
keyed: cache_counts.keyed_feedback,
};
let feedback = Box::new(ExecutableFeedback::new(slot_counts, property_lookup_cache_count));
if self.feedback.set(feedback).is_err() {
unreachable!("the feedback is made once");
}
let feedback = self.feedback.get().expect("the feedback was just made");
self.head.call_caches.set(feedback.call_caches().as_ptr());
self.point_interpreter_at_feedback(feedback);
feedback
}
/// Gives the executable all its feedback arrays, if it does not have them yet, and points the interpreter at them.
pub fn ensure_feedback(&self) -> &ExecutableFeedback {
let feedback = self.ensure_feedback_without_value_buckets();
if !feedback.has_value_buckets() {
feedback.ensure_value_buckets();
self.point_interpreter_at_feedback(feedback);
}
feedback
}
fn point_interpreter_at_feedback(&self, feedback: &ExecutableFeedback) {
let head = &self.head.feedback;
let [arith, value_buckets, call, keyed] = feedback.array_offsets();
head.arith.set(arith);
head.value_buckets.set(value_buckets);
head.call.set(call);
head.keyed.set(keyed);
}
pub fn has_dumped_feedback(&self) -> bool {
self.rare_data
.get()
.is_some_and(|rare_data| rare_data.has_dumped_feedback.get())
}
pub fn set_has_dumped_feedback(&self) {
self.rare_data().has_dumped_feedback.set(true);
}
/// What the interpreter observed running the bytecode, indexed by the feedback slots of its instructions, if the
/// executable ever left the plain tier.
pub fn feedback(&self) -> Option<&ExecutableFeedback> {
self.feedback.get().map(Box::as_ref)
}
pub fn jit_state(&self) -> &ExecutableJitState {
self.jit.get_or_init(Box::default)
}
fn environment_shape_caches(&self) -> &[NullableMember<EnvironmentShape>] {
self.rare_data
.get()
.map_or(&[], |rare_data| &rare_data.environment_shape_caches)
}
pub fn environment_shape_cache_count(&self) -> u32 {
u32::try_from(self.environment_shape_caches().len()).expect("the cache count fits in u32")
}
pub fn environment_shape_cache(&self, index: u32) -> EnvironmentShapeCache {
assert!((index as usize) < self.environment_shape_caches().len());
EnvironmentShapeCache::Executable(Gc::from_ref(self), index)
}
pub(crate) fn environment_shape_cache_slot(&self, index: u32) -> &NullableMember<EnvironmentShape> {
&self.environment_shape_caches()[index as usize]
}
pub fn name(&self) -> Utf16FlyString {
self.name.get().unwrap_or_default()
}
pub fn set_name(&self, name: Utf16FlyString) {
self.name.set(Some(name));
}
pub fn source_code(&self) -> Option<&Rc<SourceCode>> {
self.source_code.as_ref()
}
/// The operand index of the first local, which follows the registers.
pub fn local_index_base(&self) -> u32 {
self.code.number_of_registers
}
/// The operand index of the first argument, which follows the registers, the locals and the constants.
pub fn argument_index_base(&self) -> u32 {
self.head.registers_and_locals_and_constants_count.get()
}
pub fn dump(&self) {
let mut output = self.dump_to_builder();
// warnln("{}", output.string_view());
output.push(b'\n');
let _ = std::io::stderr().write_all(&output);
}
/// The StringBuilder dump() builds before it writes it to the standard error.
fn dump_to_builder(&self) -> Vec<u8> {
let mut output = Vec::new();
dump_header(&mut output, self);
dump_metadata(&mut output, self);
output.push(b'\n');
dump_bytecode(&mut output, self);
output.push(b'\n');
output
}
}
/// The line and the column that the first position of the code has.
fn first_real_source_position(executable: &Executable) -> Option<(u32, u32)> {
executable
.source_positions()
.map(|entry| (entry.line, entry.column))
.filter(|&position| position != (0, 0))
.min()
}
fn dump_header(output: &mut Vec<u8>, executable: &Executable) {
const WHITE_BOLD: &str = "\x1b[37;1m";
const RESET: &str = "\x1b[0m";
let first_source_position = first_real_source_position(executable);
let mut hash: u32 = 2166136261; // FNV-1a offset basis
let update_hash = |hash: &mut u32, value: u32| {
for i in 0..u32::BITS / 8 {
*hash ^= (value >> (i * 8)) & 0xFF;
*hash = hash.wrapping_mul(16777619);
}
};
let update_hash_with_code_unit = |hash: &mut u32, code_unit: u16| {
*hash ^= u32::from(code_unit) & 0xFF;
*hash = hash.wrapping_mul(16777619);
*hash ^= (u32::from(code_unit) >> 8) & 0xFF;
*hash = hash.wrapping_mul(16777619);
};
let name = executable.name();
let name_view = Utf16View::of_fly_string(&name);
for code_unit in name_view.code_units() {
update_hash_with_code_unit(&mut hash, code_unit);
}
if let Some((line, column)) = first_source_position {
update_hash(&mut hash, line);
update_hash(&mut hash, column);
}
update_hash(
&mut hash,
u32::try_from(executable.bytecode().len()).unwrap_or(u32::MAX),
);
output.extend_from_slice(WHITE_BOLD.as_bytes());
name_view.append_as_wtf8_to(output);
let _ = write!(output, "${hash:08x}{RESET}");
// Show source location if available.
if let Some((line, column)) = first_source_position {
let filename = executable.source_code.as_ref().map_or(Utf16View::EMPTY, |source_code| {
Utf16View::of_string(source_code.filename())
});
if !filename.is_empty() {
// Show just the basename to keep output portable across machines.
let mut last_slash = None;
for (i, code_unit) in filename.code_units().enumerate() {
if code_unit == u16::from(b'/') {
last_slash = Some(i);
}
}
let filename = match last_slash {
Some(last_slash) => {
filename.substring_view(last_slash + 1, filename.length_in_code_units() - last_slash - 1)
}
None => filename,
};
output.push(b' ');
filename.append_as_wtf8_to(output);
let _ = write!(output, ":{line}:{column}");
} else {
let _ = write!(output, " line {line}, column {column}");
}
}
output.push(b'\n');
}
fn dump_metadata(output: &mut Vec<u8>, executable: &Executable) {
const GREEN: &str = "\x1b[32m";
const YELLOW: &str = "\x1b[33m";
const BLUE: &str = "\x1b[34m";
const CYAN: &str = "\x1b[36m";
const RESET: &str = "\x1b[0m";
let _ = writeln!(
output,
" {GREEN}Registers{RESET}: {}",
executable.number_of_registers()
);
let _ = writeln!(output, " {GREEN}Blocks{RESET}: {}", count_basic_blocks(executable));
if !executable.local_variable_names().is_empty() {
let _ = write!(output, " {GREEN}Locals{RESET}: ");
for (i, local_variable_name) in executable.local_variable_names().iter().enumerate() {
if i != 0 {
output.extend_from_slice(b", ");
}
output.extend_from_slice(BLUE.as_bytes());
Utf16View::of_fly_string(local_variable_name).append_as_wtf8_to(output);
let _ = write!(output, "~{i}{RESET}");
}
output.push(b'\n');
}
if !executable.head.constants.is_empty() {
let _ = writeln!(output, " {GREEN}Constants{RESET}:");
for (i, &value) in executable.head.constants.iter().enumerate() {
output.extend_from_slice(b" ");
let _ = write!(output, "{YELLOW}[{i}]{RESET} = ");
output.extend_from_slice(CYAN.as_bytes());
if value.is_empty() {
output.extend_from_slice(b"<Empty>");
} else if value.is_boolean() {
let _ = write!(output, "Bool({})", value.as_bool());
} else if value.is_int32() {
let _ = write!(output, "Int32({})", value.as_i32());
} else if value.is_double() {
output.extend_from_slice(b"Double(");
append_double_formatted_like_ak(output, value.as_f64());
output.push(b')');
} else if value.is_bigint() {
output.extend_from_slice(b"BigInt(");
Utf16View::of_string(&value.as_bigint().to_utf16_string()).append_as_wtf8_to(output);
output.push(b')');
} else if value.is_string() {
output.extend_from_slice(b"String(\"");
Utf16View::of_string(&value.as_string().utf16_string()).append_as_wtf8_to(output);
output.extend_from_slice(b"\")");
} else if value.is_undefined() {
output.extend_from_slice(b"Undefined");
} else if value.is_null() {
output.extend_from_slice(b"Null");
} else {
output.extend_from_slice(b"Value(");
append_value_formatted_like_ak(output, value);
output.push(b')');
}
output.extend_from_slice(RESET.as_bytes());
output.push(b'\n');
}
}
}
/// What AK's Formatter<double> writes for `value` when no precision is given: the shortest digits that round-trip,
/// laid out as Number::toString lays them out, except that NaN and the infinities are spelled nan, inf and -inf.
pub(crate) fn append_double_formatted_like_ak(output: &mut Vec<u8>, value: f64) {
if value.is_nan() {
output.extend_from_slice(b"nan");
} else if value.is_infinite() {
output.extend_from_slice(if value < 0.0 { b"-inf" } else { b"inf" });
} else {
output.extend_from_slice(number_to_string(value).as_bytes());
}
}
/// What Formatter<JS::Value> writes: the value converted to a string without side effects.
pub(crate) fn append_value_formatted_like_ak(output: &mut Vec<u8>, value: Value) {
if value.is_empty() {
output.extend_from_slice(b"<empty>");
return;
}
Utf16View::of_string(&value.to_utf16_string_without_side_effects()).append_as_wtf8_to(output);
}
fn constant_value(vm: &Vm, constant: &ConstantValue) -> Value {
match constant {
ConstantValue::Number(number) => Value::from_f64(*number),
ConstantValue::Boolean(boolean) => Value::from_bool(*boolean),
ConstantValue::Null => Value::NULL,
ConstantValue::Undefined => Value::UNDEFINED,
ConstantValue::Empty => Value::EMPTY,
ConstantValue::String(string) => {
// String constants are interned so that comparisons with them are pointer comparisons.
if string.length_in_code_units() > MAXIMUM_INTERNED_CONSTANT_LENGTH {
return Value::from_string(PrimitiveString::create(vm, string.clone()));
}
Value::from_string(PrimitiveString::create_interned(vm, &to_utf16_fly_string(string)))
}
ConstantValue::BigInt(literal) => Value::from_bigint(BigInt::create(vm, parse_big_int_literal(literal))),
ConstantValue::WellKnownSymbol(WellKnownSymbolKind::SymbolIterator) => {
Value::from_symbol(vm.well_known_symbols().iterator)
}
ConstantValue::WellKnownSymbol(WellKnownSymbolKind::SymbolAsyncIterator) => {
Value::from_symbol(vm.well_known_symbols().async_iterator)
}
ConstantValue::AbstractOperation(operation) => {
let intrinsics = vm
.current_realm()
.expect("an executable that calls abstract operations is created in a realm")
.intrinsics();
let function = match operation {
AbstractOperationKind::ArraySpeciesCreate => {
return Value::from_object(intrinsics.array_species_create_abstract_operation_function(vm));
}
AbstractOperationKind::AsyncIteratorClose => {
intrinsics.async_iterator_close_abstract_operation_function(vm)
}
AbstractOperationKind::GetMethod => intrinsics.get_method_abstract_operation_function(vm),
AbstractOperationKind::GetIteratorDirect => {
intrinsics.get_iterator_direct_abstract_operation_function(vm)
}
AbstractOperationKind::GetIteratorFromMethod => {
intrinsics.get_iterator_from_method_abstract_operation_function(vm)
}
AbstractOperationKind::IteratorComplete => intrinsics.iterator_complete_abstract_operation_function(vm),
};
Value::from_object(function)
}
}
}
/// The value of a BigInt literal without its `n` suffix, in any of the radixes a literal can use.
fn parse_big_int_literal(literal: &str) -> SignedBigInteger {
let bytes = literal.as_bytes();
let (radix, digits) = match bytes {
[b'0', b'x' | b'X', _, ..] => (16, &bytes[2..]),
[b'0', b'o' | b'O', _, ..] => (8, &bytes[2..]),
[b'0', b'b' | b'B', _, ..] => (2, &bytes[2..]),
_ => (10, bytes),
};
SignedBigInteger::parse_bytes(digits, radix).expect("the frontend only emits valid BigInt literals")
}
// SAFETY: Visits the constants, the only cells that the head holds. Its inline caches do not keep what they remember
// alive.
unsafe impl Trace for ExecutableHead {
fn trace(&self, visitor: &mut Visitor) {
// NB: The constants are visited as owned values, so that a collection that moves their cells rewrites them where
// they are. They are in the tables of the executable, which nothing writes once it is built, and only its
// destructor frees. JIT code that embeds a constant lists its cell among the cells it embeds, which keeps
// the cell where it is while the code lives.
// SAFETY: See above.
unsafe { visitor.visit_owned_values(&self.constants) };
}
}
// SAFETY: Visits the template object caches, the for-in key snapshots, the literal values of classes and the environment
// shapes. The dynamic
// global variable caches do not keep what they remember alive, and the breakpoint sites hold no cells.
unsafe impl Trace for ExecutableRareData {
fn trace(&self, visitor: &mut Visitor) {
self.template_object_caches.trace(visitor);
for cache in &self.object_property_iterator_caches {
cache.data.trace(visitor);
}
self.class_blueprints.trace(visitor);
self.environment_shape_caches.trace(visitor);
}
}
// SAFETY: Visits the constants, the for-in key snapshots, the environment shapes, the template object caches, the
// functions the bytecode creates and the literal values of its classes, which are all the cells an executable keeps
// alive so far. The inline caches do not keep the shapes and objects they remember alive.
unsafe impl Trace for Executable {
fn trace(&self, visitor: &mut Visitor) {
self.head.trace(visitor);
self.property_keys.trace(visitor);
self.shared_function_data.trace(visitor);
self.rare_data.trace(visitor);
self.trace_jit_code(visitor);
}
}