Truly independent web browser
LibJS/JIT: Keep the input of a compile in one block of memory
Andreas Kling9ae28ee33811
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rsindex 329baec5717..4e89678b8c9 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs@@ -34,9 +34,7 @@ const NO_OBJECT_SHAPE_CACHE: u32 = u32::MAX;impl GraphBuilder<'_> {fn object_shape_cache(&self, cache: u32) -> Option<&ObjectShapeCacheSnapshot> {- self.function- .executable- .object_shape_caches+ self.snapshot[self.function.executable.object_shape_caches].get(cache as usize).and_then(Option::as_ref)}@@ -87,7 +85,11 @@ impl GraphBuilder<'_> {let object = self.read(object)?;let Some(offset) = self.literal_allocated_with_cache_shape(object, shape_cache_index)- .and_then(|cached| cached.property_offsets.get(property_slot as usize).copied())+ .and_then(|cached| {+ self.snapshot[cached.property_offsets]+ .get(property_slot as usize)+ .copied()+ })else {return Ok(false);};@@ -175,10 +177,7 @@ impl GraphBuilder<'_> {if has_home_object {return Ok(false);}- let Some((sample, inline_executable)) = self- .function- .executable- .closure_templates+ let Some((sample, inline_executable)) = self.snapshot[self.function.executable.closure_templates].get(shared_function_data_index as usize).and_then(Option::as_ref).map(|closure| (closure.sample, closure.inline_executable))@@ -230,10 +229,7 @@ impl GraphBuilder<'_> {if self.function.is_virtual() {return Ok(false);}- let Some(template) = self- .function- .executable- .lexical_environment_templates+ let Some(template) = self.snapshot[self.function.executable.lexical_environment_templates].get(shape_cache as usize).and_then(Option::as_ref)else {@@ -321,13 +317,14 @@ mod tests {let program = literal_program();let mut snapshot = snapshot_for(&program, test_layout());snapshot.runtime.object_allocation.slow_path = 1;- snapshot.executables[0].object_shape_caches = vec![Some(ObjectShapeCacheSnapshot {+ let property_offsets = snapshot.add(&[1, 0]);+ snapshot.executables[0].object_shape_caches = snapshot.add(&[Some(ObjectShapeCacheSnapshot {shape: ShapeSnapshot {shape: LITERAL_SHAPE,property_count: 2,},- property_offsets: vec![1, 0],- })];+ property_offsets,+ })]);snapshot.executables[0].new_object_shape = Some(ShapeSnapshot {shape: EMPTY_SHAPE,property_count: 0,@@ -383,7 +380,7 @@ mod tests {let template = crate::snapshot::LexicalEnvironmentTemplateSnapshot {allocator: 0x5000,cell_size: 88,- words: vec![0; 9],+ words: snapshot.add(&[0; 9]),binding_count: 2,inline_binding_values: true,binding_values_offset: 48,@@ -391,7 +388,7 @@ mod tests {shape: Some(SHAPE),};// NB: Cache 1 has no template.- snapshot.executables[0].lexical_environment_templates = vec![Some(template), None];+ snapshot.executables[0].lexical_environment_templates = snapshot.add(&[Some(template), None]);let graph = crate::builder::build_graph(&snapshot).unwrap();let ops = graph.blocks@@ -429,7 +426,7 @@ mod tests {let program = literal_program();let mut snapshot = snapshot_for(&program, test_layout());snapshot.runtime.object_allocation.slow_path = 1;- snapshot.executables[0].object_shape_caches = vec![None];+ snapshot.executables[0].object_shape_caches = snapshot.add(&[None]);snapshot.executables[0].new_object_shape = Some(ShapeSnapshot {shape: EMPTY_SHAPE,property_count: 0,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rsindex fc4c3c5c945..0398122ad86 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/arguments.rs@@ -113,9 +113,7 @@ fn constant_index(function: &super::Function<'_>, instruction: &Instruction) ->let SlotKind::Constant(constant) = function.layout.slot_kind(index) else {return None;};- function- .executable- .constants+ function.snapshot[function.executable.constants].get(constant as usize).and_then(|bits| value::as_int32(*bits)).and_then(|index| u32::try_from(index).ok())diff --git a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs b/Libraries/LibJS/JIT/Rust/src/builder/caches.rsindex 8ae7fa9ec9e..01714952817 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/caches.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/caches.rs@@ -236,7 +236,7 @@ impl GraphBuilder<'_> {/// action form, if the cache is monomorphic or polymorphic and compiled/// code can apply every entry.pub(super) fn cache_entries(&self, cache: u32) -> Option<Vec<CacheEntry>> {- let cache = self.function.executable.property_caches.get(cache as usize)?;+ let cache = self.snapshot[self.function.executable.property_caches].get(cache as usize)?;if !matches!(cache.kind,PropertyCacheKind::Monomorphic | PropertyCacheKind::Polymorphic@@ -244,20 +244,19 @@ impl GraphBuilder<'_> {{return None;}- cache.entries.iter().map(CacheEntry::of).collect()+ self.snapshot[cache.entries].iter().map(CacheEntry::of).collect()}/// The entry of megamorphic property lookup cache `cache` for the shape/// the code knows the object in `object` has (see/// `AbstractFrame::fresh_shapes`), if the snapshot captured one.pub(super) fn megamorphic_entries_for_known_shape(&self, cache: u32, object: Operand) -> Option<Vec<CacheEntry>> {- let cache = self.function.executable.property_caches.get(cache as usize)?;+ let cache = self.snapshot[self.function.executable.property_caches].get(cache as usize)?;if cache.kind != PropertyCacheKind::Megamorphic {return None;}let shape = self.fresh_shape(self.peek(object)?.node)?;- let entry = cache- .entries+ let entry = self.snapshot[cache.entries].iter().filter_map(CacheEntry::of).find(|entry| entry.shape.shape == shape)?;diff --git a/Libraries/LibJS/JIT/Rust/src/builder/elements.rs b/Libraries/LibJS/JIT/Rust/src/builder/elements.rsindex 08761f981cf..9f951ea3d6b 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/elements.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/elements.rs@@ -35,7 +35,11 @@ impl GraphBuilder<'_> {/// The bits of the keyed feedback of `instruction`, if it has a slot.pub(super) fn keyed_feedback_bits(&self, instruction: &Instruction) -> Option<u32> {let slot = instruction.feedback_slots().keyed?;- Some(self.function.executable.feedback.keyed.get(usize::from(slot))?.bits)+ Some(+ self.snapshot[self.function.executable.feedback.keyed]+ .get(usize::from(slot))?+ .bits,+ )}/// The typed array element kinds keyed feedback `bits` saw.diff --git a/Libraries/LibJS/JIT/Rust/src/builder/environments.rs b/Libraries/LibJS/JIT/Rust/src/builder/environments.rsindex 6bc3fdb757f..6fa9eeb6dd3 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/environments.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/environments.rs@@ -174,10 +174,7 @@ impl GraphBuilder<'_> {} else {self.check_initialized(binding)?};- let binding = match self- .function- .executable- .captured_bindings+ let binding = match self.snapshot[self.function.executable.captured_bindings].iter().find(|(captured, _)| *captured == coordinate).map(|(_, value)| *value)@@ -209,8 +206,8 @@ impl GraphBuilder<'_> {let mut slow_paths = self.start_slow_paths(None)?;// NB: Bindings of the closure's environments that every environment// of their scope declares mutable need no check of that.- let declared_mutable =- field == FrameField::LexicalEnvironment && self.function.executable.mutable_bindings.contains(&coordinate);+ let declared_mutable = field == FrameField::LexicalEnvironment+ && self.snapshot[self.function.executable.mutable_bindings].contains(&coordinate);if !declared_mutable {self.branch_to_slow_path(&mut slow_paths,@@ -259,7 +256,10 @@ impl GraphBuilder<'_> {is_immutable: bool,is_strict: bool,) -> Result<Option<Flow>, CompileFailure> {- let Some(name) = self.function.executable.identifiers.get(identifier as usize).copied() else {+ let Some(name) = self.snapshot[self.function.executable.identifiers]+ .get(identifier as usize)+ .copied()+ else {return Err(CompileFailure::InvalidBytecode {pc: self.function.pc,reason: "identifier out of range",diff --git a/Libraries/LibJS/JIT/Rust/src/builder/globals.rs b/Libraries/LibJS/JIT/Rust/src/builder/globals.rsindex 3aea999a028..2736b46cc66 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/globals.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/globals.rs@@ -73,7 +73,7 @@ impl GraphBuilder<'_> {/// executable's realm, if code may access the variable directly.fn global_cache(&self, cache: u32) -> Option<(Globals, GlobalCacheSnapshot)> {let snapshot = self.function.executable.globals.as_ref()?;- let global = (*snapshot.caches.get(cache as usize)?)?;+ let global = (*self.snapshot[snapshot.caches].get(cache as usize)?)?;let globals = Globals {object: snapshot.object,declarative_environment: snapshot.declarative_environment,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rsindex cb30d727aab..ff48a1b1c19 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs@@ -139,7 +139,7 @@ fn can_inline(callee: &Function<'_>, virtual_arguments: bool, derived_construct:// interpreter runs the handler in the callee's materialized frame (see `translate::leave()` in the// runtime). A handler that caught before would make the code leave again and again.if opcode == OpCode::Catch {- return !super::has_run(callee.executable, instruction.pc);+ return !super::has_run(callee.snapshot, callee.executable, instruction.pc);}// NB: An inlined callee reads what its call passed for constant indices (see `try_build_argument()`).if opcode == OpCode::GetArgument {@@ -200,9 +200,7 @@ fn returns_no_object(callee: &Function<'_>) -> bool {Instruction::Return { value } => {value.raw() == THIS_VALUE_REGISTER|| match callee.layout.slot_kind(value) {- SlotKind::Constant(index) => callee- .executable- .constants+ SlotKind::Constant(index) => callee.snapshot[callee.executable.constants].get(index as usize).is_some_and(|constant| value::tag(*constant) != value::OBJECT_TAG),_ => false,@@ -283,7 +281,9 @@ fn calls_super_once_before_returning(callee: &Function<'_>) -> bool {}// NB: What super() returned is `this`.let returns_undefined_or_this = |value: Operand| match callee.layout.slot_kind(value) {- SlotKind::Constant(index) => callee.executable.constants.get(index as usize) == Some(&value::UNDEFINED),+ SlotKind::Constant(index) => {+ callee.snapshot[callee.executable.constants].get(index as usize) == Some(&value::UNDEFINED)+ }_ => follows_bind_this && Some(value) == super_call_result,};match instruction.instruction {@@ -793,11 +793,12 @@ impl<'a> GraphBuilder<'a> {self.embed(target.function.global_this);}if let Some(index) = target.environment {- let Some(template) = self.function.executable.environment_templates.get(index as usize) else {+ let snapshot = self.snapshot;+ let Some(template) = snapshot[self.function.executable.environment_templates].get(index as usize) else {return Ok(None);};- for cell in template.cells.clone() {- self.embed(cell);+ for cell in &snapshot[template.cells] {+ self.embed(*cell);}}if let Some(inlined_frame_bytes) = without_frames {@@ -1062,11 +1063,7 @@ impl<'a> GraphBuilder<'a> {return Ok(None);};let start = forwarded.bound_arguments_start as usize;- let Some(bound_arguments) = self- .function- .executable- .feedback- .bound_arguments+ let Some(bound_arguments) = self.snapshot[self.function.executable.feedback.bound_arguments].get(start..start + forwarded.bound_argument_count as usize)else {return Ok(None);@@ -1484,8 +1481,7 @@ impl<'a> GraphBuilder<'a> {else {return Ok(None);};- let Some(index) = self.snapshot.executables[executable as usize]- .closure_templates+ let Some(index) = self.snapshot[self.snapshot.executables[executable as usize].closure_templates].get(shared_function_data_index as usize).and_then(Option::as_ref).and_then(|template| template.inline_executable)@@ -1596,16 +1592,15 @@ impl<'a> GraphBuilder<'a> {let Some(executable) = self.snapshot.executables.get(index as usize) else {return true;};- let Ok(decoded) = super::decoded_function(executable, &self.decoded[index as usize]) else {+ let Ok(decoded) = super::decoded_function(self.snapshot, executable, &self.decoded[index as usize]) else {return true;};+ let exit_sites = &self.snapshot[executable.exit_sites];decoded.instructions.iter().any(|instruction| {matches!(instruction.instruction.opcode(),OpCode::SuperCall | OpCode::SuperCallWithForwardedArguments- ) && executable- .exit_sites- .contains(&(instruction.pc, ExitKind::BadCallTarget))+ ) && exit_sites.contains(&(instruction.pc, ExitKind::BadCallTarget))})}@@ -1798,9 +1793,11 @@ impl<'a> GraphBuilder<'a> {{return Ok(false);}- let Some(fields) = self.function.executable.derived_instance_fields.clone() else {+ let Some(fields) = self.function.executable.derived_instance_fields else {return Ok(false);};+ let snapshot = self.snapshot;+ let added_fields = &snapshot[fields.fields];let this_register = Operand::from_raw(THIS_VALUE_REGISTER);let this_value = self.read(this_register)?;if self.graph.constant_value(this_value) != Some(value::EMPTY) {@@ -1816,9 +1813,14 @@ impl<'a> GraphBuilder<'a> {else {return Ok(false);};- let added_count = fields.fields.iter().map(|(offset, _, _)| offset + 1).max().unwrap_or(0);+ let added_count = added_fields.iter().map(|(offset, _, _)| offset + 1).max().unwrap_or(0);let reserve = reserve.max(added_count);- if self.runtime.object_allocation.size_class_for(reserve).is_none() {+ if self+ .runtime+ .object_allocation+ .size_class_for(snapshot, reserve)+ .is_none()+ {return Ok(false);}self.graph.nodes[allocation.index()].op = Op::AllocateObject {@@ -1845,7 +1847,7 @@ impl<'a> GraphBuilder<'a> {// NB: The fields have literal values, so this cannot throw, and since `this` has the shape the fields start// from (checked above), which allows extensions and has none of their names, each field adds its property// or sets the value of an earlier field of the same name.- for (offset, value, added) in fields.fields {+ for (offset, value, added) in added_fields.iter().copied() {let value = self.constant(value);match added {Some(shape) => {@@ -2113,7 +2115,8 @@ impl<'a> GraphBuilder<'a> {if callee_executable.builtin {return true;}- let Ok(decoded) = super::decoded_function(callee_executable, &self.decoded[index as usize]) else {+ let Ok(decoded) = super::decoded_function(self.snapshot, callee_executable, &self.decoded[index as usize])+ else {return false;};self.inlined_instructions + decoded.instructions.len()@@ -2146,7 +2149,7 @@ impl<'a> GraphBuilder<'a> {if !may_inline {return None;}- let decoded = super::decoded_function(callee_executable, &self.decoded[index as usize]).ok()?;+ let decoded = super::decoded_function(snapshot, callee_executable, &self.decoded[index as usize]).ok()?;let instruction_count = decoded.instructions.len();let limits = snapshot.options.inlining;// NB: Builtins are always inlined (see the snapshot's inlining rules).@@ -2181,7 +2184,7 @@ impl<'a> GraphBuilder<'a> {|| (closure && callee_executable.is_non_strict_function())|| (virtual_arguments && uses_passed_arguments)|| forwards_arguments_to_super;- let callee_function = Function::new(index, callee_executable, decoded, has_legacy_arguments).ok()?;+ let callee_function = Function::new(snapshot, index, decoded, has_legacy_arguments).ok()?;if !can_inline(&callee_function, virtual_arguments, derived_construct) {return None;}@@ -2313,7 +2316,7 @@ impl<'a> GraphBuilder<'a> {Some(construct) if derived_construct.is_none() => self.construct_this(new_target.unwrap_or(function.function),construct,- callee_executable.literal_instance_fields.as_deref().unwrap_or_default(),+ &self.snapshot[callee_executable.literal_instance_fields.unwrap_or_default()],),_ => receiver,};diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 7454f520ab7..13059db09d4 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -101,7 +101,7 @@ pub fn build_graph(snapshot: &Snapshot) -> Result<Graph, CompileFailure> {snapshot.executables.first()- .is_none_or(|executable| has_run(executable, pc))+ .is_none_or(|executable| has_run(snapshot, executable, pc))})}@@ -109,8 +109,8 @@ pub fn build_graph(snapshot: &Snapshot) -> Result<Graph, CompileFailure> {/// feedback it records tells: an instruction that records feedback ran if any/// of its slots recorded something. Instructions without feedback count as/// having run. Instructions that never ran are compiled as unconditional exits.-pub fn has_run(executable: &ExecutableSnapshot, pc: u32) -> bool {- let Ok(instruction) = crate::bytecode::decode_instruction(&executable.bytecode, pc) else {+pub fn has_run(snapshot: &Snapshot, executable: &ExecutableSnapshot, pc: u32) -> bool {+ let Ok(instruction) = crate::bytecode::decode_instruction(&snapshot[executable.bytecode], pc) else {return true;};let slots = instruction.instruction.feedback_slots();@@ -118,19 +118,19 @@ pub fn has_run(executable: &ExecutableSnapshot, pc: u32) -> bool {let slot = |slot: Option<u16>| slot.map(usize::from);let recorded = [slot(slots.arith)- .and_then(|slot| feedback.arith.get(slot))+ .and_then(|slot| snapshot[feedback.arith].get(slot)).map(|bits| *bits != 0),slot(slots.value)- .and_then(|slot| feedback.value.get(slot))+ .and_then(|slot| snapshot[feedback.value].get(slot)).map(|bits| *bits != 0),slot(slots.cache_value)- .and_then(|cache| feedback.cache_value.get(cache))+ .and_then(|cache| snapshot[feedback.cache_value].get(cache)).map(|bits| *bits != 0),slot(slots.call)- .and_then(|slot| feedback.call.get(slot))+ .and_then(|slot| snapshot[feedback.call].get(slot)).map(|call| call.target.is_some() || call.flags != 0 || call.value != 0),slot(slots.keyed)- .and_then(|slot| feedback.keyed.get(slot))+ .and_then(|slot| snapshot[feedback.keyed].get(slot)).map(|keyed| keyed.bits != 0),];recorded.iter().all(Option::is_none) || recorded.contains(&Some(true))@@ -352,12 +352,14 @@ struct DecodedFunction {}fn decoded_function<'a>(+ snapshot: &Snapshot,executable: &ExecutableSnapshot,cache: &'a OnceCell<Result<DecodedFunction, CompileFailure>>,) -> Result<&'a DecodedFunction, CompileFailure> {cache.get_or_init(|| {- let instructions = decode_all(&executable.bytecode).map_err(|error| CompileFailure::InvalidBytecode {+ let bytecode = &snapshot[executable.bytecode];+ let instructions = decode_all(bytecode).map_err(|error| CompileFailure::InvalidBytecode {pc: error.pc,reason: "undecodable instruction",})?;@@ -390,6 +392,7 @@ struct FunctionAnalysis {/// The state of the builder's walk over one executable: the compiled/// function or an inlined callee.struct Function<'a> {+ snapshot: &'a Snapshot,/// Index into `Snapshot::executables`.index: u32,executable: &'a ExecutableSnapshot,@@ -436,22 +439,23 @@ struct Function<'a> {}impl<'a> Function<'a> {+ /// The state for a walk over executable `index` of `snapshot`, which `decoded` is the instructions of.fn new(+ snapshot: &'a Snapshot,index: u32,- executable: &'a ExecutableSnapshot,decoded: &'a DecodedFunction,has_legacy_arguments: bool,) -> Result<Self, CompileFailure> {+ let executable = &snapshot.executables[index as usize];let layout = executable.layout;let instructions = decoded.instructions.as_slice();let analysis = decoded.analysis.get_or_init(|| {- let cfg = Cfg::new(instructions, &executable.exception_handlers, &layout).map_err(|_| {- CompileFailure::InvalidBytecode {- pc: 0,- reason: "invalid control flow",- }+ let handlers = &snapshot[executable.exception_handlers];+ let cfg = Cfg::new(instructions, handlers, &layout).map_err(|_| CompileFailure::InvalidBytecode {+ pc: 0,+ reason: "invalid control flow",})?;let loop_phi_slots = loop_phi_slots(&cfg);let loops_replacing_environments = loops_replacing_environments(&cfg, instructions);@@ -481,6 +485,7 @@ impl<'a> Function<'a> {.get_or_init(|| Liveness::compute(instructions, &analysis.cfg, &layout, has_legacy_arguments));let block_count = analysis.cfg.blocks.len();Ok(Self {+ snapshot,index,executable,layout,@@ -567,7 +572,7 @@ impl<'a> GraphBuilder<'a> {pc: 0,reason: "no executable",})?;- let decoded_root = decoded_function(executable, &decoded[0])?;+ let decoded_root = decoded_function(snapshot, executable, &decoded[0])?;// NB: `GetArgument` reads the argument slots from frame memory, which only the slots it keeps live hold the// current values of: a dead slot may be in sync with `undefined` instead (see `dead_frame()`). Inlined// callees that read their passed arguments keep them live the same way (see `inlinable_callee()`).@@ -575,7 +580,7 @@ impl<'a> GraphBuilder<'a> {.instructions.iter().any(|instruction| instruction.instruction.opcode() == OpCode::GetArgument);- let function = Function::new(0, executable, decoded_root, reads_argument_slots)?;+ let function = Function::new(snapshot, 0, decoded_root, reads_argument_slots)?;let arguments_base = function.layout.arguments_base();let legacy_arguments = if executable.supports_legacy_arguments {arguments_base..arguments_base + function.layout.number_of_arguments@@ -637,20 +642,22 @@ impl<'a> GraphBuilder<'a> {let unwritten_slots = self.slots_kept_from_start();let mut graph = self.graph;- for (index, executable) in self.snapshot.executables.iter().enumerate() {- let sites = if executable.builtin {- self.snapshot.executables[0]- .builtin_exit_sites- .iter()- .filter(|(cell, _, _)| *cell == executable.cell)- .map(|(_, pc, kind)| (*pc, *kind))- .collect::<Vec<_>>()+ let snapshot = self.snapshot;+ for (index, executable) in (0..).zip(snapshot.executables.iter()) {+ if executable.builtin {+ let sites = &snapshot[snapshot.executables[0].builtin_exit_sites];+ graph.exit_sites.extend(+ sites+ .iter()+ .filter(|(cell, _, _)| *cell == executable.cell)+ .map(|(_, pc, kind)| (index, *pc, *kind)),+ );} else {- executable.exit_sites.clone()- };- graph- .exit_sites- .extend(sites.into_iter().map(|(pc, kind)| (index as u32, pc, kind)));+ let sites = &snapshot[executable.exit_sites];+ graph+ .exit_sites+ .extend(sites.iter().map(|(pc, kind)| (index, *pc, *kind)));+ }}assert_eq!(graph.blocks.len(), self.order.len(), "every created block was started");graph.reorder_blocks(&self.order);@@ -1173,7 +1180,9 @@ impl<'a> GraphBuilder<'a> {/// The feedback a call instruction recorded in its feedback slot `slot`.fn call_feedback(&self, slot: u16) -> Option<CallFeedbackSnapshot> {- self.function.executable.feedback.call.get(usize::from(slot)).copied()+ self.snapshot[self.function.executable.feedback.call]+ .get(usize::from(slot))+ .copied()}/// Whether the instruction at `pc` of the function being walked ever ran.@@ -1181,7 +1190,7 @@ impl<'a> GraphBuilder<'a> {if self.function.index == 0 {(self.has_run)(pc)} else {- has_run(self.function.executable, pc)+ has_run(self.snapshot, self.function.executable, pc)}}@@ -1208,15 +1217,12 @@ impl<'a> GraphBuilder<'a> {{return Ok(self.emit(Op::LoadSlot { slot: operand.raw() }, Vec::new(), Some(Repr::Tagged)));}- let bits = *self- .function- .executable- .constants- .get(index)- .ok_or(CompileFailure::InvalidBytecode {+ let bits = *self.snapshot[self.function.executable.constants].get(index).ok_or(+ CompileFailure::InvalidBytecode {pc: self.function.pc,reason: "read of a constant that does not exist",- })?;+ },+ )?;Ok(self.constant(bits))}}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rsindex 140cfc29ae7..5db2feeb990 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_access.rs@@ -71,9 +71,9 @@ impl GraphBuilder<'_> {let executable = self.function.executable;if executable.builtin {let site = (executable.cell, self.function.pc, kind);- return !self.snapshot.executables[0].builtin_exit_sites.contains(&site);+ return !self.snapshot[self.snapshot.executables[0].builtin_exit_sites].contains(&site);}- !executable.exit_sites.contains(&(self.function.pc, kind))+ !self.snapshot[executable.exit_sites].contains(&(self.function.pc, kind))}pub(super) fn embed(&mut self, cell: CellId) {diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rsindex c6f9c0971c2..70386a2d403 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_additions.rs@@ -75,7 +75,12 @@ impl GraphBuilder<'_> {return Ok(false);};let reserve = reserve.max(added_count);- if self.runtime.object_allocation.size_class_for(reserve).is_none() {+ if self+ .runtime+ .object_allocation+ .size_class_for(self.snapshot, reserve)+ .is_none()+ {return Ok(false);}let value = self.read(src)?;diff --git a/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs b/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rsindex 3c30d29f450..6c7c3b8fa38 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/slow_paths.rs@@ -66,9 +66,7 @@ impl GraphBuilder<'_> {let layout = slow_path_layout(opcode);let bytes_at = |offset: u32, size: usize| -> Result<&[u8], CompileFailure> {let at = (self.function.pc + offset) as usize;- self.function- .executable- .bytecode+ self.snapshot[self.function.executable.bytecode].get(at..at + size).ok_or(CompileFailure::InvalidBytecode {pc: self.function.pc,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rsindex f2a99a0a51d..7ff377ac616 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/speculation.rs@@ -239,7 +239,9 @@ impl GraphBuilder<'_> {/// The arithmetic feedback of the instruction being built.fn arith_feedback(&self, instruction: &Instruction) -> Option<u8> {let slot = instruction.feedback_slots().arith?;- self.function.executable.feedback.arith.get(usize::from(slot)).copied()+ self.snapshot[self.function.executable.feedback.arith]+ .get(usize::from(slot))+ .copied()}/// Builds an arithmetic, comparison or update instruction.diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rsindex 30ee9afbb29..3279d3bbb53 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs@@ -8,27 +8,33 @@ use super::*;use crate::bytecode::test_support::*;use crate::ir::dump;use crate::snapshot::ExecutableSnapshot;+use crate::snapshot::List;/// The constants of `test_layout()`: c0 is 0 and c1 is 10.pub(crate) fn test_constants() -> Vec<u64> {vec![value::int32(0), value::int32(10)]}-/// A snapshot of `program`. Its `bytecode_address` points at the snapshot's-/// own copy of the bytecode.-pub(crate) fn snapshot_for(program: &Program, layout: FrameLayout) -> Snapshot {- let mut snapshot = Snapshot {- executables: vec![ExecutableSnapshot {- bytecode: program.bytes.clone(),- bytecode_address: 0,- layout,- constants: test_constants(),- exception_handlers: program.handlers.clone(),- ..ExecutableSnapshot::default()- }],- ..Snapshot::default()+/// Adds `program` to `snapshot` as its next executable. Its `bytecode_address` points at a copy of the bytecode that+/// stays where it is for the rest of the test run: compiled code has the address, and the pools of a snapshot move+/// when they grow.+pub(crate) fn add_program(snapshot: &mut Snapshot, program: &Program, layout: FrameLayout) {+ let code: &'static [u8] = Box::leak(program.bytes.clone().into_boxed_slice());+ let executable = ExecutableSnapshot {+ bytecode: snapshot.add(code),+ bytecode_address: code.as_ptr() as u64,+ layout,+ constants: snapshot.add(&test_constants()),+ exception_handlers: snapshot.add(&program.handlers),+ ..ExecutableSnapshot::default()};- snapshot.executables[0].bytecode_address = snapshot.executables[0].bytecode.as_ptr() as u64;+ snapshot.add_executable(executable);+}++/// A snapshot of `program`.+pub(crate) fn snapshot_for(program: &Program, layout: FrameLayout) -> Snapshot {+ let mut snapshot = Snapshot::new();+ add_program(&mut snapshot, program, layout);snapshot}@@ -62,11 +68,14 @@ fn executable_analyses_are_lazy_and_borrowed_by_independent_walks() {let snapshot = snapshot_for(&program, test_layout());let executable = &snapshot.executables[0];let cache = OnceCell::new();- let decoded = decoded_function(executable, &cache).unwrap();+ let decoded = decoded_function(&snapshot, executable, &cache).unwrap();assert!(decoded.analysis.get().is_none());- assert!(std::ptr::eq(decoded, decoded_function(executable, &cache).unwrap()));- let mut first = Function::new(0, executable, decoded, false).unwrap();- let second = Function::new(0, executable, decoded, false).unwrap();+ assert!(std::ptr::eq(+ decoded,+ decoded_function(&snapshot, executable, &cache).unwrap()+ ));+ let mut first = Function::new(&snapshot, 0, decoded, false).unwrap();+ let second = Function::new(&snapshot, 0, decoded, false).unwrap();assert!(std::ptr::eq(first.cfg, second.cfg));assert!(std::ptr::eq(first.liveness, second.liveness));assert_eq!(first.instructions.as_ptr(), second.instructions.as_ptr());@@ -82,16 +91,16 @@ fn cached_liveness_keeps_legacy_arguments_only_for_inlined_walks() {let snapshot = snapshot_for(&program, layout);let executable = &snapshot.executables[0];let cache = OnceCell::new();- let decoded = decoded_function(executable, &cache).unwrap();- let first = Function::new(0, executable, decoded, first_mode).unwrap();- let second = Function::new(0, executable, decoded, !first_mode).unwrap();+ let decoded = decoded_function(&snapshot, executable, &cache).unwrap();+ let first = Function::new(&snapshot, 0, decoded, first_mode).unwrap();+ let second = Function::new(&snapshot, 0, decoded, !first_mode).unwrap();assert!(std::ptr::eq(first.cfg, second.cfg));let argument_slot = layout.tracked_index(Operand::from_raw(layout.arguments_base())).unwrap();assert_eq!(first.liveness.live_in(0).contains(argument_slot), first_mode);assert_eq!(second.liveness.live_in(0).contains(argument_slot), !first_mode);- let repeated = Function::new(0, executable, decoded, first_mode).unwrap();+ let repeated = Function::new(&snapshot, 0, decoded, first_mode).unwrap();assert!(std::ptr::eq(first.liveness, repeated.liveness));}}@@ -367,10 +376,10 @@ fn instructions_whose_feedback_is_empty_never_ran() {Instruction::Return { value: r(6) },]});- let compile = |arith: Vec<u8>, exit_sites| {+ let compile = |arith: Vec<u8>, exit_sites: Vec<(u32, crate::code::ExitKind)>| {let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.arith = arith;- snapshot.executables[0].exit_sites = exit_sites;+ snapshot.executables[0].feedback.arith = snapshot.add(&arith);+ snapshot.executables[0].exit_sites = snapshot.add(&exit_sites);dump(&optimized_graph(&snapshot), &test_layout())};let add_pc = program.offsets[1];@@ -583,8 +592,8 @@ fn counting_loop(feedback: u8, exit_sites: Vec<(u32, ExitKind)>) -> String {]});let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.arith = vec![feedback, feedback];- snapshot.executables[0].exit_sites = exit_sites;+ snapshot.executables[0].feedback.arith = snapshot.add(&[feedback, feedback]);+ snapshot.executables[0].exit_sites = snapshot.add(&exit_sites);dump(&optimized_graph(&snapshot), &test_layout())}@@ -648,7 +657,8 @@ fn strict_equality_with_constants_compares_bits_and_feeds_branches_directly() {]});let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].constants[1] = value::UNDEFINED;+ let constants = snapshot.executables[0].constants;+ snapshot[constants][1] = value::UNDEFINED;let text = dump(&optimized_graph(&snapshot), &test_layout());assert_eq!(text.matches("TaggedEquals").count(), 2, "{text}");assert!(!text.contains("BranchTruthy"), "{text}");@@ -669,12 +679,12 @@ fn strict_equality_of_identity_comparable_values_compares_bits() {]});let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.arith = vec![1 << 5];+ snapshot.executables[0].feedback.arith = snapshot.add(&[1 << 5]);let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(text.contains("CheckIdentityComparable"), "{text}");assert!(text.contains("TaggedEquals"), "{text}");// Numbers compare as numbers, other values in the slow path.- snapshot.executables[0].feedback.arith = vec![(1 << 5) | (1 << 1)];+ snapshot.executables[0].feedback.arith = snapshot.add(&[(1 << 5) | (1 << 1)]);let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(text.contains("Float64StrictlyEquals"), "{text}");assert!(text.contains("CallSlowPath StrictlyEquals"), "{text}");@@ -873,8 +883,15 @@ pub(crate) mod property_access {}}- pub(crate) fn cache(entries: Vec<PropertyCacheEntrySnapshot>) -> PropertyCacheSnapshot {- PropertyCacheSnapshot {+ /// A property cache with its entries, which a snapshot has in a list.+ #[derive(Clone)]+ pub(crate) struct PropertyCache {+ pub kind: PropertyCacheKind,+ pub entries: Vec<PropertyCacheEntrySnapshot>,+ }++ pub(crate) fn cache(entries: Vec<PropertyCacheEntrySnapshot>) -> PropertyCache {+ PropertyCache {kind: if entries.len() == 1 {PropertyCacheKind::Monomorphic} else {@@ -884,14 +901,22 @@ pub(crate) mod property_access {}}- fn dump_with_caches(- program: &Program,- caches: Vec<PropertyCacheSnapshot>,- exit_sites: Vec<(u32, ExitKind)>,- ) -> String {+ /// Adds `caches` and their entries to `snapshot`.+ pub(crate) fn add_caches(snapshot: &mut Snapshot, caches: &[PropertyCache]) -> List<PropertyCacheSnapshot> {+ let caches = caches+ .iter()+ .map(|cache| PropertyCacheSnapshot {+ kind: cache.kind,+ entries: snapshot.add(&cache.entries),+ })+ .collect::<Vec<_>>();+ snapshot.add(&caches)+ }++ fn dump_with_caches(program: &Program, caches: Vec<PropertyCache>, exit_sites: Vec<(u32, ExitKind)>) -> String {let mut snapshot = snapshot_for(program, test_layout());- snapshot.executables[0].property_caches = caches;- snapshot.executables[0].exit_sites = exit_sites;+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &caches);+ snapshot.executables[0].exit_sites = snapshot.add(&exit_sites);snapshot.runtime.heap_region_offset_mask = (1 << 48) - 1;dump(&optimized_graph(&snapshot), &test_layout())}@@ -1133,11 +1158,9 @@ pub(crate) mod property_access {(Some(crate::snapshot::keyed_feedback_bits::MAGICAL_LENGTH), false),] {let mut snapshot = snapshot_for(&get_length, test_layout());- snapshot.executables[0].property_caches = vec![cache(vec![entry(0x100, true)])];- snapshot.executables[0].feedback.keyed = feedback- .map(|bits| crate::snapshot::KeyedFeedbackSnapshot { bits })- .into_iter()- .collect();+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &[cache(vec![entry(0x100, true)])]);+ let keyed = feedback.map(|bits| crate::snapshot::KeyedFeedbackSnapshot { bits });+ snapshot.executables[0].feedback.keyed = snapshot.add(keyed.as_slice());snapshot.runtime.heap_region_offset_mask = (1 << 48) - 1;let text = dump(&optimized_graph(&snapshot), &test_layout());assert_eq!(text.contains("CallNativeAccessor"), calls_getter, "{text}");@@ -1205,7 +1228,7 @@ pub(crate) mod property_access {entry.prototype_chain_validity = Some(CellId(0x8000));entry.prototype_chain_valid = true;let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].property_caches = vec![cache(vec![entry])];+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &[cache(vec![entry])]);let graph = optimized_graph(&snapshot);let text = dump(&graph, &test_layout());// The code is valid where it starts, so the first load needs nothing,@@ -1327,8 +1350,9 @@ pub(crate) mod property_access {]});let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.keyed = vec![crate::snapshot::KeyedFeedbackSnapshot { bits: keyed_bits }];- snapshot.executables[0].exit_sites = exit_sites;+ snapshot.executables[0].feedback.keyed =+ snapshot.add(&[crate::snapshot::KeyedFeedbackSnapshot { bits: keyed_bits }]);+ snapshot.executables[0].exit_sites = snapshot.add(&exit_sites);snapshot.runtime.layout.typed_array_kind_uint16 = 3;dump(&optimized_graph(&snapshot), &test_layout())}@@ -1340,9 +1364,9 @@ pub(crate) mod property_access {// `return a0[10]` where the feedback saw indices of strings.let program = assemble(|_| vec![get_by_value(r(5), a(0), c(1)), Instruction::Return { value: r(5) }]);let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.keyed = vec![crate::snapshot::KeyedFeedbackSnapshot {+ snapshot.executables[0].feedback.keyed = snapshot.add(&[crate::snapshot::KeyedFeedbackSnapshot {bits: OTHER_KEY | OTHER_ELEMENTS,- }];+ }]);snapshot.runtime.layout.single_ascii_character_strings = 0x1000;let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(@@ -1419,9 +1443,10 @@ pub(crate) mod property_access {exit_sites: Vec<(u32, ExitKind)>,) -> String {let mut snapshot = snapshot_for(program, test_layout());- snapshot.executables[0].constants[1] = KEY;- snapshot.executables[0].property_caches = vec![cache(entries)];- snapshot.executables[0].exit_sites = exit_sites;+ let constants = snapshot.executables[0].constants;+ snapshot[constants][1] = KEY;+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &[cache(entries)]);+ snapshot.executables[0].exit_sites = snapshot.add(&exit_sites);snapshot.runtime.heap_region_offset_mask = (1 << 48) - 1;dump(&optimized_graph(&snapshot), &test_layout())}@@ -1521,10 +1546,10 @@ pub(crate) mod property_access {(7, TypedArrayElement::Float32),(8, TypedArrayElement::Float64),] {- snapshot.executables[0].feedback.keyed = vec![crate::snapshot::KeyedFeedbackSnapshot {+ snapshot.executables[0].feedback.keyed = snapshot.add(&[crate::snapshot::KeyedFeedbackSnapshot {bits: 1 | (1 << (9 + kind)),- }];- snapshot.executables[0].exit_sites.clear();+ }]);+ snapshot.executables[0].exit_sites = List::empty();let text = dump(&optimized_graph(&snapshot), &test_layout());for name in ["CheckNumber", "CheckBounds"] {assert!(text.contains(name), "{text}");@@ -1541,7 +1566,7 @@ pub(crate) mod property_access {_ => assert!(text.contains("Float64ToInt32"), "{text}"),}assert!(!text.contains("CallSlowPath"), "{text}");- snapshot.executables[0].exit_sites = vec![(0, ExitKind::BadType), (0, ExitKind::OutOfBounds)];+ snapshot.executables[0].exit_sites = snapshot.add(&[(0, ExitKind::BadType), (0, ExitKind::OutOfBounds)]);let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(!text.contains("CheckNumber"), "{text}");assert!(text.contains("CallSlowPath PutByValue"), "{text}");@@ -1610,7 +1635,7 @@ pub(crate) mod property_access {shape: None,..own(GetOwnProperty, 0x100, 1)};- let megamorphic = PropertyCacheSnapshot {+ let megamorphic = PropertyCache {kind: PropertyCacheKind::Megamorphic,entries: vec![own(GetOwnProperty, 0x100, 1)],};@@ -1690,19 +1715,17 @@ pub(crate) mod inlining {let mut snapshot = snapshot_for(caller, test_layout());snapshot.runtime.heap_region_offset_mask = (1 << 48) - 1;snapshot.executables[0].cell = CellId(0x100);- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(function.function),inline_executable: Some(1),..CallFeedbackSnapshot::default()- }];- let mut callee_snapshot = snapshot_for(callee, test_layout()).executables.remove(0);+ }]);+ add_program(&mut snapshot, callee, test_layout());+ let callee_snapshot = &mut snapshot.executables[1];callee_snapshot.cell = CellId(0x200);callee_snapshot.function = Some(function);callee_snapshot.supports_legacy_arguments = !function.strict;callee_snapshot.environment = Some(CellId(ENVIRONMENT));- snapshot.executables.push(callee_snapshot);- let callee_bytes = snapshot.executables[1].bytecode.as_ptr() as u64;- snapshot.executables[1].bytecode_address = callee_bytes;snapshot.options.inlining = InliningLimits {always_inlined_instructions: 10,max_construct_instructions: 50,@@ -1732,7 +1755,7 @@ pub(crate) mod inlining {/// The IR of `return a0.value` whose cache entries call getters that/// are closures of the callee `return this`.fn dump_getter_call(getters: &[u64], exit_sites: Vec<(u32, ExitKind)>) -> String {- use super::property_access::{cache, get_by_id, own};+ use super::property_access::{add_caches, cache, get_by_id, own};use crate::snapshot::{AccessorFunctionSnapshot, PropertyCacheEntrySnapshot, PropertyCacheEntryType};let program = assemble(|_| vec![get_by_id(r(5), a(0), 0), Instruction::Return { value: r(5) }]);let callee = assemble(|_| {@@ -1759,8 +1782,8 @@ pub(crate) mod inlining {..own(PropertyCacheEntryType::GetOwnProperty, 0x100 + 0x100 * index as u64, 0)}).collect();- snapshot.executables[0].property_caches = vec![cache(entries)];- snapshot.executables[0].exit_sites = exit_sites;+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &[cache(entries)]);+ snapshot.executables[0].exit_sites = snapshot.add(&exit_sites);dump(&optimized_graph(&snapshot), &test_layout())}@@ -1790,7 +1813,7 @@ pub(crate) mod inlining {#[test]fn inlined_legacy_arguments_use_eligibility_but_keep_closures_conservative() {- use super::property_access::{cache, get_by_id, own};+ use super::property_access::{add_caches, cache, get_by_id, own};use crate::snapshot::{AccessorFunctionSnapshot, PropertyCacheEntrySnapshot, PropertyCacheEntryType};let caller = assemble(|_| vec![get_by_id(r(5), a(0), 0), Instruction::Return { value: r(5) }]);let callee = assemble(|_| {@@ -1821,7 +1844,7 @@ pub(crate) mod inlining {..own(PropertyCacheEntryType::GetOwnProperty, 0x100 + index * 0x100, 0)}).collect();- snapshot.executables[0].property_caches = vec![cache(entries)];+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &[cache(entries)]);let graph = build_graph(&snapshot).unwrap();let frames = graph.frame_states@@ -2095,8 +2118,8 @@ pub(crate) mod inlining {});let mut snapshot = snapshot_with_callee(&caller, &callee, function(true, false));// The callee's Add never ran; the caller's did.- snapshot.executables[1].feedback.arith = vec![0];- snapshot.executables[0].feedback.arith = vec![0, 1];+ snapshot.executables[1].feedback.arith = snapshot.add(&[0]);+ snapshot.executables[0].feedback.arith = snapshot.add(&[0, 1]);assert_dump(&dump(&optimized_graph(&snapshot), &test_layout()),"@@ -2184,17 +2207,19 @@ pub(crate) mod inlining {snapshot.executables[1].cell = snapshot.executables[0].cell;for index in 1..=3 {if index > 1 {- snapshot.executables.push(snapshot.executables[1].clone());+ let copy = snapshot.executables[1];+ snapshot.add_executable(copy);}+ let calls = snapshot.add(&[CallFeedbackSnapshot {+ target: Some(CellId(CALLEE_FUNCTION + (index as u64 % 3) * 0x100)),+ inline_executable: Some((index % 3 + 1) as u32),+ ..CallFeedbackSnapshot::default()+ }]);let executable = &mut snapshot.executables[index];let function = executable.function.as_mut().unwrap();function.function = CellId(CALLEE_FUNCTION + (index as u64 - 1) * 0x100);executable.environment = Some(CellId(ENVIRONMENT + (index as u64 - 1) * 0x100));- executable.feedback.call = vec![CallFeedbackSnapshot {- target: Some(CellId(CALLEE_FUNCTION + (index as u64 % 3) * 0x100)),- inline_executable: Some((index % 3 + 1) as u32),- ..CallFeedbackSnapshot::default()- }];+ executable.feedback.call = calls;}let text = dump(&optimized_graph(&snapshot), &test_layout());assert_eq!(text.matches("CallSlowPath Call").count(), 1, "{text}");@@ -2219,7 +2244,7 @@ pub(crate) mod inlining {// A call target that already turned out wrong here.let mut snapshot = snapshot_with_callee(&caller(), &identity, function(true, false));- snapshot.executables[0].exit_sites = vec![(caller().offsets[1], ExitKind::BadCallTarget)];+ snapshot.executables[0].exit_sites = snapshot.add(&[(caller().offsets[1], ExitKind::BadCallTarget)]);assert!(!is_inlined(&snapshot));// Recursion, which inlines two levels deep.@@ -2228,7 +2253,7 @@ pub(crate) mod inlining {assert!(is_inlined(&snapshot));let mut snapshot = snapshot_with_callee(&caller(), &caller(), function(true, false));snapshot.executables[1].cell = snapshot.executables[0].cell;- snapshot.executables[1].feedback.call = snapshot.executables[0].feedback.call.clone();+ snapshot.executables[1].feedback.call = snapshot.executables[0].feedback.call;let recursive = dump(&optimized_graph(&snapshot), &test_layout());assert_eq!(recursive.matches("CallSlowPath Call").count(), 1, "{recursive}");// One check of the call target for each inlined level.@@ -2241,11 +2266,15 @@ pub(crate) mod inlining {// Mutual recursion of f and g, which inline each other until each runs in three frames.let mut snapshot = snapshot_with_callee(&caller(), &caller(), function(true, false));snapshot.options.inlining.max_depth = 10;- snapshot.executables[1].feedback.call = snapshot.executables[0].feedback.call.clone();- let mut g = snapshot.executables[1].clone();+ let call = snapshot[snapshot.executables[0].feedback.call][0];+ let mut g = snapshot.executables[1];g.cell = CellId(0x300);- snapshot.executables[1].feedback.call[0].inline_executable = Some(2);- snapshot.executables.push(g);+ g.feedback.call = snapshot.add(&[call]);+ snapshot.executables[1].feedback.call = snapshot.add(&[CallFeedbackSnapshot {+ inline_executable: Some(2),+ ..call+ }]);+ snapshot.add_executable(g);let mutual = dump(&optimized_graph(&snapshot), &test_layout());assert_eq!(mutual.matches("CallSlowPath Call").count(), 1, "{mutual}");assert!(mutual.contains("CallSlowPath Call @e2:"), "{mutual}");@@ -2330,6 +2359,7 @@ pub(crate) mod inlining {#[test]fn methods_loaded_as_constants_are_inlined_without_a_callee_check() {+ use crate::builder::tests::property_access::add_caches;use crate::builder::tests::property_access::cache;use crate::builder::tests::property_access::get_by_id;use crate::builder::tests::property_access::own;@@ -2350,7 +2380,7 @@ pub(crate) mod inlining {entry.prototype = Some(CellId(0x7000));entry.prototype_chain_validity = Some(CellId(0x7100));entry.prototype_property = Some(CellId(CALLEE_FUNCTION));- snapshot.executables[0].property_caches = vec![cache(vec![entry])];+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &[cache(vec![entry])]);let text = dump(&optimized_graph(&snapshot), &test_layout());// The method's load is checked; the call of it is not.assert_eq!(text.matches("CheckValue").count(), 1, "{text}");@@ -2359,6 +2389,7 @@ pub(crate) mod inlining {#[test]fn calls_forwarded_through_call_and_bound_functions_are_inlined() {+ use crate::builder::tests::property_access::add_caches;use crate::builder::tests::property_access::cache;use crate::builder::tests::property_access::get_by_id;use crate::builder::tests::property_access::own;@@ -2394,10 +2425,13 @@ pub(crate) mod inlining {entry.prototype_chain_validity = Some(CellId(0x7100));entry.prototype_property = Some(CellId(0x9000));entry.prototype_property_intrinsic = Some(Intrinsic::FunctionPrototypeCall);- snapshot.executables[0].property_caches = vec![cache(vec![entry])];- snapshot.executables[0].feedback.call[0].target = Some(CellId(0x9000));- snapshot.executables[0].feedback.call[0].inline_executable = None;- snapshot.executables[0].feedback.call[0].forwarded = Some(forwarded(Forwarding::Call));+ snapshot.executables[0].property_caches = add_caches(&mut snapshot, &[cache(vec![entry])]);+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].target = Some(CellId(0x9000));+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].inline_executable = None;+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].forwarded = Some(forwarded(Forwarding::Call));let text = dump(&optimized_graph(&snapshot), &test_layout());// The function `call` is called on is checked, and gets the second argument.assert!(text.contains("CheckValue 0xfff9000000005000 (v6)"), "{text}");@@ -2412,10 +2446,13 @@ pub(crate) mod inlining {]});let mut snapshot = snapshot_with_callee(&caller, &identity, function(true, false));- snapshot.executables[0].feedback.call[0].target = Some(CellId(0x9100));- snapshot.executables[0].feedback.call[0].inline_executable = None;- snapshot.executables[0].feedback.call[0].forwarded = Some(forwarded(Forwarding::Bound));- snapshot.executables[0].feedback.bound_arguments = vec![value::int32(7)];+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].target = Some(CellId(0x9100));+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].inline_executable = None;+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].forwarded = Some(forwarded(Forwarding::Bound));+ snapshot.executables[0].feedback.bound_arguments = snapshot.add(&[value::int32(7)]);let graph = optimized_graph(&snapshot);let text = dump(&graph, &test_layout());assert!(text.contains("CheckValue 0xfff9000000009100"), "{text}");@@ -2427,20 +2464,24 @@ pub(crate) mod inlining {let fifth = assemble(|_| vec![Instruction::Enter, Instruction::Return { value: fifth_argument }]);let mut snapshot = snapshot_with_callee(&caller, &fifth, function(true, false));snapshot.executables[1].layout.number_of_arguments = 5;- snapshot.executables[0].feedback.call[0].target = Some(CellId(0x9100));- snapshot.executables[0].feedback.call[0].inline_executable = None;+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].target = Some(CellId(0x9100));+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].inline_executable = None;let mut five = forwarded(Forwarding::Bound);five.bound_arguments_start = 2;five.bound_argument_count = 5;- snapshot.executables[0].feedback.call[0].forwarded = Some(five);- snapshot.executables[0].feedback.bound_arguments = (1..=8).map(value::int32).collect();+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].forwarded = Some(five);+ snapshot.executables[0].feedback.bound_arguments = snapshot.add(&(1..=8).map(value::int32).collect::<Vec<_>>());let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(text.contains("CheckValue 0xfff9000000009100"), "{text}");assert!(text.contains("Return (#7)"), "{text}");// Bound arguments past the end of the table are not inlined.five.bound_arguments_start = 4;- snapshot.executables[0].feedback.call[0].forwarded = Some(five);+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].forwarded = Some(five);let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(!text.contains("CheckValue 0xfff9000000009100"), "{text}");}@@ -2459,7 +2500,8 @@ pub(crate) mod inlining {};let identity = assemble(|_| vec![Instruction::Enter, Instruction::Return { value: a(0) }]);let mut snapshot = snapshot_with_callee(&caller(), &identity, function(true, false));- snapshot.executables[0].feedback.call[0].direct_call = Some(DirectCallTarget {+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].direct_call = Some(DirectCallTarget {function: function(true, false),..target});@@ -2467,8 +2509,10 @@ pub(crate) mod inlining {let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(!text.contains("CallDirect"), "{text}");- snapshot.executables[0].feedback.call[0].inline_executable = None;- snapshot.executables[0].feedback.call[0].direct_call = Some(target);+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].inline_executable = None;+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].direct_call = Some(target);let graph = optimized_graph(&snapshot);let text = dump(&graph, &test_layout());// NB: The callee, the `this` value (the sloppy callee reads it) and@@ -2491,8 +2535,10 @@ pub(crate) mod inlining {]});let mut many = snapshot_with_callee(&many_arguments, &identity, function(true, false));- many.executables[0].feedback.call[0].inline_executable = None;- many.executables[0].feedback.call[0].direct_call = Some(target);+ let calls = many.executables[0].feedback.call;+ many[calls][0].inline_executable = None;+ let calls = many.executables[0].feedback.call;+ many[calls][0].direct_call = Some(target);let text = dump(&optimized_graph(&many), &test_layout());let expected = format!("CallDirect @{} storing operands (v6, #0, #10, #10, #10, #10, #10, #10) [fs",@@ -2501,7 +2547,8 @@ pub(crate) mod inlining {assert!(text.contains(&expected), "{text}");// Without a target, the call is a call of the runtime's call helper.- snapshot.executables[0].feedback.call[0].direct_call = None;+ let calls = snapshot.executables[0].feedback.call;+ snapshot[calls][0].direct_call = None;let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(text.contains("CallSlowPath Call"), "{text}");}@@ -2510,6 +2557,7 @@ pub(crate) mod inlining {mod arguments {use super::*;use crate::builder::tests::inlining::call;+ use crate::builder::tests::property_access::add_caches;use crate::builder::tests::property_access::cache;use crate::builder::tests::property_access::get_by_id;use crate::builder::tests::property_access::own;@@ -2552,10 +2600,13 @@ mod arguments {apply.prototype_property = Some(CellId(0x7200));apply.prototype_property_intrinsic = Some(Intrinsic::FunctionPrototypeApply);let text = build(&program, |snapshot| {- snapshot.executables[0].property_caches = vec![- cache(vec![own(PropertyCacheEntryType::GetOwnProperty, 0x100, 0)]),- cache(vec![apply]),- ];+ snapshot.executables[0].property_caches = add_caches(+ snapshot,+ &[+ cache(vec![own(PropertyCacheEntryType::GetOwnProperty, 0x100, 0)]),+ cache(vec![apply]),+ ],+ );});assert!(text.contains("CallForwardingArguments"), "{text}");assert!(!text.contains("CreateArguments"), "{text}");@@ -2564,10 +2615,13 @@ mod arguments {let mut not_apply = apply;not_apply.prototype_property_intrinsic = None;let text = build(&program, |snapshot| {- snapshot.executables[0].property_caches = vec![- cache(vec![own(PropertyCacheEntryType::GetOwnProperty, 0x100, 0)]),- cache(vec![not_apply]),- ];+ snapshot.executables[0].property_caches = add_caches(+ snapshot,+ &[+ cache(vec![own(PropertyCacheEntryType::GetOwnProperty, 0x100, 0)]),+ cache(vec![not_apply]),+ ],+ );});assert!(text.contains("Generic CreateArguments"), "{text}");}@@ -2692,7 +2746,7 @@ fn dump_bitwise_or(feedback: u8) -> String {]});let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.arith = vec![feedback];+ snapshot.executables[0].feedback.arith = snapshot.add(&[feedback]);dump(&optimized_graph(&snapshot), &test_layout())}@@ -2735,7 +2789,7 @@ fn numeric_feedback_uses_number_guards_instead_of_type_dispatch() {]});let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::DOUBLE];+ snapshot.executables[0].feedback.arith = snapshot.add(&[crate::snapshot::arith_feedback::DOUBLE]);let graph = optimized_graph(&snapshot);let text = dump(&graph, &test_layout());assert_eq!(text.matches("CheckNumber").count(), 2, "{text}");@@ -2761,7 +2815,7 @@ fn captured_object_bindings_are_guarded_before_becoming_constants() {let mut snapshot = snapshot_for(&program, test_layout());let object = crate::snapshot::CellId(0x1234);let bits = value::tagged(value::OBJECT_TAG) | object.0;- snapshot.executables[0].captured_bindings.push((+ snapshot.executables[0].captured_bindings = snapshot.add(&[(coordinate,crate::snapshot::GlobalValueSnapshot {bits,@@ -2771,7 +2825,7 @@ fn captured_object_bindings_are_guarded_before_becoming_constants() {typed_array: None,has_instance: None,},- ));+ )]);let graph = optimized_graph(&snapshot);let text = dump(&graph, &test_layout());assert!(text.contains("LoadEnvironmentBinding 2"), "{text}");@@ -2779,7 +2833,7 @@ fn captured_object_bindings_are_guarded_before_becoming_constants() {assert!(text.contains(&format!("Return (#0x{bits:x})")), "{text}");assert!(graph.embedded_cells.contains(&object));- snapshot.executables[0].exit_sites.push((0, ExitKind::UnexpectedValue));+ snapshot.executables[0].exit_sites = snapshot.add(&[(0, ExitKind::UnexpectedValue)]);let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(text.contains("LoadEnvironmentBinding 2"), "{text}");assert!(!text.contains("CheckValue"), "{text}");@@ -2811,12 +2865,12 @@ fn captured_typed_arrays_use_guarded_fixed_lengths() {});let mut snapshot = snapshot_for(&program, test_layout());snapshot.runtime.layout.typed_array_kind_uint16 = 3;- snapshot.executables[0].feedback.keyed = vec![KeyedFeedbackSnapshot {+ snapshot.executables[0].feedback.keyed = snapshot.add(&[KeyedFeedbackSnapshot {bits: 1 | (1 << (9 + 3)),- }];+ }]);let object = crate::snapshot::CellId(0x1234);let bits = value::tagged(value::OBJECT_TAG) | object.0;- snapshot.executables[0].captured_bindings.push((+ snapshot.executables[0].captured_bindings = snapshot.add(&[(coordinate,GlobalValueSnapshot {bits,@@ -2829,7 +2883,7 @@ fn captured_typed_arrays_use_guarded_fixed_lengths() {fixed_length: Some(8),}),},- ));+ )]);let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(text.contains("CheckTypedArrayStorage"), "{text}");assert!(text.contains("LoadTypedArrayDataOffset"), "{text}");@@ -2837,7 +2891,8 @@ fn captured_typed_arrays_use_guarded_fixed_lengths() {assert!(!text.contains("CheckElements"), "{text}");assert!(!text.contains("CheckBounds"), "{text}");- snapshot.executables[0].captured_bindings[0]+ let captured_bindings = snapshot.executables[0].captured_bindings;+ snapshot[captured_bindings][0].1.typed_array.as_mut()@@ -2848,12 +2903,8 @@ fn captured_typed_arrays_use_guarded_fixed_lengths() {assert!(!text.contains("CheckTypedArrayStorage"), "{text}");assert!(!text.contains("CheckElements"), "{text}");- snapshot.executables[0].captured_bindings[0]- .1- .typed_array- .as_mut()- .unwrap()- .element = TypedArrayElement::Int8;+ let captured_bindings = snapshot.executables[0].captured_bindings;+ snapshot[captured_bindings][0].1.typed_array.as_mut().unwrap().element = TypedArrayElement::Int8;let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(text.contains("CheckElements TypedArray(Uint16)"), "{text}");}@@ -2873,14 +2924,14 @@ fn array_length_specialization_requires_monomorphic_receivers_and_exit_gates() {]});let mut snapshot = snapshot_for(&program, test_layout());- snapshot.executables[0].feedback.cache_value = vec![crate::snapshot::value_feedback::INT32];+ snapshot.executables[0].feedback.cache_value = snapshot.add(&[crate::snapshot::value_feedback::INT32]);for bits in [0,keyed_feedback_bits::OTHER_ELEMENTS,keyed_feedback_bits::MAGICAL_LENGTH | keyed_feedback_bits::OTHER_ELEMENTS,keyed_feedback_bits::MAGICAL_LENGTH,] {- snapshot.executables[0].feedback.keyed = vec![KeyedFeedbackSnapshot { bits }];+ snapshot.executables[0].feedback.keyed = snapshot.add(&[KeyedFeedbackSnapshot { bits }]);let text = dump(&optimized_graph(&snapshot), &test_layout());if bits == keyed_feedback_bits::MAGICAL_LENGTH {assert!(text.contains("CheckArray"), "{text}");@@ -2892,7 +2943,7 @@ fn array_length_specialization_requires_monomorphic_receivers_and_exit_gates() {}}for kind in [ExitKind::BadType, ExitKind::Overflow] {- snapshot.executables[0].exit_sites = vec![(0, kind)];+ snapshot.executables[0].exit_sites = snapshot.add(&[(0, kind)]);let text = dump(&optimized_graph(&snapshot), &test_layout());assert!(!text.contains("CheckArray"), "{text}");assert!(text.contains("CallSlowPath"), "{text}");@@ -2926,7 +2977,7 @@ mod globals {object: CellId(0x1000),declarative_environment: CellId(0x2000),environment_serial: 1,- caches: vec![cache],+ caches: snapshot.add(&[cache]),});dump(&optimized_graph(&snapshot), &test_layout())};diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rsindex bc44f35c5aa..e0332cb4e34 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs@@ -119,7 +119,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {&& info.named_properties_offset.is_multiple_of(8)&& info.shape_offset + 4 <= info.plain_inline_storage_offset&& info.inline_capacity_offset < info.plain_inline_storage_offset;- let size_class = info.size_class_for(reserve).copied().filter(|_| fields_fit);+ let size_class = info+ .size_class_for(self.snapshot, reserve)+ .copied()+ .filter(|_| fields_fit);let Some(size_class) = size_class else {self.masm.jump(entry);self.masm.bind(resume);@@ -127,7 +130,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {};let cell = self.output(node);- let info = self.runtime.object_allocation.clone();+ let info = self.runtime.object_allocation;let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);self.emit_check_heap_threshold(size_class.cell_size, cell, heap, entry);@@ -136,8 +139,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// The template, with the shape, the inline capacity and every inline// value undefined. The pointer to the inline storage is stored last.- let mut image = info- .template+ let mut image = self.snapshot[info.template].iter().flat_map(|word| word.to_le_bytes()).take(info.plain_inline_storage_offset as usize)@@ -233,7 +235,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_unbox_cell(scratch, parent);self.masm.move64(arguments[1], scratch);self.masm.move64(arguments[0], self.pinned.vm);- self.masm.move_imm64(arguments[2], self.executables[0].cell.0);+ self.masm.move_imm64(arguments[2], self.snapshot.executables[0].cell.0);self.masm.move_imm32(arguments[3], shape_cache);self.masm.move_imm32(arguments[4], capacity);self.masm.call_absolute(self.runtime.create_lexical_environment);@@ -427,16 +429,15 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// Larger arrays are rare, and filling their storage takes longer// than the runtime call.const MAX_INLINE_ELEMENTS: u32 = 64;- let info = self.runtime.array_allocation.clone();+ let info = self.runtime.array_allocation;let (entry, resume) = self.defer_allocation(node, AllocationCall::Array(count));// NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.let (storage, temp) = (self.temp(node, 0), self.temp(node, 1));- let storage_size_class = info- .storage_size_classes+ let storage_size_class = self.snapshot[info.storage_size_classes].iter().find(|size_class| size_class.capacity >= count).copied();- let objects = self.runtime.object_allocation.clone();+ let objects = self.runtime.object_allocation;let layout = self.runtime.layout;let template_bytes = 8 * info.template.len() as u64;let array_fields = [@@ -486,8 +487,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {);// The array, with its packed elements if it has any.- let mut image = info- .template+ let mut image = self.snapshot[info.template].iter().flat_map(|word| word.to_le_bytes()).collect::<Vec<u8>>();@@ -510,7 +510,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {if let Some(size_class) = storage_size_class {let mut fields: Vec<ConstantField> = (0u32..)- .zip(&info.storage_template)+ .zip(&self.snapshot[info.storage_template]).map(|(index, word)| (8 * index, 8, *word)).collect();for index in 0..size_class.capacity {@@ -550,11 +550,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {shape_cache: u32,capacity: u32,) -> Result<(), CompileFailure> {- let template = self.executables[0]- .lexical_environment_templates+ let template = self.snapshot[self.snapshot.executables[0].lexical_environment_templates].get(shape_cache as usize)- .and_then(Option::as_ref)- .cloned()+ .copied()+ .flatten().ok_or(CompileFailure::CodeGeneration)?;let (entry, resume) = self.defer_allocation(node, AllocationCall::Environment(shape_cache, capacity));// NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.@@ -579,7 +578,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_pop_free_list(template.allocator, environment, temp, entry);self.emit_count_allocation(template.cell_size, template.cell_size, temp, false);- let mut fields = template_fields(&template.words, &stored);+ let mut fields = template_fields(&self.snapshot[template.words], &stored);self.emit_constant_fields(environment, temp, &mut fields)?;if template.inline_binding_values {self.masm@@ -608,19 +607,21 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {shared_function_data_index: u32,) -> Result<(), CompileFailure> {let info = self.runtime.function_allocation;- let closure = self+ let closure_templates = self+ .snapshot.executables.get(executable as usize).ok_or(CompileFailure::CodeGeneration)?- .closure_templates+ .closure_templates;+ let closure = self.snapshot[closure_templates].get(shared_function_data_index as usize)- .and_then(Option::as_ref)- .cloned()+ .copied()+ .flatten().ok_or(CompileFailure::CodeGeneration)?;let (entry, resume) = self.defer_allocation(node, AllocationCall::Function(closure.sample));// NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.let (function, temp) = (self.temp(node, 0), self.temp(node, 1));- let objects = self.runtime.object_allocation.clone();+ let objects = self.runtime.object_allocation;let offsets = self.runtime.offsets;let stored = [(objects.named_properties_offset, 8),@@ -648,7 +649,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_pop_free_list(info.allocator, function, temp, entry);self.emit_count_allocation(info.cell_size, info.cell_size, temp, false);- let mut fields = template_fields(&closure.words, &stored);+ let mut fields = template_fields(&self.snapshot[closure.words], &stored);self.emit_constant_fields(function, temp, &mut fields)?;self.masm.load_effective_address(temp, &at(function, objects.inline_storage_offset));diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rsindex 8387e167e7b..d9937ba1df1 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs@@ -164,7 +164,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {registers: &super::InputRegisters,) -> Result<(), CompileFailure> {let invalid = |reason| CompileFailure::InvalidBytecode { pc, reason };- let snapshot = &self.executables[executable as usize];+ let snapshot = &self.snapshot.executables[executable as usize];let decoded = self.decoded(executable, pc)?;let Instruction::Call { call_feedback, .. } = decoded.instruction else {return Err(invalid("direct call of a non-Call instruction"));@@ -183,9 +183,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {};let target: DirectCallTarget = constant_target.or_else(|| {- snapshot- .feedback- .call+ self.snapshot[snapshot.feedback.call].get(usize::from(call_feedback)).and_then(|feedback| feedback.direct_call)})@@ -247,12 +245,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// A generic `Call`: through the dynamic call path, calling the `this`/// value directly if the site's single callee is `Function.prototype.call`.pub(super) fn emit_generic_js_call(&mut self, executable: u32, pc: u32) -> Result<(), CompileFailure> {- let snapshot = &self.executables[executable as usize];+ let snapshot = &self.snapshot.executables[executable as usize];let call_function = match self.decoded(executable, pc) {Ok(decoded) => match decoded.instruction {- Instruction::Call { call_feedback, .. } => snapshot- .feedback- .call+ Instruction::Call { call_feedback, .. } => self.snapshot[snapshot.feedback.call].get(usize::from(call_feedback)).and_then(|feedback| feedback.function_prototype_call_target()),_ => None,@@ -602,10 +598,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let (site, next_pc, dst, argument_count) = (&call.site, call.next_pc, call.dst, call.argument_count);let environment = match target.environment {Some(index) => Some(- self.executables[call.executable as usize]- .environment_templates+ self.snapshot[self.snapshot.executables[call.executable as usize].environment_templates].get(index as usize)- .cloned()+ .copied().ok_or(invalid("direct call without its environment template"))?,),None => None,@@ -1009,7 +1004,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {overwritten.push(template.this_value_offset);}let mut fields: Vec<ConstantField> = (0u32..)- .zip(&template.words)+ .zip(&self.snapshot[template.words]).map(|(index, word)| (8 * index, 8, *word)).filter(|(offset, _, _)| !overwritten.contains(offset)).collect();@@ -1145,7 +1140,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {input_registers: &super::InputRegisters,) -> Result<(), CompileFailure> {let invalid = |reason| CompileFailure::InvalidBytecode { pc, reason };- let snapshot = &self.executables[executable as usize];+ let snapshot = &self.snapshot.executables[executable as usize];let decoded = self.decoded(executable, pc)?;let stored_operands = crate::builder::js_call_operands(&decoded.instruction).inputs;let next_pc = decoded.next_pc();@@ -1160,9 +1155,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {else {return Err(invalid("native call of a non-Call instruction"));};- let target: NativeCallTarget = snapshot- .feedback- .call+ let target: NativeCallTarget = self.snapshot[snapshot.feedback.call].get(usize::from(call_feedback)).and_then(|feedback| feedback.native_call).ok_or(invalid("native call without a target"))?;@@ -1585,7 +1578,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {header: &FrameHeader,) -> Vec<ConstantField> {let offsets = self.runtime.offsets;- let snapshot = &self.executables[executable as usize];+ let snapshot = &self.snapshot.executables[executable as usize];let function_fields = snapshot.function_fields;let builtin = snapshot.builtin;let mut constants = Vec::new();@@ -1768,7 +1761,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {closure: Option<Gpr>,temps: [Gpr; 3],) -> Result<(), CompileFailure> {- let snapshot = &self.executables[executable as usize];+ let snapshot = &self.snapshot.executables[executable as usize];let function = snapshot.function.ok_or(CompileFailure::InvalidBytecode {pc: call_pc,reason: "inlined executable without a function",diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 275e69bc030..157f19a9fb6 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -47,6 +47,7 @@ use crate::ir::value;use crate::regalloc::Allocation;use crate::snapshot::COMPRESSED_POINTER_SHIFT;use crate::snapshot::RuntimeInfo;+use crate::snapshot::Snapshot;/// Where the stub keeps its inputs and what must survive calls into the/// runtime and the callee, relative to the stack pointer.@@ -102,6 +103,8 @@ pub fn generate_construct_stub<M: PortableMacroAssembler>(fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: bool) -> Result<Vec<u8>, CompileFailure> {let graph = Graph::default();let allocation = Allocation::default();+ // NB: A stub is code for no executable. It reads no list of the runtime info.+ let snapshot = Snapshot::new();let (_, pinned) = target_registers::<M>();let mut masm = M::new();let exit_stub = masm.new_label();@@ -111,7 +114,7 @@ fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: bomasm,graph: &graph,allocation: &allocation,- executables: &[],+ snapshot: &snapshot,runtime,stress: crate::snapshot::StressOptions::default(),pinned,@@ -186,7 +189,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {cell,} = registers;let layout = self.runtime.dynamic_calls;- let heap_info = self.runtime.object_allocation.clone();+ let heap_info = self.runtime.object_allocation;let scratch = self.pinned.scratch;let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);let environment_local = self.stub_local(local::ENVIRONMENT);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rsindex b4528d1753b..c7689c349d7 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs@@ -149,7 +149,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {) {let scratch = self.pinned.scratch;let output = self.output(node);- let rope = self.runtime.rope_allocation.clone();+ let rope = self.runtime.rope_allocation;let string_length = |string: Gpr| Address::new(string, rope.length_offset as i32);let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);@@ -189,7 +189,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_pop_free_list(rope.allocator, cell, other, no_free_cell);self.emit_count_allocation(rope.cell_size, rope.cell_size, other, false);- let mut fields = template_fields(&rope.template, &rope_stored_fields(&rope));+ let mut fields = template_fields(&self.snapshot[rope.template], &rope_stored_fields(&rope));self.emit_constant_fields(cell, other, &mut fields).expect("rope string fields are near the cell");self.masm.store32(&string_length(cell), length);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 0b20c6ec306..3b7246f0ea8 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -114,6 +114,7 @@ use crate::snapshot::COMPRESSED_POINTER_SHIFT;use crate::snapshot::CellId;use crate::snapshot::ExecutableSnapshot;use crate::snapshot::RuntimeInfo;+use crate::snapshot::Snapshot;use crate::snapshot::StressOptions;use sites::SiteSource;@@ -271,8 +272,9 @@ struct Codegen<'a, M: PortableMacroAssembler> {masm: M,graph: &'a Graph,allocation: &'a Allocation,- /// `Snapshot::executables`; index 0 is the compiled function.- executables: &'a [ExecutableSnapshot],+ /// What the graph was built from. Executable 0 is the compiled function.+ snapshot: &'a Snapshot,+ /// The runtime info of the snapshot.runtime: &'a RuntimeInfo,stress: StressOptions,pinned: PinnedRegisters,@@ -421,9 +423,7 @@ struct LeaveStub {pub fn generate<M: PortableMacroAssembler>(graph: &Graph,allocation: &Allocation,- executables: &[ExecutableSnapshot],- runtime: &RuntimeInfo,- stress: StressOptions,+ snapshot: &Snapshot,verify: bool,scratch: &mut Scratch,) -> Result<GeneratedCode, CompileFailure> {@@ -443,9 +443,9 @@ pub fn generate<M: PortableMacroAssembler>(masm,graph,allocation,- executables,- runtime,- stress,+ snapshot,+ runtime: &snapshot.runtime,+ stress: snapshot.options.stress,pinned,frame: M::frame(GprSet::EMPTY, FprSet::EMPTY, 0),locals: Locals::default(),@@ -932,11 +932,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// The instruction at `pc` of executable `executable`.fn decoded(&self, executable: u32, pc: u32) -> Result<DecodedInstruction, CompileFailure> {- decode_instruction(&self.executables[executable as usize].bytecode, pc).map_err(|_| {- CompileFailure::InvalidBytecode {- pc,- reason: "undecodable instruction",- }+ let bytecode = &self.snapshot[self.snapshot.executables[executable as usize].bytecode];+ decode_instruction(bytecode, pc).map_err(|_| CompileFailure::InvalidBytecode {+ pc,+ reason: "undecodable instruction",})}@@ -953,8 +952,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// The byte at `offset` in the instruction at `pc` of executable `executable`.fn read_u8(&self, executable: u32, pc: u32, offset: u32) -> Result<u8, CompileFailure> {let at = (pc + offset) as usize;- let byte = self.executables[executable as usize]- .bytecode+ let byte = self.snapshot[self.snapshot.executables[executable as usize].bytecode].get(at).ok_or(CompileFailure::InvalidBytecode {pc,@@ -2367,7 +2365,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_publish_frame();// Up to this many registers and locals are emptied with one store per two slots, more in a loop.const UNROLLED_SLOTS: u32 = 64;- let layout = self.executables[0].layout;+ let layout = self.snapshot.executables[0].layout;let slots = self.runtime.offsets.execution_context_slots;let first = crate::bytecode::RESERVED_REGISTER_COUNT;let mut fields: Vec<call::ConstantField> = Vec::new();@@ -2388,7 +2386,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {fields.push((slots + 8 * index, 8, value::EMPTY));}}- for (index, constant) in (0..).zip(&self.executables[0].constants) {+ for (index, constant) in (0..).zip(&self.snapshot[self.snapshot.executables[0].constants]) {fields.push((slots + 8 * (layout.constants_base() + index), 8, *constant));}fields.push((self.runtime.offsets.execution_context_frame_initialized, 1, 1));@@ -2765,7 +2763,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}}- let frame_layout = self.executables[executable as usize].layout;+ let frame_layout = self.snapshot.executables[executable as usize].layout;let ssa_outputs = outputs.into_iter().filter(|operand| {@@ -3099,7 +3097,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let record = self.local_address(self.locals.record);self.masm.load_effective_address(arguments[3], &record);}- let instruction = self.executables[executable as usize]+ let instruction = self.snapshot.executables[executable as usize].bytecode_address.checked_add(u64::from(pc)).ok_or(CompileFailure::InvalidBytecode {@@ -3384,8 +3382,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.expect("a frame state chain is not empty");let pc = self.graph.frame_state(root).pc;// NB: Handler ranges do not overlap.- let Some(handler) = self.executables[0]- .exception_handlers+ let Some(handler) = self.snapshot[self.snapshot.executables[0].exception_handlers].iter().find(|handler| handler.start_offset <= pc && pc < handler.end_offset)else {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rsindex 58f46756443..7a4965a6917 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs@@ -68,8 +68,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {&& info.storage_values_offset as usize == 8 * info.storage_template.len()&& info.storage_capacity_offset + 8 == info.storage_values_offset&& i64::from(self.runtime.layout.named_properties_capacity) == -8- && info- .storage_size_classes+ && self.snapshot[info.storage_size_classes].iter().all(|size_class| size_class.cell_size == info.storage_values_offset + 8 * size_class.capacity)}@@ -144,8 +143,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Architecture::X86_64 => 8,Architecture::AArch64 => 0,};- let info = self.runtime.array_allocation.clone();- let objects = self.runtime.object_allocation.clone();+ let info = self.runtime.array_allocation;+ let objects = self.runtime.object_allocation;let offsets = self.runtime.offsets;let scratch = self.pinned.scratch;let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);@@ -184,7 +183,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// kind, which must be a cell's: malloc storage is freed when// replaced.let capacity_offset = self.runtime.layout.named_properties_capacity;- let cell_kind = info.storage_template[info.storage_capacity_offset as usize / 8] >> 32;+ let cell_kind = self.snapshot[info.storage_template][info.storage_capacity_offset as usize / 8] >> 32;self.masm.load32(old_capacity, &Address::new(storage, capacity_offset));self.masm.load32(scratch, &Address::new(storage, capacity_offset + 4));self.masm@@ -202,7 +201,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.move32(capacity, scratch);self.masm.bind(at_least_needed);let found = self.masm.new_label();- for size_class in &info.storage_size_classes {+ let snapshot = self.snapshot;+ for size_class in &snapshot[info.storage_size_classes] {let next = self.masm.new_label();self.masm.branch32_imm(Condition::Above, capacity, size_class.capacity as i32, next);@@ -233,7 +233,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}// The header, then the values: undefined beyond the old ones.- for (index, word) in info.storage_template.iter().enumerate() {+ for (index, word) in snapshot[info.storage_template].iter().enumerate() {self.masm.store_imm64(&at(cell, 8 * index as u32), *word);}self.masm.store32(&at(cell, info.storage_capacity_offset), capacity);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rsindex 5e29b4f304f..5119a0d7268 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs@@ -288,8 +288,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let not_polymorphic = self.masm.new_label();self.property_cache_address(entry, executable, cache_index)?;self.masm.load64(entry, &Address::new(entry, 0));- let was_megamorphic = self.executables[executable as usize]- .property_caches+ let was_megamorphic = self.snapshot[self.snapshot.executables[executable as usize].property_caches].get(cache_index as usize).is_some_and(|cache| cache.kind == PropertyCacheKind::Megamorphic);if was_megamorphic {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rsindex d46021ede16..9b8447c87b2 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs@@ -128,7 +128,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let running = self.frame_field(self.runtime.offsets.execution_context_executable);self.masm.load64(dst, &running);} else {- self.masm.move_imm64(dst, self.executables[executable as usize].cell.0);+ self.masm+ .move_imm64(dst, self.snapshot.executables[executable as usize].cell.0);}self.masm.load64(dst,@@ -163,8 +164,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_load_compressed_cell(shape, &Address::new(object, self.runtime.offsets.object_shape as i32));self.property_cache_address(entry, executable, cache_index)?;self.masm.load64(entry, &Address::new(entry, 0));- let was_megamorphic = self.executables[executable as usize]- .property_caches+ let was_megamorphic = self.snapshot[self.snapshot.executables[executable as usize].property_caches].get(cache_index as usize).is_some_and(|cache| cache.kind == PropertyCacheKind::Megamorphic);if was_megamorphic {@@ -366,7 +366,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let base = self.input(node, 0);self.masm.shr64_imm(scratch, base, value::TAG_SHIFT);- let snapshot = &self.executables[executable as usize];+ let snapshot = &self.snapshot.executables[executable as usize];let prototypes = [(value::STRING_TAG, snapshot.string_prototype),(value::INT32_TAG, snapshot.number_prototype),@@ -467,12 +467,15 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// shapes than their hash tables hold, so their accesses also look in/// the VM's keyed caches.fn megamorphic_cache_name(&self, executable: u32, cache_index: u32, property: u32) -> Option<u64> {- let snapshot = &self.executables[executable as usize];- snapshot- .property_caches+ let snapshot = &self.snapshot.executables[executable as usize];+ self.snapshot[snapshot.property_caches].get(cache_index as usize).filter(|cache| cache.kind == PropertyCacheKind::Megamorphic)- .and_then(|_| snapshot.property_key_names.get(property as usize).copied())+ .and_then(|_| {+ self.snapshot[snapshot.property_key_names]+ .get(property as usize)+ .copied()+ }).filter(|name| *name != 0)}@@ -964,7 +967,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.store64(&self.local_address(record + 8), source);self.masm.load_effective_address(arguments[3], &self.local_address(record));- let instruction = self.executables[executable as usize]+ let instruction = self.snapshot.executables[executable as usize].bytecode_address.checked_add(u64::from(pc)).ok_or(CompileFailure::InvalidBytecode {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rsindex 13921c459f4..1817d890e66 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs@@ -95,7 +95,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let compiled_code_writes_headers = saved.len() >= 5&& chain[..pushed].iter().all(|id| {let frame_state = self.graph.frame_state(*id);- let arguments_base = self.executables[frame_state.executable as usize]+ let arguments_base = self.snapshot.executables[frame_state.executable as usize].layout.arguments_base();frame_state.values.iter().all(|(slot, value)| {@@ -292,7 +292,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let (caller, _) = &frames[level + 1];let (callee, values) = &frames[level];let call = self.decoded(caller.executable, caller.pc)?;- let callee_function = self.executables[callee.executable as usize]+ let callee_function = self.snapshot.executables[callee.executable as usize].function.map(|function| function.function);let (argument_count, construct) = match call.instruction {@@ -371,7 +371,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {if level + 1 == frames.len() {continue;}- let arguments_base = self.executables[frames[level].0.executable as usize]+ let arguments_base = self.snapshot.executables[frames[level].0.executable as usize].layout.arguments_base();for &(slot, location, repr) in &frames[level].1 {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex dcddca357df..4a3a5689726 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -930,12 +930,12 @@ impl Machine {state.bytecodes = snapshot.executables.iter()- .map(|executable| executable.bytecode.clone())+ .map(|executable| snapshot[executable.bytecode].to_vec()).collect();state.constants = snapshot.executables.iter()- .map(|executable| executable.constants.clone())+ .map(|executable| snapshot[executable.constants].to_vec()).collect();state.layouts = snapshot.executables@@ -985,7 +985,7 @@ fn compile_program_with() -> (Snapshot, CompiledCode) {let mut snapshot = crate::builder::tests::snapshot_for(program, layout);snapshot.runtime = runtime();- snapshot.executables[0].feedback.arith = vec![NUMBERS_AND_STRINGS_FEEDBACK];+ snapshot.executables[0].feedback.arith = snapshot.add(&[NUMBERS_AND_STRINGS_FEEDBACK]);configure(&mut snapshot);let never_ran_pcs = never_ran.iter()@@ -1198,7 +1198,7 @@ mod execution {assert_eq!(pc, program.offsets[back_edge]);// The interpreter ran Enter and five iterations of the loop.let mut machine = Machine::new(test_layout(), &[value::int32(10)]);- for (index, constant) in snapshot.executables[0].constants.iter().enumerate() {+ for (index, constant) in snapshot[snapshot.executables[0].constants].iter().enumerate() {machine.frame[FRAME_HEADER_WORDS + c(index as u32).raw() as usize] = *constant;}for index in crate::bytecode::RESERVED_REGISTER_COUNT..test_layout().registers_and_locals_count {@@ -1252,7 +1252,7 @@ mod execution {assert_eq!(pc, program.offsets[7]);// The interpreter ran five iterations.let mut machine = Machine::new(test_layout(), &[value::int32(10)]);- for (index, constant) in snapshot.executables[0].constants.iter().enumerate() {+ for (index, constant) in snapshot[snapshot.executables[0].constants].iter().enumerate() {machine.frame[FRAME_HEADER_WORDS + c(index as u32).raw() as usize] = *constant;}for index in crate::bytecode::RESERVED_REGISTER_COUNT..test_layout().registers_and_locals_count {@@ -1359,7 +1359,7 @@ mod execution {assert_eq!(pc, program.offsets[8]);// The interpreter ran five iterations of the inner loop.let mut machine = Machine::new(test_layout(), &[value::int32(10)]);- for (index, constant) in snapshot.executables[0].constants.iter().enumerate() {+ for (index, constant) in snapshot[snapshot.executables[0].constants].iter().enumerate() {machine.frame[FRAME_HEADER_WORDS + c(index as u32).raw() as usize] = *constant;}for index in crate::bytecode::RESERVED_REGISTER_COUNT..test_layout().registers_and_locals_count {@@ -1670,7 +1670,7 @@ mod execution {(value::int32(1), value::FALSE),] {let (snapshot, compiled) = compile_program_with(&program, test_layout(), &[], |snapshot| {- fake_heap::use_in(&mut snapshot.runtime)+ fake_heap::use_in(&mut snapshot.runtime);});let mut machine = Machine::new(test_layout(), &[argument]);machine.frame[1] = lexical_environment.as_ptr() as u64;@@ -1985,7 +1985,12 @@ mod execution {let mut machine = Machine::new(layout, &arguments);let environment = [0u64; 2];machine.frame[1] = environment.as_ptr() as u64;- let expected = run_reference(&program, &machine, &snapshot.executables[0].constants, &never_ran_pcs);+ let expected = run_reference(+ &program,+ &machine,+ &snapshot[snapshot.executables[0].constants],+ &never_ran_pcs,+ );if expected == ReferenceEnd::OutOfFuel {continue;}@@ -2026,6 +2031,7 @@ mod execution {#[test]fn random_programs_with_property_access_match_a_reference_interpreter() {+ use crate::builder::tests::property_access::add_caches;use crate::builder::tests::property_access::cache;use crate::builder::tests::property_access::own;use crate::regalloc::tests::ProgramGenerator;@@ -2091,7 +2097,7 @@ mod execution {let arguments = [argument(), argument()];let (snapshot, compiled) = compile_program_with(&program, layout, &[], |snapshot| {- snapshot.executables[0].property_caches = caches.clone();+ snapshot.executables[0].property_caches = add_caches(snapshot, &caches);});let mut machine = Machine::new(layout, &arguments);let environment = [0u64; 2];@@ -2105,8 +2111,13 @@ mod execution {// know, so code relying on stale shape facts would misbehave.call_toggles: toggles.then(|| (shape(0), shape(2))),};- let expected =- run_reference_with_heap(&program, &machine, &snapshot.executables[0].constants, &[], &mut heap);+ let expected = run_reference_with_heap(+ &program,+ &machine,+ &snapshot[snapshot.executables[0].constants],+ &[],+ &mut heap,+ );if expected == ReferenceEnd::OutOfFuel {continue;}@@ -2146,7 +2157,7 @@ mod execution {&program,&machine,machine.program_counter(),- &snapshot.executables[0].constants,+ &snapshot[snapshot.executables[0].constants],&[],&mut resumed_heap,);@@ -2475,10 +2486,11 @@ fn slow_paths_share_initialization_of_large_frames() {});let mut snapshot = crate::builder::tests::snapshot_for(&program, layout);snapshot.runtime = runtime();- snapshot.executables[0].constants = (0..layout.number_of_constants)+ let constants = (0..layout.number_of_constants).map(|index| 0x1234_5678_9abc_0000 | u64::from(index))- .collect();- snapshot.executables[0].feedback.arith = vec![1 | 1 << 1 | 1 << 2 | 1 << 3];+ .collect::<Vec<_>>();+ snapshot.executables[0].constants = snapshot.add(&constants);+ snapshot.executables[0].feedback.arith = snapshot.add(&[1 | 1 << 1 | 1 << 2 | 1 << 3]);snapshot.options.dump_asm = true;let aarch64 =compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())@@ -2544,7 +2556,7 @@ fn x86_64_shifts_find_their_amount_in_cl() {});let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());snapshot.runtime = runtime();- snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 2];+ snapshot.executables[0].feedback.arith = snapshot.add(&[crate::snapshot::arith_feedback::INT32; 2]);let compiled =compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();@@ -2601,6 +2613,8 @@ fn missing_slow_paths_fail_compilation_cleanly() {#[cfg(target_arch = "x86_64")]mod property_access {use super::*;+ use crate::builder::tests::property_access::PropertyCache;+ use crate::builder::tests::property_access::add_caches;use crate::builder::tests::property_access::cache;use crate::builder::tests::property_access::get_by_id;use crate::builder::tests::property_access::own;@@ -2610,7 +2624,6 @@ mod property_access {use crate::snapshot::PropertyCacheEntryType::ChangeOwnProperty;use crate::snapshot::PropertyCacheEntryType::GetOwnProperty;use crate::snapshot::PropertyCacheEntryType::GetPropertyInPrototypeChain;- use crate::snapshot::PropertyCacheSnapshot;/// A fake cell, in the low fake heap so that objects can have it as/// their compressed shape.@@ -2657,13 +2670,13 @@ mod property_access {fn run_with_caches(program: &Program,- caches: Vec<PropertyCacheSnapshot>,+ caches: Vec<PropertyCache>,argument: u64,call_writes: Option<(*mut u64, u64)>,) -> (JitResult, Machine, CompiledCode) {let layout = test_layout();let (snapshot, compiled) = compile_program_with(program, layout, &[], |snapshot| {- snapshot.executables[0].property_caches = caches;+ snapshot.executables[0].property_caches = add_caches(snapshot, &caches);});let mut machine = Machine::new(layout, &[argument]);machine.state.borrow_mut().call_writes = call_writes;@@ -2883,7 +2896,7 @@ mod property_access {entry.prototype_property_intrinsic = Some(Intrinsic::ArrayPrototypePush);let layout = test_layout();let (snapshot, compiled) = compile_program_with(&program, layout, &[], |snapshot| {- snapshot.executables[0].property_caches = vec![cache(vec![entry])];+ snapshot.executables[0].property_caches = add_caches(snapshot, &[cache(vec![entry])]);let runtime = &mut snapshot.runtime;runtime.array_push = grow as *const () as u64;runtime.array_prototype = CellId(self.array_prototype.address());@@ -3043,6 +3056,7 @@ mod property_access {#[test]fn aarch64_property_access_disassembles() {+ use crate::builder::tests::property_access::add_caches;use crate::builder::tests::property_access::cache;use crate::builder::tests::property_access::get_by_id;use crate::builder::tests::property_access::own;@@ -3067,11 +3081,14 @@ fn aarch64_property_access_disassembles() {prototype_entry.prototype_chain_validity = Some(CellId(0x2_0000_2000));prototype_entry.shape_dictionary_generation = 9;prototype_entry.shape_is_dictionary = true;- snapshot.executables[0].property_caches = vec![- cache(vec![own(GetOwnProperty, 0x1000, 1), own(GetOwnProperty, 0x2000, 4)]),- cache(vec![prototype_entry]),- cache(vec![own(ChangeOwnProperty, 0x3000, 2)]),- ];+ snapshot.executables[0].property_caches = add_caches(+ &mut snapshot,+ &[+ cache(vec![own(GetOwnProperty, 0x1000, 1), own(GetOwnProperty, 0x2000, 4)]),+ cache(vec![prototype_entry]),+ cache(vec![own(ChangeOwnProperty, 0x3000, 2)]),+ ],+ );let compiled =compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();@@ -3155,8 +3172,9 @@ mod inlining {function.function = CellId(function_object.as_ptr() as u64);let mut snapshot = snapshot_with_callee(caller, callee, function);snapshot.runtime = runtime();- for executable in &mut snapshot.executables {- executable.feedback.arith = vec![NUMBERS_AND_STRINGS_FEEDBACK];+ let arith = snapshot.add(&[NUMBERS_AND_STRINGS_FEEDBACK]);+ for executable in snapshot.executables.iter_mut() {+ executable.feedback.arith = arith;// 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],@@ -3275,7 +3293,10 @@ mod inlining {&caller(),&callee,|function| function,- |snapshot| snapshot.executables[1].constants[0] = value::int32(5),+ |snapshot| {+ let constants = snapshot.executables[1].constants;+ snapshot[constants][0] = value::int32(5);+ },|_| {},);assert_eq!(result, returned(value::int32(25)));@@ -3337,7 +3358,7 @@ mod inlining {&caller(),&twice(),|function| function,- |snapshot| snapshot.executables[1].feedback.arith = vec![0],+ |snapshot| snapshot.executables[1].feedback.arith = snapshot.add(&[0]),|_| {},);assert_eq!(result.status, RESUME);@@ -3681,11 +3702,11 @@ mod direct_calls {fn compile_caller(target: DirectCallTarget) -> (Snapshot, CompiledCode) {compile_program_with(&caller(), caller_layout(), &[], |snapshot| {- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(target.function.function),direct_call: Some(target),..CallFeedbackSnapshot::default()- }];+ }]);})}@@ -3902,27 +3923,29 @@ mod direct_calls {FreeCell::NeverAllocated => vec![0, address, address + 14 * 8, 14 * 8],FreeCell::None => vec![0, 0, 0, 14 * 8],};- let template = crate::snapshot::EnvironmentTemplateSnapshot {- allocator: free_list.as_mut_ptr() as u64,+ let allocator = free_list.as_mut_ptr() as u64;+ let template = |snapshot: &mut Snapshot| crate::snapshot::EnvironmentTemplateSnapshot {+ allocator,cell_size: 14 * 8,- words: (0..12).map(|index| 0x1000 + index).collect(),+ words: snapshot.add(&(0..12).map(|index| 0x1000 + index).collect::<Vec<_>>()),inline_binding_values: true,binding_values_offset: 48,binds_this: true,this_value_offset: 72,- cells: vec![CellId(0xcafe)],+ cells: snapshot.add(&[CellId(0xcafe)]),};let target = DirectCallTarget {environment: Some(0),..callee.target(true, true)};let (snapshot, compiled) = compile_program_with(&caller(), caller_layout(), &[], |snapshot| {- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(target.function.function),direct_call: Some(target),..CallFeedbackSnapshot::default()- }];- snapshot.executables[0].environment_templates = vec![template.clone()];+ }]);+ let template = template(snapshot);+ snapshot.executables[0].environment_templates = snapshot.add(&[template]);let allocation = &mut snapshot.runtime.object_allocation;allocation.heap = heap.as_mut_ptr() as u64;allocation.heap_allocated_bytes_offset = 0;@@ -4139,12 +4162,12 @@ mod direct_calls {fn run_dynamic(callee: &mut DynamicCallee, arguments: &[u64], through_call: bool) -> (JitResult, Machine) {let (snapshot, compiled) = compile_program_with(&caller(), caller_layout(), &[], |snapshot| {dynamic_runtime(&mut snapshot.runtime, &callee);- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(CellId(CALL_FUNCTION)),flags: if through_call { 0 } else { 1 },target_intrinsic: through_call.then_some(crate::snapshot::Intrinsic::FunctionPrototypeCall),..CallFeedbackSnapshot::default()- }];+ }]);});let mut machine = Machine::new(caller_layout(), arguments);let stack = callee.callee.interpreter_stack.as_mut_ptr() as u64;@@ -4304,11 +4327,11 @@ mod direct_calls {snapshot.runtime.dynamic_calls.prepare_call_environment =prepare_call_environment as *const () as u64;install_call_stub(&mut snapshot.runtime);- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(CellId(CALL_FUNCTION)),flags: 1,..CallFeedbackSnapshot::default()- }];+ }]);});let mut machine = Machine::new(caller_layout(), &arguments);let stack = callee.callee.interpreter_stack.as_mut_ptr() as u64;@@ -4427,11 +4450,11 @@ mod direct_calls {allocation.local_end_offset = 16;allocation.local_cell_size_offset = 24;install_call_stub(&mut snapshot.runtime);- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(CellId(CALL_FUNCTION)),flags: 1,..CallFeedbackSnapshot::default()- }];+ }]);});let mut machine = Machine::new(caller_layout(), &arguments);let stack = callee.callee.interpreter_stack.as_mut_ptr() as u64;@@ -4600,12 +4623,12 @@ mod direct_calls {layout.native_function_table_entry_size = 16;layout.native_function_table_entry_function = 0;install_call_stub(&mut snapshot.runtime);- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(CellId(CALL_FUNCTION)),flags: if through_call { 0 } else { 1 },target_intrinsic: through_call.then_some(crate::snapshot::Intrinsic::FunctionPrototypeCall),..CallFeedbackSnapshot::default()- }];+ }]);});let mut machine = Machine::new(caller_layout(), &arguments);let stack = callee.callee.interpreter_stack.as_mut_ptr() as u64;@@ -4687,11 +4710,11 @@ fn aarch64_direct_calls_disassemble() {environment: None,closures: false,};- snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[CallFeedbackSnapshot {target: Some(target.function.function),direct_call: Some(target),..CallFeedbackSnapshot::default()- }];+ }]);let compiled =compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex f4d580d372d..f439e90fcca 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -213,9 +213,11 @@ fn argument(index: u32) -> Operand {Operand::from_raw(layout().arguments_base() + index)}-fn marker_runtime() -> RuntimeInfo {+/// Gives `snapshot` the runtime of the tests, with slow paths that leave a marker.+fn set_marker_runtime(snapshot: &mut Snapshot) {use OpCode as O;let mut runtime = runtime();+ runtime.object_allocation.template = snapshot.add(&[PLAIN_OBJECT_CLASS]);let mut set =|opcode: OpCode, address: u64| std::sync::Arc::make_mut(&mut runtime.slow_paths)[opcode as usize] = address;for opcode in [@@ -320,12 +322,11 @@ fn marker_runtime() -> RuntimeInfo {runtime.object_allocation.plain_inline_storage_offset = 64;runtime.object_allocation.inline_capacity_offset = 40;runtime.offsets.shape_dictionary_generation = 84;- runtime.object_allocation.template = vec![PLAIN_OBJECT_CLASS];runtime.dynamic_calls.object_flag_is_ecmascript_function = FLAG_IS_ECMASCRIPT_FUNCTION;for opcode in [O::Increment, O::Decrement, O::PostfixIncrement, O::PostfixDecrement] {set(opcode, marker_record as *const () as u64);}- runtime+ snapshot.runtime = runtime;}/// Compiles `program` with the marker slow paths and runs it with `arguments`.@@ -346,8 +347,8 @@ fn run_program_with_snapshot(fn compile_program(program: &Program, prepare_snapshot: impl FnOnce(&mut Snapshot)) -> (Snapshot, CompiledCode) {let mut snapshot = crate::builder::tests::snapshot_for(program, layout());- snapshot.runtime = marker_runtime();- snapshot.executables[0].feedback.arith = vec![GENERAL_FEEDBACK];+ set_marker_runtime(&mut snapshot);+ snapshot.executables[0].feedback.arith = snapshot.add(&[GENERAL_FEEDBACK]);prepare_snapshot(&mut snapshot);let compiled = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap_or_else(|failure| panic!("compilation failed: {failure:?}"));@@ -393,7 +394,7 @@ fn compile_instruction(feedback: u8, instruction: Instruction) -> impl Fn(&[u64]]});let (snapshot, compiled) = compile_program(&program, |snapshot| {- snapshot.executables[0].feedback.arith = vec![feedback]+ snapshot.executables[0].feedback.arith = snapshot.add(&[feedback]);});move |arguments| instruction_result(run_compiled_program(&snapshot, &compiled, arguments, |_| {}))}@@ -704,7 +705,7 @@ fn double_operations_on_values_that_die_at_them() {]});let (snapshot, compiled) = compile_program(&program, |snapshot| {- snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::DOUBLE; 4];+ snapshot.executables[0].feedback.arith = snapshot.add(&[crate::snapshot::arith_feedback::DOUBLE; 4]);});let numbers = [0.5, -1.25, 3.0, 1e300, -0.0, f64::INFINITY, f64::NAN, 7.75];for lhs in numbers {@@ -851,7 +852,7 @@ fn updates() {let (result, _) = run_program_with_snapshot(program,&[value, value::UNDEFINED],- |snapshot| snapshot.executables[0].feedback.arith = vec![feedback],+ |snapshot| snapshot.executables[0].feedback.arith = snapshot.add(&[feedback]),|_| {},);if result.status == crate::code::JitStatus::Resume as u64 {@@ -1686,12 +1687,12 @@ fn typed_array_accesses_with_constant_indices() {&program,&[object_value(&array), value::int32(77)],|snapshot| {- let executable = &mut snapshot.executables[0];- executable.constants[1] = value::int32(index);- executable.feedback.keyed = vec![KeyedFeedbackSnapshot {+ let constants = snapshot.executables[0].constants;+ snapshot[constants][1] = value::int32(index);+ snapshot.executables[0].feedback.keyed = snapshot.add(&[KeyedFeedbackSnapshot {bits: keyed_feedback_bits::INT32_INDEX| 1 << (keyed_feedback_bits::TYPED_ARRAY_SHIFT + u32::from(kind)),- }];+ }]);},|_| {},);@@ -1898,7 +1899,7 @@ fn property_iterator_next(receiver: u64, keys: u64, cursor: u64) -> (u64, u64, ulet (result, machine) = run_program_with_snapshot(&program,&[receiver, keys, cursor],- |snapshot| snapshot.executables[0].exit_sites = vec![(pc, ExitKind::SlowPath)],+ |snapshot| snapshot.executables[0].exit_sites = snapshot.add(&[(pc, ExitKind::SlowPath)]),|_| {},);assert_eq!(result.status, RETURNED);@@ -2073,12 +2074,12 @@ fn run_with_environments(let exit_sites = exits.iter().map(|(index, kind)| (program.offsets[*index], *kind))- .collect();+ .collect::<Vec<_>>();let (result, machine) = run_program_with_snapshot(&program,arguments,|snapshot| {- snapshot.executables[0].exit_sites = exit_sites;+ snapshot.executables[0].exit_sites = snapshot.add(&exit_sites);super::fake_heap::use_in(&mut snapshot.runtime);},|machine| {@@ -2262,7 +2263,7 @@ fn create_variable() {&program,&[],|snapshot| {- snapshot.executables[0].identifiers = NAMES.to_vec();+ snapshot.executables[0].identifiers = snapshot.add(&NAMES);super::fake_heap::use_in(&mut snapshot.runtime);},|machine| {@@ -2477,18 +2478,19 @@ fn run_with_global_cache(Instruction::Return { value: r(5) },]});- let snapshot_globals = crate::snapshot::GlobalsSnapshot {- object: crate::snapshot::CellId(globals.object.as_ptr() as u64),- declarative_environment: crate::snapshot::CellId(globals.environment.address()),- environment_serial: serial,- caches: vec![None, Some(cache)],- };// NB: The code accesses the global variables directly, without the// realm or the executable's caches.let (result, _) = run_program_with_snapshot(&program,arguments,- |snapshot| snapshot.executables[0].globals = Some(snapshot_globals),+ |snapshot| {+ snapshot.executables[0].globals = Some(crate::snapshot::GlobalsSnapshot {+ object: crate::snapshot::CellId(globals.object.as_ptr() as u64),+ declarative_environment: crate::snapshot::CellId(globals.environment.address()),+ environment_serial: serial,+ caches: snapshot.add(&[None, Some(cache)]),+ });+ },|_| {},);result@@ -2678,35 +2680,37 @@ fn instance_of_global_functions_walks_prototype_chains() {});let globals = FakeGlobals::new();let run = |value: u64, shape: u64| {- let snapshot_globals = crate::snapshot::GlobalsSnapshot {- object: CellId(globals.object.as_ptr() as u64),- declarative_environment: CellId(globals.environment.address()),- environment_serial: 99,- caches: vec![- None,- Some(GlobalCacheSnapshot::Binding {- index: 2,- mutable: false,- assigned: false,- value: Some(GlobalValueSnapshot {- bits: function_value,- inline_executable: None,- cell: None,- intrinsic: None,- typed_array: None,- has_instance: Some(OrdinaryHasInstanceSnapshot {- shape: CellId(shape),- dictionary_generation: None,- prototype_offset: 1,- }),+ let caches = [+ None,+ Some(GlobalCacheSnapshot::Binding {+ index: 2,+ mutable: false,+ assigned: false,+ value: Some(GlobalValueSnapshot {+ bits: function_value,+ inline_executable: None,+ cell: None,+ intrinsic: None,+ typed_array: None,+ has_instance: Some(OrdinaryHasInstanceSnapshot {+ shape: CellId(shape),+ dictionary_generation: None,+ prototype_offset: 1,}),}),- ],- };+ }),+ ];let (result, _) = run_program_with_snapshot(&program,&[value],- |snapshot| snapshot.executables[0].globals = Some(snapshot_globals),+ |snapshot| {+ snapshot.executables[0].globals = Some(crate::snapshot::GlobalsSnapshot {+ object: CellId(globals.object.as_ptr() as u64),+ declarative_environment: CellId(globals.environment.address()),+ environment_serial: 99,+ caches: snapshot.add(&caches),+ });+ },|_| {},);result@@ -2743,8 +2747,8 @@ fn modulo_of_random_int32_values() {]});let mut snapshot = crate::builder::tests::snapshot_for(&program, layout());- snapshot.runtime = marker_runtime();- snapshot.executables[0].feedback.arith = vec![INT32_RESULTS_FEEDBACK];+ set_marker_runtime(&mut snapshot);+ snapshot.executables[0].feedback.arith = snapshot.add(&[INT32_RESULTS_FEEDBACK]);let compiled =compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();let mut random = crate::regalloc::tests::Random(0x1234_5678_9ABC_DEF1);@@ -2792,7 +2796,9 @@ fn checks_take_the_slow_path_only_when_they_fail() {]});let pc = program.offsets[1];- let exits = |snapshot: &mut Snapshot| snapshot.executables[0].exit_sites = vec![(pc, ExitKind::Uninitialized)];+ let exits = |snapshot: &mut Snapshot| {+ snapshot.executables[0].exit_sites = snapshot.add(&[(pc, ExitKind::Uninitialized)]);+ };let (result, machine) = run_program_with_snapshot(&program, &[argument], exits, |machine| {// The this value register.machine.frame[FRAME_HEADER_WORDS + 2] = argument;@@ -2981,7 +2987,7 @@ fn every_fast_path_compiles_for_both_architectures() {instructions});let mut snapshot = crate::builder::tests::snapshot_for(&program, layout());- snapshot.runtime = marker_runtime();+ set_marker_runtime(&mut snapshot);for opcode in [OpCode::InitializeVariableBinding, OpCode::SetLexicalBinding] {std::sync::Arc::make_mut(&mut snapshot.runtime.slow_paths)[opcode as usize] = marker_put as *const () as u64;}@@ -3096,14 +3102,19 @@ impl FakeCachedObject {|snapshot| {snapshot.runtime.layout.keyed_lookup_cache_entries = self.keyed_lookup_cache.get();snapshot.runtime.layout.keyed_store_cache_entries = self.keyed_store_cache.get();+ if self.megamorphic_in_snapshot.get() {+ snapshot.executables[0].property_caches = snapshot.add(&[+ crate::snapshot::PropertyCacheSnapshot::default(),+ crate::snapshot::PropertyCacheSnapshot {+ kind: crate::snapshot::PropertyCacheKind::Megamorphic,+ ..Default::default()+ },+ ]);+ }let executable = &mut snapshot.executables[0];executable.string_prototype = prototypes.string.map(crate::snapshot::CellId);executable.number_prototype = prototypes.number.map(crate::snapshot::CellId);executable.boolean_prototype = prototypes.boolean.map(crate::snapshot::CellId);- if self.megamorphic_in_snapshot.get() {- executable.property_caches.resize(2, Default::default());- executable.property_caches[1].kind = crate::snapshot::PropertyCacheKind::Megamorphic;- }},|machine| machine.frame[4] = self.executable.as_ptr() as u64,);@@ -3225,7 +3236,7 @@ fn get_by_id_reads_direct_getter_wrappers_of_compressed_fields_inline() {}fn get_by_id_reads_direct_getter_wrappers_inline_from(compressed_field: bool) {- use crate::builder::tests::property_access::{cache, own};+ use crate::builder::tests::property_access::{add_caches, cache, own};use crate::snapshot::{AccessorFunctionSnapshot, CellId, DirectGetterFields, NativeCallTarget, PropertyCacheEntryType,};@@ -3288,7 +3299,10 @@ fn get_by_id_reads_direct_getter_wrappers_inline_from(compressed_field: bool) {let (result, _) = run_program_with_snapshot(&program,&[fake.value()],- |snapshot| snapshot.executables[0].property_caches = vec![cache(Vec::new()), cache(vec![entry])],+ |snapshot| {+ snapshot.executables[0].property_caches =+ add_caches(snapshot, &[cache(Vec::new()), cache(vec![entry])]);+ },|machine| machine.frame[4] = fake.executable.as_ptr() as u64,);assert_eq!(result.status, RETURNED);@@ -3338,7 +3352,7 @@ extern "C" fn fake_native_setter(vm: *mut u64) -> FakeNativeResult {#[test]fn put_by_id_calls_native_setters_of_prototypes() {- use crate::builder::tests::property_access::{cache, own};+ use crate::builder::tests::property_access::{add_caches, cache, own};use crate::snapshot::{AccessorFunctionSnapshot, CellId, NativeCallTarget, PropertyCacheEntryType};// A prototype whose property 0 is an accessor with a native setter.let function = low_cell(&[0; 4]);@@ -3386,7 +3400,9 @@ fn put_by_id_calls_native_setters_of_prototypes() {let (result, machine) = run_program_with_snapshot(&program,&[fake.value(), value::int32(42)],- |snapshot| snapshot.executables[0].property_caches = vec![cache(Vec::new()), cache(vec![entry])],+ |snapshot| {+ snapshot.executables[0].property_caches = add_caches(snapshot, &[cache(Vec::new()), cache(vec![entry])]);+ },|machine| machine.frame[4] = fake.executable.as_ptr() as u64,);assert_eq!(result.status, RETURNED);@@ -3639,10 +3655,10 @@ fn builtin_call(this_value: Operand, arguments: Vec<Operand>) -> Instruction {/// Makes the feedback of the `Call` of `builtin_call()` say it saw the/// builtin `builtin`.fn saw_builtin(snapshot: &mut Snapshot, builtin: u8) {- snapshot.executables[0].feedback.call = vec![crate::snapshot::CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[crate::snapshot::CallFeedbackSnapshot {target_builtin: Some(builtin),..Default::default()- }];+ }]);}/// Fake function memory: its flags at byte 8, and the builtin it is plus one@@ -3743,7 +3759,8 @@ fn math_builtin_calls() {|snapshot| {saw_builtin(snapshot, builtin);if exited {- snapshot.executables[0].exit_sites = vec![(pc, ExitKind::SlowPath), (pc, ExitKind::Overflow)];+ snapshot.executables[0].exit_sites =+ snapshot.add(&[(pc, ExitKind::SlowPath), (pc, ExitKind::Overflow)]);}},|_| {},@@ -3900,7 +3917,7 @@ fn math_function_calls() {|snapshot| {saw_builtin(snapshot, builtin);if exited {- snapshot.executables[0].exit_sites = vec![(pc, ExitKind::SlowPath)];+ snapshot.executables[0].exit_sites = snapshot.add(&[(pc, ExitKind::SlowPath)]);}},|_| {},@@ -4081,7 +4098,7 @@ fn short_string_concatenations_through_the_fly_string_cache() {snapshot.runtime.rope_allocation = crate::snapshot::RopeAllocationInfo {allocator: 1,cell_size: 64,- template: vec![0; 8],+ template: snapshot.add(&[0; 8]),lhs_offset: 32,rhs_offset: 36,length_offset: 16,@@ -4098,7 +4115,7 @@ fn short_string_concatenations_through_the_fly_string_cache() {snapshot.runtime.layout.large_numeric_string_cache_number = 0;snapshot.runtime.layout.large_numeric_string_cache_string = 8;// ArithFeedback::String and ArithFeedback::Int32.- snapshot.executables[0].feedback.arith = vec![1 << 3 | 1];+ snapshot.executables[0].feedback.arith = snapshot.add(&[1 << 3 | 1]);},|_| {},);@@ -4638,7 +4655,7 @@ fn rope_strings_come_from_the_runtime_without_a_local_free_cell() {snapshot.runtime.rope_allocation = crate::snapshot::RopeAllocationInfo {allocator: free_list.as_mut_ptr() as u64,cell_size: 64,- template: vec![0x1234; 8],+ template: snapshot.add(&[0x1234; 8]),lhs_offset: 32,rhs_offset: 36,length_offset: 16,@@ -4657,7 +4674,7 @@ fn rope_strings_come_from_the_runtime_without_a_local_free_cell() {allocation.local_end_offset = 16;allocation.local_cell_size_offset = 24;// ArithFeedback::String.- snapshot.executables[0].feedback.arith = vec![1 << 3];+ snapshot.executables[0].feedback.arith = snapshot.add(&[1 << 3]);},|_| {},);@@ -4737,7 +4754,7 @@ fn concatenations_that_are_keys_take_the_strings_the_vm_remembers() {snapshot.runtime.rope_allocation = crate::snapshot::RopeAllocationInfo {allocator: free_list.as_mut_ptr() as u64,cell_size: 64,- template: vec![0x1234; 8],+ template: snapshot.add(&[0x1234; 8]),lhs_offset: 32,rhs_offset: 36,length_offset: 16,@@ -4762,7 +4779,7 @@ fn concatenations_that_are_keys_take_the_strings_the_vm_remembers() {allocation.local_end_offset = 16;allocation.local_cell_size_offset = 24;// ArithFeedback::String.- snapshot.executables[0].feedback.arith = vec![1 << 3];+ snapshot.executables[0].feedback.arith = snapshot.add(&[1 << 3]);},|_| {},);diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex a09e58d8d26..ffbc1481cc4 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -76,7 +76,7 @@ pub fn compile(snapshot: &Snapshot, scratch: &mut Scratch, compiled: &mut Compilsnapshot.executables.first()- .is_none_or(|executable| builder::has_run(executable, pc))+ .is_none_or(|executable| builder::has_run(snapshot, executable, pc))},scratch,compiled,@@ -108,6 +108,9 @@ fn compile_into<M: asm::PortableMacroAssembler>(compiled: &mut CompiledCode,) -> Result<(), CompileFailure> {compiled.clear();+ if !snapshot.is_complete() {+ return Err(CompileFailure::TooLarge);+ }let mut graph = builder::build_graph_with_feedback(snapshot, has_run)?;let executable = &snapshot.executables[0];let pass_dumps = if snapshot.options.dump_passes {@@ -133,15 +136,7 @@ fn compile_into<M: asm::PortableMacroAssembler>(regalloc::dump_allocation(&graph, &allocation));}- let mut generated = codegen::generate::<M>(- &graph,- &allocation,- &snapshot.executables,- &snapshot.runtime,- snapshot.options.stress,- snapshot.options.verify_ir,- scratch,- )?;+ let mut generated = codegen::generate::<M>(&graph, &allocation, snapshot, snapshot.options.verify_ir, scratch)?;generated.osr_entries.sort_unstable();let layout = scratch.artifact.finish(&Tail {diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex 16137775f8b..1ec8307cced 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -479,7 +479,7 @@ fn loops_leave_the_values_they_only_carry_through_in_their_stack_slots() {]});let mut snapshot = crate::builder::tests::snapshot_for(&program, layout);- snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 16];+ snapshot.executables[0].feedback.arith = snapshot.add(&[crate::snapshot::arith_feedback::INT32; 16]);let graph = crate::builder::tests::optimized_graph(&snapshot);let allocation = allocate_and_verify(&graph);let header = graph.blocks.iter().position(|block| block.is_loop_header).unwrap();@@ -533,7 +533,7 @@ fn int32_operations_write_over_their_first_input_where_it_dies() {]});let mut snapshot = crate::builder::tests::snapshot_for(&program, crate::bytecode::test_support::test_layout());- snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 2];+ snapshot.executables[0].feedback.arith = snapshot.add(&[crate::snapshot::arith_feedback::INT32; 2]);let graph = crate::builder::tests::optimized_graph(&snapshot);let allocation = allocate_and_verify(&graph);let xors = graph@@ -585,7 +585,7 @@ fn shift_amounts_are_in_the_targets_shift_register_or_immediates() {]});let mut snapshot = crate::builder::tests::snapshot_for(&program, crate::bytecode::test_support::test_layout());- snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 3];+ snapshot.executables[0].feedback.arith = snapshot.add(&[crate::snapshot::arith_feedback::INT32; 3]);let graph = crate::builder::tests::optimized_graph(&snapshot);let shift = |op| find_node(&graph, |node| node.op == Op::Int32Binary { op });let (variable, constant) = (@@ -637,7 +637,7 @@ fn float64_operations_write_over_their_first_input_where_it_dies() {]});let mut snapshot = crate::builder::tests::snapshot_for(&program, crate::bytecode::test_support::test_layout());- snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::DOUBLE; 2];+ snapshot.executables[0].feedback.arith = snapshot.add(&[crate::snapshot::arith_feedback::DOUBLE; 2]);let graph = crate::builder::tests::optimized_graph(&snapshot);let allocation = allocate_and_verify(&graph);let binaries = graph@@ -1219,10 +1219,10 @@ fn float64_values_get_floating_point_registers() {});let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());snapshot.runtime.layout.builtin_math_sqrt = 13;- snapshot.executables[0].feedback.call = vec![crate::snapshot::CallFeedbackSnapshot {+ snapshot.executables[0].feedback.call = snapshot.add(&[crate::snapshot::CallFeedbackSnapshot {target_builtin: Some(13),..Default::default()- }];+ }]);let mut graph = crate::builder::build_graph_with_feedback(&snapshot, &|_| true).unwrap();crate::passes::optimize(&mut graph, &snapshot.executables[0].layout, true);let allocation = allocate_and_verify(&graph);diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex e2dd8a35557..6249ad305ef 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -10,7 +10,16 @@//! identified by `CellId`, which is only ever compared. The main thread keeps//! every referenced cell alive until the compiled code is installed or the//! compile job is abandoned.+//!+//! A snapshot is tables. Every type in it is a plain value, and where one has a list of something, it has a `List`:+//! rows that are next to each other in the one block of memory that holds all the lists of the snapshot. So a+//! snapshot owns no heap block, however much it holds. Its memory serves the next snapshot (see+//! `Snapshot::clear()`), and all of it can go back to the system when no compile is running.++use core::marker::PhantomData;+use core::ops::{Deref, DerefMut, Index, IndexMut};+use ak::{Column, RowBlock};use std::sync::Arc;use crate::ir::Float64Function;@@ -52,30 +61,30 @@ impl CellId {/// each with at most `LIBJS_JIT=inline-max-size=N` bytecode instructions. The/// graph builder applies the inlining budget. Each function object is added/// once, so the same index can be the target of several slots.-#[derive(Debug, Clone, Default)]+#[derive(Debug, Clone, Copy, Default)]pub struct ExecutableSnapshot {/// A copy of the assembled bytecode, exactly as the interpreter runs it.- pub bytecode: Vec<u8>,+ pub bytecode: List<u8>,/// The address of the executable's own bytecode on the main thread/// (`Executable::bytecode.data()`). Slow paths receive pointers to/// instructions in it, which the code embeds as immediates.pub bytecode_address: u64,pub layout: FrameLayout,/// NaN-boxed constant values, in constant slot order.- pub constants: Vec<u64>,- pub exception_handlers: Vec<ExceptionHandler>,+ pub constants: List<u64>,+ pub exception_handlers: List<ExceptionHandler>,/// Places where speculation already failed. The compiler never repeats a/// speculation of the same kind at the same pc.- pub exit_sites: Vec<(u32, ExitKind)>,+ pub exit_sites: List<(u32, ExitKind)>,/// For the compiled executable only: places in builtins written in/// JavaScript (by their executable's cell) where its code exited while/// running them inlined. Code inlining a builtin consults these instead/// of the builtin's `exit_sites`, which come from all its callers.- pub builtin_exit_sites: Vec<(CellId, u32, ExitKind)>,+ pub builtin_exit_sites: List<(CellId, u32, ExitKind)>,pub feedback: FeedbackSnapshot,/// The interpreter's property lookup caches, indexed like/// `Executable::property_lookup_caches`.- pub property_caches: Vec<PropertyCacheSnapshot>,+ pub property_caches: List<PropertyCacheSnapshot>,/// The `Executable` cell itself.pub cell: CellId,/// The function object of an inlining candidate; `None` for index 0.@@ -92,11 +101,11 @@ pub struct ExecutableSnapshot {/// Object values of captured bindings at compile time. Each load must/// check the value before using it as a constant, since bindings and/// the environments of other closures sharing the executable may differ.- pub captured_bindings: Vec<(EnvironmentCoordinate, GlobalValueSnapshot)>,+ pub captured_bindings: List<(EnvironmentCoordinate, GlobalValueSnapshot)>,/// The captured bindings that stores of the executable store to, which/// are mutable in every environment of their scope, so that the stores/// need not check that.- pub mutable_bindings: Vec<EnvironmentCoordinate>,+ pub mutable_bindings: List<EnvironmentCoordinate>,/// Whether `function` is a builtin written in JavaScript. Its frames are/// set up like those of other builtins: with the environments of their/// caller's frame, and without a script or module.@@ -123,23 +132,23 @@ pub struct ExecutableSnapshot {/// The shapes object literals reached before (`NewObject` with a cache/// index creates its object with that shape if there is one), indexed/// like `Executable::object_shape_caches`.- pub object_shape_caches: Vec<Option<ObjectShapeCacheSnapshot>>,+ pub object_shape_caches: List<Option<ObjectShapeCacheSnapshot>>,/// For the compiled function only: the closures its `NewFunction`/// instructions create, indexed by `shared_function_data_index`, if JIT/// code can create them by copying (see `FunctionAllocationInfo`).- pub closure_templates: Vec<Option<ClosureTemplateSnapshot>>,+ pub closure_templates: List<Option<ClosureTemplateSnapshot>>,/// For the compiled function only: how JIT code allocates the/// environments of its `CreateLexicalEnvironment` instructions itself,/// indexed by their environment shape cache, if it can.- pub lexical_environment_templates: Vec<Option<LexicalEnvironmentTemplateSnapshot>>,+ pub lexical_environment_templates: List<Option<LexicalEnvironmentTemplateSnapshot>>,/// The environments of direct calls (see `DirectCallTarget::environment`).- pub environment_templates: Vec<EnvironmentTemplateSnapshot>,+ pub environment_templates: List<EnvironmentTemplateSnapshot>,/// For the compiled function only: its identifier table, as the words of/// its `Utf16FlyString`s, which the executable keeps alive.- pub identifiers: Vec<u64>,+ pub identifiers: List<u64>,/// The property key table, as the words of the `Utf16FlyString`s of its/// string keys (which the executable keeps alive), or 0 for symbols.- pub property_key_names: Vec<u64>,+ pub property_key_names: List<u64>,/// The global variables of the executable's realm that its `GetGlobal`/// and `SetGlobal` instructions access, if code may access them directly.pub globals: Option<GlobalsSnapshot>,@@ -155,7 +164,7 @@ pub struct ExecutableSnapshot {/// fields give `this`, by property offset, in the order/// InitializeInstanceElements defines them. `this` is created with the/// shape it has after that (see `ConstructTarget::this_shape`).- pub literal_instance_fields: Option<Vec<(u32, u64)>>,+ pub literal_instance_fields: Option<List<(u32, u64)>>,/// For a derived constructor with instance elements among the inlining/// candidates whose constructs JIT code can inline: its fields, if they/// can be added to `this` like literal fields of a base constructor,@@ -169,15 +178,15 @@ pub struct ExecutableSnapshot {/// and allows extensions, in order, the property offset of each field, its/// value, and the shape `this` gets if the field adds the property (the/// same one as an earlier field otherwise).-#[derive(Debug, Clone, Default, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct DerivedInstanceFields {pub shape: CellId,- pub fields: Vec<(u32, u64, Option<CellId>)>,+ pub fields: List<(u32, u64, Option<CellId>)>,}/// The global object and the global declarative environment of a realm, and/// what the global variable caches of an executable running in it know.-#[derive(Debug, Clone, Default, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct GlobalsSnapshot {pub object: CellId,/// The declarative environment record of the global environment, which@@ -189,7 +198,7 @@ pub struct GlobalsSnapshot {pub environment_serial: u64,/// Indexed like `Executable::global_variable_caches`: what each cache/// found, if it still applies.- pub caches: Vec<Option<GlobalCacheSnapshot>>,+ pub caches: List<Option<GlobalCacheSnapshot>>,}/// What a global variable cache found.@@ -271,26 +280,26 @@ pub struct OrdinaryHasInstanceSnapshot {/// A function object like the closures of one `NewFunction` instruction,/// apart from their environments.-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct ClosureTemplateSnapshot {/// The function object itself. Code that copies it embeds it, which/// keeps everything it refers to alive.pub sample: CellId,/// Its bytes (see `FunctionAllocationInfo`).- pub words: Vec<u64>,+ pub words: List<u64>,/// The index in `Snapshot::executables` of the closures' executable, if/// calls of them can be inlined.pub inline_executable: Option<u32>,}/// An `ObjectShapeCache` that has a shape.-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct ObjectShapeCacheSnapshot {pub shape: ShapeSnapshot,/// Where `InitObjectLiteralProperty` with each `property_slot` stores/// its value in objects of `shape`, as far as the cache knows. A slot/// without an offset here has none known.- pub property_offsets: Vec<u32>,+ pub property_offsets: List<u32>,}/// A shape objects can be created with. Code that does so embeds it and must@@ -450,19 +459,19 @@ impl ExecutableSnapshot {/// A copy of the interpreter feedback of one executable, indexed by the/// feedback slot indices in the bytecode. The bits mean the same as in/// `Libraries/LibJS/Rust/src/layout/feedback.rs`.-#[derive(Debug, Clone, Default)]+#[derive(Debug, Clone, Copy, Default)]pub struct FeedbackSnapshot {/// `ArithFeedback` bits.- pub arith: Vec<u8>,+ pub arith: List<u8>,/// `ValueFeedback` bits.- pub value: Vec<u16>,+ pub value: List<u16>,/// The `ValueFeedback` bits of the sites of the property lookup caches, indexed like the caches.- pub cache_value: Vec<u16>,- pub call: Vec<CallFeedbackSnapshot>,- pub keyed: Vec<KeyedFeedbackSnapshot>,+ pub cache_value: List<u16>,+ pub call: List<CallFeedbackSnapshot>,+ pub keyed: List<KeyedFeedbackSnapshot>,/// The bound arguments of the bound functions that call sites forwarded/// to, as NaN-boxed values (see `ForwardedCallSnapshot::bound_arguments_start`).- pub bound_arguments: Vec<u64>,+ pub bound_arguments: List<u64>,}#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]@@ -615,11 +624,11 @@ pub struct DirectCallTarget {/// pointer to its binding values (which follow `words`, if/// `inline_binding_values`) at `binding_values_offset` and its parent at/// `outer_offset`. Code that allocates it embeds `shape`.-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct LexicalEnvironmentTemplateSnapshot {pub allocator: u64,pub cell_size: u32,- pub words: Vec<u64>,+ pub words: List<u64>,pub binding_count: u32,pub inline_binding_values: bool,pub binding_values_offset: u32,@@ -636,11 +645,11 @@ pub struct LexicalEnvironmentTemplateSnapshot {/// after `words`, at `binding_values_offset`, and the `this` value the call/// binds at `this_value_offset` if `binds_this`. The binding values need no/// initialization: the environment has none yet.-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct EnvironmentTemplateSnapshot {pub allocator: u64,pub cell_size: u32,- pub words: Vec<u64>,+ pub words: List<u64>,/// Whether the environment has room for binding values in its cell.pub inline_binding_values: bool,pub binding_values_offset: u32,@@ -648,7 +657,7 @@ pub struct EnvironmentTemplateSnapshot {pub this_value_offset: u32,/// The cells `words` refer to besides the function, which code that/// allocates the environment embeds: its shape and outer environment.- pub cells: Vec<CellId>,+ pub cells: List<CellId>,}/// The words of an ECMAScript function's `[[ScriptOrModule]]`,@@ -726,11 +735,11 @@ pub enum PropertyCacheKind {Megamorphic,}-#[derive(Debug, Clone, Default, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct PropertyCacheSnapshot {pub kind: PropertyCacheKind,/// The non-empty entries.- pub entries: Vec<PropertyCacheEntrySnapshot>,+ pub entries: List<PropertyCacheEntrySnapshot>,}/// `PropertyLookupCache::Entry::Type`.@@ -1427,10 +1436,10 @@ pub struct DynamicCallLayout {/// `undefined` (for any property count), with room for `reserve` properties/// inline if a size class has room for them. It may collect garbage, like/// any call.-#[derive(Debug, Clone, Default)]+#[derive(Debug, Clone, Copy, Default)]pub struct ObjectAllocationInfo {/// By ascending `inline_capacity`.- pub size_classes: Vec<ObjectSizeClass>,+ pub size_classes: List<ObjectSizeClass>,pub empty_object_inline_capacity: u32,pub heap: u64,pub heap_allocated_bytes_offset: u32,@@ -1445,7 +1454,7 @@ pub struct ObjectAllocationInfo {pub local_end_offset: u32,pub local_cell_size_offset: u32,/// The bytes every new plain object starts with, as u64 words.- pub template: Vec<u64>,+ pub template: List<u64>,pub shape_offset: u32,pub named_properties_offset: u32,/// Where the inline named storage of the objects of other classes starts.@@ -1461,13 +1470,13 @@ pub struct ObjectAllocationInfo {impl ObjectAllocationInfo {/// The size class JIT code allocates plain objects whose shape has/// `property_count` properties in, or `None` if it must take the slow path.- pub fn size_class_for(&self, property_count: u32) -> Option<&ObjectSizeClass> {+ pub fn size_class_for<'a>(&self, snapshot: &'a Snapshot, property_count: u32) -> Option<&'a ObjectSizeClass> {let inline_values = if property_count == 0 {self.empty_object_inline_capacity} else {property_count};- self.size_classes+ snapshot[self.size_classes].iter().find(|size_class| size_class.inline_capacity >= inline_values)}@@ -1489,13 +1498,13 @@ impl ObjectAllocationInfo {/// `PrimitiveString* slow_path(VM*, PrimitiveString* lhs, PrimitiveString* rhs)`/// instead, which returns the rope string; if `slow_path` is 0, the/// interpreter's slow path concatenates the strings.-#[derive(Debug, Clone, Default)]+#[derive(Debug, Clone, Copy, Default)]pub struct RopeAllocationInfo {/// The `GC::CellAllocator` of rope strings.pub allocator: u64,pub cell_size: u32,/// The bytes every new rope string starts with, as u64 words.- pub template: Vec<u64>,+ pub template: List<u64>,pub lhs_offset: u32,pub rhs_offset: u32,pub length_offset: u32,@@ -1529,15 +1538,15 @@ pub struct RopeAllocationInfo {/// If `allocator` is 0, there is no fast path. Slow path:/// `Array* libjs_jit_allocate_array(VM*, u32 count)` returns an array of/// `count` packed `undefined` elements.-#[derive(Debug, Clone, Default)]+#[derive(Debug, Clone, Copy, Default)]pub struct ArrayAllocationInfo {pub allocator: u64,pub cell_size: u32,- pub template: Vec<u64>,+ pub template: List<u64>,pub shape: CellId,/// By ascending capacity.- pub storage_size_classes: Vec<StorageSizeClass>,- pub storage_template: Vec<u64>,+ pub storage_size_classes: List<StorageSizeClass>,+ pub storage_template: List<u64>,pub storage_values_offset: u32,pub storage_capacity_offset: u32,pub slow_path: u64,@@ -1753,13 +1762,280 @@ pub struct StressOptions {pub few_registers: bool,}+/// A list of rows of type `T` of a snapshot. The snapshot gives its rows: `&snapshot[list]`. A list is only good for+/// the snapshot it was added to.+pub type List<T> = ak::RowList<T>;++/// A list of a snapshot that is being written row by row (see `SnapshotWriter::begin()`).+#[must_use]+pub struct ListStart<T> {+ rows: PhantomData<fn() -> T>,+}++/// A type that snapshots have lists of.+pub trait Row: Copy + Send + Sync + 'static {+ #[doc(hidden)]+ const INDEX: usize;+ #[doc(hidden)]+ fn open(lists: &OpenLists) -> &Column<Self>;+ #[doc(hidden)]+ fn open_mut(lists: &mut OpenLists) -> &mut Column<Self>;+}++/// How many bytes of rows a list that is written row by row holds at most.+const MAX_OPEN_LIST_BYTES: usize = 16 * 1024 * 1024;++macro_rules! rows {+ ($($name:ident: $row:ty,)*) => {+ #[allow(non_camel_case_types)]+ enum RowIndex {+ $($name,)*+ }++ const ROW_TYPE_COUNT: usize = [$(RowIndex::$name,)*].len();++ /// For each type of row, the rows of the list that is being written row by row, if one is. A snapshot is+ /// one block of lists, so the rows of a list have to be next to each other, and lists of other types get+ /// written while the list gets its rows. So the rows wait here until the list ends.+ ///+ /// This is memory that comes straight from the system, and it keeps that memory: one of these serves+ /// capture after capture, and its memory goes back to the system as a whole when it is dropped.+ #[derive(Debug)]+ pub struct OpenLists {+ $($name: Column<$row>,)*+ /// Whether a list of each type is being written.+ open: [bool; ROW_TYPE_COUNT],+ }++ impl OpenLists {+ pub fn new() -> Self {+ Self {+ $($name: Column::new(MAX_OPEN_LIST_BYTES / size_of::<$row>(), c"JIT snapshot open lists"),)*+ open: [false; ROW_TYPE_COUNT],+ }+ }++ /// Drops the lists that are being written.+ fn reset(&mut self) {+ $(self.$name.clear();)*+ self.open = [false; ROW_TYPE_COUNT];+ }+ }++ impl Default for OpenLists {+ fn default() -> Self {+ Self::new()+ }+ }++ $(+ impl Row for $row {+ const INDEX: usize = RowIndex::$name as usize;++ fn open(lists: &OpenLists) -> &Column<Self> {+ &lists.$name+ }++ fn open_mut(lists: &mut OpenLists) -> &mut Column<Self> {+ &mut lists.$name+ }+ }+ )*+ };+}++rows! {+ bytes: u8,+ halves: u16,+ offsets: u32,+ words: u64,+ cells: CellId,+ exception_handlers: ExceptionHandler,+ exit_sites: (u32, ExitKind),+ builtin_exit_sites: (CellId, u32, ExitKind),+ property_caches: PropertyCacheSnapshot,+ property_cache_entries: PropertyCacheEntrySnapshot,+ call_feedback: CallFeedbackSnapshot,+ keyed_feedback: KeyedFeedbackSnapshot,+ captured_bindings: (EnvironmentCoordinate, GlobalValueSnapshot),+ mutable_bindings: EnvironmentCoordinate,+ object_shape_caches: Option<ObjectShapeCacheSnapshot>,+ closure_templates: Option<ClosureTemplateSnapshot>,+ lexical_environment_templates: Option<LexicalEnvironmentTemplateSnapshot>,+ environment_templates: EnvironmentTemplateSnapshot,+ global_caches: Option<GlobalCacheSnapshot>,+ literal_fields: (u32, u64),+ derived_fields: (u32, u64, Option<CellId>),+ object_size_classes: ObjectSizeClass,+ storage_size_classes: StorageSizeClass,+}+/// The input of one compile job.-#[derive(Debug, Clone, Default)]+///+/// The thread of the VM writes it and a compile thread reads it. All its lists are in one block of memory, list+/// after list, and its executables are in a second one. Both come straight from the system and go back there as a+/// whole. A snapshot that was cleared keeps its memory for what is written next, so a snapshot that is used again+/// and again takes nothing from the system and nothing from the heap.+#[derive(Debug)]pub struct Snapshot {/// Index 0 is the function being compiled; the rest are inlining candidates.- pub executables: Vec<ExecutableSnapshot>,+ pub executables: Column<ExecutableSnapshot>,+ rows: RowBlock,pub runtime: RuntimeInfo,pub options: CompileOptions,+ /// Whether a row had no room (see `is_complete()`).+ overflowed: bool,+}++impl Snapshot {+ const MAX_EXECUTABLES: usize = 1 << 16;+ /// How many bytes of rows the lists of a snapshot hold at most. A capture that needs more gives a snapshot that+ /// is not complete (see `is_complete()`).+ const MAX_ROW_BYTES: usize = 64 * 1024 * 1024;+ /// How many bytes of rows and how many executables a snapshot keeps the memory for when it serves the next+ /// capture: the first step its memory grows by.+ const SPARE_ROW_BYTES: usize = 64 * 1024;+ const SPARE_EXECUTABLES: usize = 64 * 1024 / size_of::<ExecutableSnapshot>();++ pub fn new() -> Self {+ Self {+ executables: Column::new(Self::MAX_EXECUTABLES, c"JIT snapshot executables"),+ rows: RowBlock::new(Self::MAX_ROW_BYTES, c"JIT snapshot rows"),+ runtime: RuntimeInfo::default(),+ options: CompileOptions::default(),+ overflowed: false,+ }+ }++ /// Makes this a snapshot of nothing, which keeps its memory. The lists of the snapshot are lists of no snapshot+ /// after this.+ pub fn clear(&mut self) {+ self.executables.clear();+ self.rows.clear();+ self.runtime = RuntimeInfo::default();+ self.options = CompileOptions::default();+ self.overflowed = false;+ }++ /// Gives memory back to the system: what is above the needs of a usual snapshot.+ pub fn trim(&mut self) {+ self.executables.trim(Self::SPARE_EXECUTABLES);+ self.rows.trim(Self::SPARE_ROW_BYTES);+ }++ /// Whether the snapshot holds all that was written into it. One that does not is too large to compile, and has+ /// lists that miss rows.+ pub fn is_complete(&self) -> bool {+ !self.overflowed+ }++ /// Adds an executable, and returns its index.+ pub fn add_executable(&mut self, executable: ExecutableSnapshot) -> u32 {+ let index = self.executables.len() as u32;+ if self.executables.try_push(executable).is_err() {+ self.overflowed = true;+ }+ index+ }++ /// Adds `rows` as a list.+ pub fn add<T: Row>(&mut self, rows: &[T]) -> List<T> {+ self.rows.try_add(rows).unwrap_or_else(|_| {+ self.overflowed = true;+ List::empty()+ })+ }+}++impl Default for Snapshot {+ fn default() -> Self {+ Self::new()+ }+}++impl<T: Row> Index<List<T>> for Snapshot {+ type Output = [T];++ fn index(&self, list: List<T>) -> &[T] {+ self.rows.rows(list)+ }+}++impl<T: Row> IndexMut<List<T>> for Snapshot {+ fn index_mut(&mut self, list: List<T>) -> &mut [T] {+ self.rows.rows_mut(list)+ }+}++/// A snapshot that is being captured, with what writes its lists row by row: `begin()`, `push()` and `end()`. A list+/// that is ready is added in one go, with `Snapshot::add()`.+pub struct SnapshotWriter {+ snapshot: Box<Snapshot>,+ lists: OpenLists,+}++impl SnapshotWriter {+ /// Writes into `snapshot`, with the memory of `lists` for the lists that are written row by row.+ pub fn new(snapshot: Box<Snapshot>, mut lists: OpenLists) -> Self {+ lists.reset();+ Self { snapshot, lists }+ }++ /// The snapshot as it is now, and the memory for lists that are written row by row, for the next capture.+ pub fn finish(self) -> (Box<Snapshot>, OpenLists) {+ (self.snapshot, self.lists)+ }++ /// Starts a list, which gets the rows that `push()` adds until `end()`. Only one list of a type of row can be+ /// written at a time.+ pub fn begin<T: Row>(&mut self) -> ListStart<T> {+ // NB: Rows of two lists that mix would be wrong input for the compiler, so this is checked in every build.+ assert!(!self.lists.open[T::INDEX], "another list of this type is being written");+ self.lists.open[T::INDEX] = true;+ ListStart { rows: PhantomData }+ }++ /// Adds a row to the list of its type that is being written.+ pub fn push<T: Row>(&mut self, row: T) {+ assert!(self.lists.open[T::INDEX], "no list of this type is being written");+ if T::open_mut(&mut self.lists).try_push(row).is_err() {+ self.snapshot.overflowed = true;+ }+ }++ /// The rows that the list that is being written has so far.+ pub fn rows_of<T: Row>(&self, _list: &ListStart<T>) -> &[T] {+ T::open(&self.lists)+ }++ /// Drops the rows of the list that is being written.+ pub fn drop_rows<T: Row>(&mut self, _list: &ListStart<T>) {+ T::open_mut(&mut self.lists).clear();+ }++ /// Ends the list that is being written, and adds it to the snapshot.+ pub fn end<T: Row>(&mut self, _list: ListStart<T>) -> List<T> {+ assert!(self.lists.open[T::INDEX], "no list of this type is being written");+ self.lists.open[T::INDEX] = false;+ let rows = T::open_mut(&mut self.lists);+ let list = self.snapshot.add(rows);+ rows.clear();+ list+ }+}++impl Deref for SnapshotWriter {+ type Target = Snapshot;++ fn deref(&self) -> &Snapshot {+ &self.snapshot+ }+}++impl DerefMut for SnapshotWriter {+ fn deref_mut(&mut self) -> &mut Snapshot {+ &mut self.snapshot+ }}/// The VM's strings of the results of `typeof`, as values.diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rsindex 7cee69a5bc3..575a3c41c81 100644--- a/Libraries/LibJS/Rust/src/jit/allocation.rs+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs@@ -16,7 +16,8 @@ use core::ptr::NonNull;use libjs_jit::snapshot::{ArrayAllocationInfo, CellId, ClosureTemplateSnapshot, EnvironmentTemplateSnapshot, FunctionAllocationInfo,- LexicalEnvironmentTemplateSnapshot, ObjectAllocationInfo, ObjectSizeClass, RopeAllocationInfo, StorageSizeClass,+ LexicalEnvironmentTemplateSnapshot, List, ObjectAllocationInfo, ObjectSizeClass, RopeAllocationInfo,+ SnapshotWriter, StorageSizeClass,};use libjs_runtime_macros::{jit_abi, jit_function_address};@@ -59,16 +60,27 @@ fn address(local_free_list: Option<NonNull<*mut core::ffi::c_void>>) -> u64 {local_free_list.map_or(0, |list| list.as_ptr() as u64)}-/// The bytes of `cell` (of `size` bytes) as u64 words, with a clear mark: cells allocated while the incremental sweep-/// is active start out marked, but cells from local free lists never need marking.-fn cell_words<T>(cell: Gc<T>, size: usize) -> Vec<u64> {- let mut words = vec![0u64; size.div_ceil(8)];- // SAFETY: The cell is live and has `size` bytes, which the words have room for.- unsafe { core::ptr::copy_nonoverlapping(cell.as_ptr().cast::<u8>(), words.as_mut_ptr().cast::<u8>(), size) };+/// Gives `word` the bytes of `cell` (of `size` bytes) as u64 words, first to last, with a clear mark: cells allocated+/// while the incremental sweep is active start out marked, but cells from local free lists never need marking.+fn for_each_cell_word<T>(cell: Gc<T>, size: usize, mut word: impl FnMut(u64)) {let mark = core::mem::offset_of!(CellHeader, mark);- // SAFETY: The mark is a byte within the words.- unsafe { words.as_mut_ptr().cast::<u8>().add(mark).write(0) };- words+ for start in (0..size).step_by(8) {+ let mut bytes = [0u8; 8];+ let len = (size - start).min(8);+ // SAFETY: The cell is live and has `size` bytes, of which these `len` are some, and `bytes` has room for 8.+ unsafe { core::ptr::copy_nonoverlapping(cell.as_ptr().cast::<u8>().add(start), bytes.as_mut_ptr(), len) };+ if let Some(byte) = mark.checked_sub(start).and_then(|index| bytes.get_mut(index)) {+ *byte = 0;+ }+ word(u64::from_ne_bytes(bytes));+ }+}++/// The words of `cell` (see `for_each_cell_word()`), as a list of `snapshot`.+fn cell_words<T>(snapshot: &mut SnapshotWriter, cell: Gc<T>, size: usize) -> List<u64> {+ let words = snapshot.begin();+ for_each_cell_word(cell, size, |word| snapshot.push(word));+ snapshot.end(words)}/// Clears the `size` bytes at `offset` of `words`, which may share their word with other fields.@@ -89,7 +101,12 @@ pub struct AllocationInfos<'d> {pub cells: Deferred<'d, Vec<Gc<CellHeader>>>,}-pub fn allocation_infos<'d>(vm: &Vm, realm: Gc<Realm>, defer_gc: &'d DeferGc<'_>) -> AllocationInfos<'d> {+pub fn allocation_infos<'d>(+ vm: &Vm,+ realm: Gc<Realm>,+ defer_gc: &'d DeferGc<'_>,+ snapshot: &mut SnapshotWriter,+) -> AllocationInfos<'d> {let heap = vm.heap();let inline = heap.inline_allocation_info();let heap_address = heap.raw() as u64;@@ -110,7 +127,7 @@ pub fn allocation_infos<'d>(vm: &Vm, realm: Gc<Realm>, defer_gc: &'d DeferGc<'_>local_cursor_offset: offset(inline.local_cursor_offset),local_end_offset: offset(inline.local_end_offset),local_cell_size_offset: offset(inline.local_cell_size_offset),- template: cell_words(object_template, size_of::<Object>()),+ template: cell_words(snapshot, object_template, size_of::<Object>()),shape_offset: offset(core::mem::offset_of!(Object, shape)),named_properties_offset: offset(core::mem::offset_of!(Object, named_properties)),inline_storage_offset: offset(core::mem::offset_of!(Object, inline_named_storage)),@@ -121,46 +138,51 @@ pub fn allocation_infos<'d>(vm: &Vm, realm: Gc<Realm>, defer_gc: &'d DeferGc<'_>};// NB: Free lists are only popped inline where the heap gives their addresses (not in AddressSanitizer builds).if heap.local_free_list_of(Object::CLASS).is_some() {+ let size_classes = snapshot.begin();for (size_class, inline_capacity) in plain_object_size_classes(heap).iter().zip(&PLAIN_OBJECT_INLINE_CAPACITIES){- object.size_classes.push(ObjectSizeClass {+ snapshot.push(ObjectSizeClass {allocator: address(size_class.local_free_list()),cell_size: size_class.cell_size(),inline_capacity: u32::from(*inline_capacity),});}+ object.size_classes = snapshot.end(size_classes);}let array_template = Array::create(vm, realm, 0, None).must();let array_shape = array_template.shape();- let storage_size_classes = value_storage::size_classes(heap)- .iter()- .zip(SIZE_CLASS_CAPACITIES)- .map(|(size_class, capacity)| StorageSizeClass {- allocator: address(size_class.local_free_list()),+ // NB: Storage is only allocated inline where the heap gives the addresses of all the free lists it comes from.+ let storage_size_classes = snapshot.begin();+ let mut has_all_free_lists = true;+ for (size_class, capacity) in value_storage::size_classes(heap).iter().zip(SIZE_CLASS_CAPACITIES) {+ let allocator = address(size_class.local_free_list());+ has_all_free_lists &= allocator != 0;+ snapshot.push(StorageSizeClass {+ allocator,cell_size: size_class.cell_size(),capacity,- })- .collect::<Vec<_>>();+ });+ }+ if !has_all_free_lists {+ snapshot.drop_rows(&storage_size_classes);+ }+ let storage_size_classes = snapshot.end(storage_size_classes);let array = ArrayAllocationInfo {allocator: address(heap.local_free_list_of(Array::CLASS)),cell_size: size(size_of::<Array>()),- template: cell_words(array_template, size_of::<Array>()),+ template: cell_words(snapshot, array_template, size_of::<Array>()),shape: CellId(array_shape.as_ptr() as u64),- storage_size_classes: if storage_size_classes.iter().all(|size_class| size_class.allocator != 0) {- storage_size_classes- } else {- Vec::new()- },- storage_template: value_storage::cell_header_template().to_vec(),+ storage_size_classes,+ storage_template: snapshot.add(&value_storage::cell_header_template()[..]),storage_values_offset: offset(VALUES_OFFSET),storage_capacity_offset: offset(value_storage::CAPACITY_OFFSET),slow_path: jit_function_address!(libjs_jit_allocate_array),};- let rope_template = rope_template(vm);+ let rope_template = rope_template(vm, snapshot);let rope = RopeAllocationInfo {allocator: address(heap.local_free_list_of(RopeString::CLASS)),cell_size: size(size_of::<RopeString>()),@@ -192,13 +214,16 @@ fn header_of<T: Extends<CellHeader>>(cell: Gc<T>) -> Gc<CellHeader> {}/// The bytes of a new rope string, with null halves.-fn rope_template(vm: &Vm) -> Vec<u64> {+fn rope_template(vm: &Vm, snapshot: &mut SnapshotWriter) -> List<u64> {let half = PrimitiveString::create_from_utf8(vm, "ropes are made of two halves");let rope = PrimitiveString::create_from_concatenation(vm, half, half).must();assert!(class_of(rope).is_subclass_of(RopeString::CLASS));- let mut words = cell_words(rope, size_of::<RopeString>());- clear_bytes(&mut words, ROPE_STRING_LHS_OFFSET, 4);- clear_bytes(&mut words, ROPE_STRING_RHS_OFFSET, 4);+ let words = cell_words(snapshot, rope, size_of::<RopeString>());+ // NB: A snapshot that had no room for the words does not have all of them (see `Snapshot::is_complete()`).+ if snapshot.is_complete() {+ clear_bytes(&mut snapshot[words], ROPE_STRING_LHS_OFFSET, 4);+ clear_bytes(&mut snapshot[words], ROPE_STRING_RHS_OFFSET, 4);+ }words}@@ -333,7 +358,6 @@ pub fn make_call_environment_template(vm: &Vm, function: Gc<EcmascriptFunctionOb} else {size_of::<DeclarativeEnvironment>()};- let words = cell_words(environment, cell_bytes);let mut template = CallEnvironmentTemplate {header: CellHeader::for_class(CallEnvironmentTemplate::CLASS),size_class: size_class as u64,@@ -347,7 +371,11 @@ pub fn make_call_environment_template(vm: &Vm, function: Gc<EcmascriptFunctionObhas_function_fields: u64::from(has_function_fields),words: [0; FUNCTION_ENVIRONMENT_WORDS],};- template.words[..words.len()].copy_from_slice(&words);+ let mut word_count = 0;+ for_each_cell_word(environment, cell_bytes, |word| {+ template.words[word_count] = word;+ word_count += 1;+ });for (offset, size) in [(core::mem::offset_of!(DeclarativeEnvironment, binding_values), 8),(@@ -374,6 +402,7 @@ pub fn make_call_environment_template(vm: &Vm, function: Gc<EcmascriptFunctionObpub fn function_environment_template(vm: &Vm,function: Gc<EcmascriptFunctionObject>,+ snapshot: &mut SnapshotWriter,mut cell: impl FnMut(Gc<CellHeader>) -> CellId,) -> Option<EnvironmentTemplateSnapshot> {if !function.function_environment_needed() {@@ -397,20 +426,24 @@ pub fn function_environment_template(if !sample.rare_data.is_null() || sample.binding_values_are_inline() != (binding_count != 0) {return None;}- let mut cells = Vec::new();- if let Some(shape) = sample.shape.get() {- cells.push(cell(header_of(shape)));- } else if binding_count != 0 {+ let shape = sample.shape.get();+ if shape.is_none() && binding_count != 0 {return None;}+ let cells = snapshot.begin();+ if let Some(shape) = shape {+ snapshot.push(cell(header_of(shape)));+ }if let Some(outer) = sample.outer.get() {- cells.push(cell(header_of(outer)));+ snapshot.push(cell(header_of(outer)));}- cells.push(cell(header_of(function)));+ snapshot.push(cell(header_of(function)));+ let cells = snapshot.end(cells);Some(EnvironmentTemplateSnapshot {allocator: allocator.as_ptr() as u64,cell_size,words: cell_words(+ snapshot,sample,if has_function_fields {size_of::<FunctionEnvironment>()@@ -433,11 +466,13 @@ pub fn lexical_environment_templates(vm: &Vm,executable: Gc<Executable>,realm: Gc<Realm>,+ snapshot: &mut SnapshotWriter,mut cell: impl FnMut(Gc<CellHeader>) -> CellId,-) -> Vec<Option<LexicalEnvironmentTemplateSnapshot>> {+) -> List<Option<LexicalEnvironmentTemplateSnapshot>> {let heap = vm.heap();- (0..executable.environment_shape_cache_count())- .map(|index| {+ let templates = snapshot.begin();+ for index in 0..executable.environment_shape_cache_count() {+ let template = (|| {let cache = executable.environment_shape_cache(index);let shape = cache.shape();let binding_count = shape.map_or(0, |shape| shape.size());@@ -466,15 +501,17 @@ pub fn lexical_environment_templates(Some(LexicalEnvironmentTemplateSnapshot {allocator: allocator.as_ptr() as u64,cell_size,- words: cell_words(sample, size_of::<DeclarativeEnvironment>()),+ words: cell_words(snapshot, sample, size_of::<DeclarativeEnvironment>()),binding_count: u32::try_from(binding_count).ok()?,inline_binding_values: binding_count != 0,binding_values_offset: offset(core::mem::offset_of!(DeclarativeEnvironment, binding_values)),outer_offset: offset(core::mem::offset_of!(Environment, outer)),shape: shape.map(|shape| cell(header_of(shape))),})- })- .collect()+ })();+ snapshot.push(template);+ }+ snapshot.end(templates)}/// `Environment* libjs_jit_create_lexical_environment(VM*, Environment* parent, Executable*, u32 shape_cache, u32@@ -500,7 +537,7 @@ pub extern "C" fn libjs_jit_create_lexical_environment(}/// The sample of each closure template with its words, by shared function data index.-pub type ClosureTemplates = Vec<Option<(Gc<EcmascriptFunctionObject>, Vec<u64>)>>;+pub type ClosureTemplates = Vec<Option<(Gc<EcmascriptFunctionObject>, List<u64>)>>;/// The closures JIT code of `executable`, whose frames run `function`, creates with each `NewFunction` (by shared/// function data index) by copying a sample (see `FunctionAllocationInfo`), or None for those it cannot.@@ -509,12 +546,13 @@ pub fn closure_templates<'d>(executable: Gc<Executable>,function: Gc<EcmascriptFunctionObject>,defer_gc: &'d DeferGc<'_>,+ snapshot: &mut SnapshotWriter,) -> Deferred<'d, ClosureTemplates> {defer_gc.cover((0..executable.shared_function_data_count()).map(|index| {let shared_data = executable.shared_function_data(u32::try_from(index).ok()?);- closure_template(vm, function, shared_data)+ closure_template(vm, function, shared_data, snapshot)}).collect(),)@@ -524,7 +562,8 @@ fn closure_template(vm: &Vm,function: Gc<EcmascriptFunctionObject>,shared_data: Gc<SharedFunctionInstanceData>,-) -> Option<(Gc<EcmascriptFunctionObject>, Vec<u64>)> {+ snapshot: &mut SnapshotWriter,+) -> Option<(Gc<EcmascriptFunctionObject>, List<u64>)> {// NB: Only the closures of plain functions are copies of each other apart from their environments.if shared_data.kind() != FunctionKind::Normal || shared_data.is_class_constructor() {return None;@@ -546,7 +585,7 @@ fn closure_template(if !sample.can_be_copied() {return None;}- let words = cell_words(sample, size_of::<EcmascriptFunctionObject>());+ let words = cell_words(snapshot, sample, size_of::<EcmascriptFunctionObject>());Some((sample, words))}@@ -555,17 +594,17 @@ pub fn closure_template_snapshots(templates: ClosureTemplates,mut cell: impl FnMut(Gc<EcmascriptFunctionObject>) -> CellId,_defer_gc: &DeferGc<'_>,-) -> Vec<Option<ClosureTemplateSnapshot>> {- templates- .into_iter()- .map(|template| {- template.map(|(sample, words)| ClosureTemplateSnapshot {- sample: cell(sample),- words,- inline_executable: None,- })- })- .collect()+ snapshot: &mut SnapshotWriter,+) -> List<Option<ClosureTemplateSnapshot>> {+ let rows = snapshot.begin();+ for template in templates {+ snapshot.push(template.map(|(sample, words)| ClosureTemplateSnapshot {+ sample: cell(sample),+ words,+ inline_executable: None,+ }));+ }+ snapshot.end(rows)}/// `Object* libjs_jit_allocate_object(VM*, Shape*, u32 reserve)`: a plain object of the shape, every named propertydiff --git a/Libraries/LibJS/Rust/src/jit/compile_queue.rs b/Libraries/LibJS/Rust/src/jit/compile_queue.rsindex a8ad8a26e5c..21843ce9445 100644--- a/Libraries/LibJS/Rust/src/jit/compile_queue.rs+++ b/Libraries/LibJS/Rust/src/jit/compile_queue.rs@@ -5,7 +5,8 @@*///! A VM's share of the compile threads of the process. Only snapshots go to them and only compile results come back: the-//! compiler never sees the heap.+//! compiler never sees the heap. Snapshots and results keep their memory, which serves one compile after the other+//! (see `Spare`).use core::ops::Deref;use std::cell::{Cell, RefCell};@@ -18,13 +19,18 @@ use libjs_jit::CompileFailure;use libjs_jit::code::CompiledCode;use libjs_jit::compile_pool::{CompilePool, CompilePoolClient};use libjs_jit::scratch::Scratch;-use libjs_jit::snapshot::Snapshot;+use libjs_jit::snapshot::{OpenLists, Snapshot};pub type CompileResult = Result<Compiled, CompileFailure>;/// How many results of compiles that nothing uses now keep their memory for the next compiles.const SPARE_RESULTS: usize = 32;+/// How many snapshots that nothing uses now keep their memory for the next compiles. Nearly always, fewer snapshots+/// than this wait for a compile at one time, so the memory of a snapshot seldom comes from the system or goes back+/// there while compiles run.+const SPARE_SNAPSHOTS: usize = 16;+/// How many bytes of code and words of tables such a result keeps the memory for when a compile takes it: the first/// step a column grows by. The thread that compiles gives the rest back to the system, so that the thread of a VM,/// which brings the results back, does not pay for that. A result that keeps more than this keeps pages that the@@ -32,16 +38,26 @@ const SPARE_RESULTS: usize = 32;const SPARE_CODE_BYTES: usize = 64 * 1024;const SPARE_TABLE_WORDS: usize = 8 * 1024;-/// The results that nothing uses now. A compile thread writes the code and the tables of a compile into one, and the-/// thread of the VM that asked for the compile brings it back.+/// How many threads that capture snapshots at one time find the memory of an earlier capture for the lists they+/// write row by row.+const SPARE_OPEN_LISTS: usize = 2;++/// The snapshots and the results that nothing uses now, and the memory that captures write with. The thread of a VM+/// writes the input of a compile into a snapshot, and the compile thread that read it brings it back. A compile+/// thread writes the code and the tables of a compile into a result, and the thread of the VM that asked for the+/// compile brings it back.struct Spare {+ snapshots: [Option<Box<Snapshot>>; SPARE_SNAPSHOTS],+ open_lists: [Option<OpenLists>; SPARE_OPEN_LISTS],results: [Option<CompiledCode>; SPARE_RESULTS],/// How many compile threads had a task since they last were idle. The last of them to go idle gives the memory- /// of the results back to the system.+ /// of the snapshots and of the results back to the system.active_thread_count: usize,}static SPARE: Mutex<Spare> = Mutex::new(Spare {+ snapshots: [const { None }; SPARE_SNAPSHOTS],+ open_lists: [const { None }; SPARE_OPEN_LISTS],results: [const { None }; SPARE_RESULTS],active_thread_count: 0,});@@ -65,14 +81,29 @@ fn note_thread_is_active() {}}-/// The task of a compile thread for a result that came back while all of them were idle (see `Compiled::drop()`),-/// which counted the thread as active already.-fn stay_active_for_late_result() {+/// The task of a compile thread for spare memory that came back while all of them were idle (see+/// `release_spare_memory_later()`), which counted the thread as active already.+fn stay_active_for_late_memory() {if THREAD_IS_ACTIVE.replace(true) {spare().active_thread_count -= 1;}}+/// Makes sure that a compile thread gives the spare memory back to the system, after something came back into+/// `spare`. If the compile threads are idle, none of them is going to do that. This makes one of them go idle again,+/// so that the thread of a VM does not pay for it. Without compile threads, the memory stays for the next compile.+fn release_spare_memory_later(mut spare: MutexGuard<'static, Spare>) {+ if spare.active_thread_count > 0 {+ return;+ }+ let Some(pool) = POOL.get() else {+ return;+ };+ spare.active_thread_count += 1;+ drop(spare);+ pool.run_unowned(Box::new(stay_active_for_late_memory));+}+/// Notes that this compile thread went idle.fn note_thread_is_idle() {if !THREAD_IS_ACTIVE.replace(false) {@@ -83,12 +114,53 @@ fn note_thread_is_idle() {if spare.active_thread_count > 0 {return;}+ let snapshots = core::mem::replace(&mut spare.snapshots, [const { None }; SPARE_SNAPSHOTS]);+ let open_lists = core::mem::replace(&mut spare.open_lists, [const { None }; SPARE_OPEN_LISTS]);let results = core::mem::replace(&mut spare.results, [const { None }; SPARE_RESULTS]);drop(spare);- // NB: The memory goes back to the system here, with the lock released.+ // NB: The memory is given back here, with the lock released.+ drop(snapshots);+ drop(open_lists);drop(results);}+/// A snapshot of nothing, to capture into. It has the memory of an earlier snapshot if one is spare.+pub fn spare_snapshot() -> Box<Snapshot> {+ let snapshot = spare().snapshots.iter_mut().find_map(Option::take);+ snapshot.unwrap_or_default()+}++/// The memory for the lists that a capture writes row by row. It is the memory of an earlier capture if that is+/// spare.+pub fn spare_open_lists() -> OpenLists {+ let lists = spare().open_lists.iter_mut().find_map(Option::take);+ lists.unwrap_or_default()+}++/// Takes back the memory for the lists that a capture wrote row by row, for a later capture.+pub fn give_back_open_lists(lists: OpenLists) {+ let mut spare = spare();+ // NB: With no place left, the memory goes back to the system here.+ let Some(place) = spare.open_lists.iter_mut().find(|place| place.is_none()) else {+ return;+ };+ *place = Some(lists);+ release_spare_memory_later(spare);+}++/// Takes back a snapshot that nothing reads anymore, for a later capture.+pub fn give_back_snapshot(mut snapshot: Box<Snapshot>) {+ snapshot.clear();+ snapshot.trim();+ let mut spare = spare();+ // NB: With no place left, the memory of the snapshot goes back to the system here.+ let Some(place) = spare.snapshots.iter_mut().find(|place| place.is_none()) else {+ return;+ };+ *place = Some(snapshot);+ release_spare_memory_later(spare);+}+/// The code of a finished compile, on its way to where it is installed. The code and its tables are in memory that is/// no block of the heap (see `CompiledCode`), which serves a later compile once this is dropped.pub struct Compiled {@@ -131,18 +203,7 @@ impl Drop for Compiled {return;};*place = Some(code);- if spare.active_thread_count > 0 {- return;- }- // NB: The compile threads are idle, so none of them is going to give the memory of this result back. This- // makes one of them go idle again, so that the thread of a VM does not pay for that. Without compile- // threads, the result stays for the next compile on this thread.- let Some(pool) = POOL.get() else {- return;- };- spare.active_thread_count += 1;- drop(spare);- pool.run_unowned(Box::new(stay_active_for_late_result));+ release_spare_memory_later(spare);}}@@ -207,6 +268,7 @@ impl CompileQueue {let _scratch = ak::ScratchHeapScope::enter();compile(&snapshot)};+ give_back_snapshot(snapshot);// NB: A VM that went away has no use for the result, and the thread goes on with other VMs' jobs.if result_sender.send((id, result)).is_ok() {results_pending.store(true, Ordering::Release);diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 4ea3fd487d3..ede2a135fa4 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -18,9 +18,9 @@ use libjs_jit::snapshot::{DerivedInstanceFields, DirectCallTarget, DirectGetterFields, EnvironmentTemplateSnapshot, ExecutableSnapshot,FeedbackSnapshot, ForwardedCallSnapshot, Forwarding, FunctionFrameFields, GlobalCacheSnapshot, GlobalValueSnapshot,GlobalsSnapshot, InlinedFunctionSnapshot, InliningLimits, Intrinsic, KeyedFeedbackSnapshot,- LexicalEnvironmentTemplateSnapshot, NativeCallTarget, ObjectShapeCacheSnapshot, OrdinaryHasInstanceSnapshot,- PropertyCacheEntrySnapshot, PropertyCacheEntryType, PropertyCacheKind, PropertyCacheSnapshot, ShapeSnapshot,- Snapshot, StressOptions, SuperBaseSnapshot, SuperConstructTarget, TypedArraySnapshot,+ LexicalEnvironmentTemplateSnapshot, List, NativeCallTarget, ObjectShapeCacheSnapshot, OrdinaryHasInstanceSnapshot,+ PropertyCacheEntrySnapshot, PropertyCacheEntryType, PropertyCacheKind, PropertyCacheSnapshot, Row, ShapeSnapshot,+ Snapshot, SnapshotWriter, StressOptions, SuperBaseSnapshot, SuperConstructTarget, TypedArraySnapshot,};use super::allocation::{@@ -99,6 +99,8 @@ struct Entry {struct SnapshotBuilder<'vm> {vm: &'vm Vm,defer_gc: &'vm DeferGc<'vm>,+ /// The snapshot that is being captured.+ snapshot: SnapshotWriter,cells: Vec<Gc<CellHeader>>,entries: Vec<Entry>,indices: HashMap<InlinedFunction, u32>,@@ -106,13 +108,13 @@ struct SnapshotBuilder<'vm> {compiled_function: Option<Gc<EcmascriptFunctionObject>>,/// The words the compiled executable's frames start with (see `FunctionFrameFields`).compiled_function_fields: FunctionFrameFields,- /// The closure templates of the compiled executable, until its snapshot takes them.- closure_templates: Vec<Option<ClosureTemplateSnapshot>>,+ /// The closure templates of the compiled executable.+ closure_templates: List<Option<ClosureTemplateSnapshot>>,/// The samples of the closure templates of inlined functions, by executable and template index, until the/// inlining candidates they are get their indices.closure_samples: Vec<(u32, usize, Gc<EcmascriptFunctionObject>)>,- /// The lexical environment templates of the compiled executable, until its snapshot takes them.- lexical_environment_templates: Vec<Option<LexicalEnvironmentTemplateSnapshot>>,+ /// The lexical environment templates of the compiled executable.+ lexical_environment_templates: List<Option<LexicalEnvironmentTemplateSnapshot>>,/// The environment templates of the direct calls of the executable whose snapshot is being made.environment_templates: Vec<EnvironmentTemplateSnapshot>,/// The bound arguments of the call feedback of the executable whose snapshot is being made.@@ -125,7 +127,7 @@ struct SnapshotBuilder<'vm> {super_constructors: HashMap<u32, SuperConstructTarget>,/// For the base constructors with fields among the inlining candidates, by index: the values of their fields (see/// `ExecutableSnapshot::literal_instance_fields`).- literal_instance_fields: HashMap<u32, Vec<(u32, u64)>>,+ literal_instance_fields: HashMap<u32, LiteralFieldValues>,/// For the derived constructors with fields among the inlining candidates, by index: how they add their fields/// (see `ExecutableSnapshot::derived_instance_fields`).derived_instance_fields: HashMap<u32, DerivedInstanceFields>,@@ -136,7 +138,7 @@ struct SnapshotBuilder<'vm> {type FieldDefinition = (u32, u64, Option<CellId>);/// The values of literal fields, by property offset (see `ExecutableSnapshot::literal_instance_fields`).-type LiteralFieldValues = Vec<(u32, u64)>;+type LiteralFieldValues = List<(u32, u64)>;/// The number of bytecode instructions of an executable, counted up to one past `limit`.fn instruction_count(executable: &Executable, limit: u32) -> u32 {@@ -400,11 +402,24 @@ fn function_frame_fields(function: Gc<EcmascriptFunctionObject>) -> FunctionFram}}+/// Adds `cell` to `cells`, the cells a snapshot refers to, and returns what the snapshot knows it as.+fn note_cell<T: Extends<CellHeader>>(cells: &mut Vec<Gc<CellHeader>>, cell: Gc<T>) -> CellId {+ cells.push(cell.upcast::<CellHeader>());+ CellId(cell.as_ptr() as u64)+}+impl SnapshotBuilder<'_> {fn cell<T: Extends<CellHeader>>(&mut self, cell: Gc<T>) -> CellId {- let header = cell.upcast::<CellHeader>();- self.cells.push(header);- CellId(cell.as_ptr() as u64)+ note_cell(&mut self.cells, cell)+ }++ /// Adds `rows` to the snapshot as a list.+ fn list<T: Row>(&mut self, rows: impl IntoIterator<Item = T>) -> List<T> {+ let list = self.snapshot.begin();+ for row in rows {+ self.snapshot.push(row);+ }+ self.snapshot.end(list)}fn optional_cell<T: Extends<CellHeader>>(&mut self, cell: Option<Gc<T>>) -> Option<CellId> {@@ -442,7 +457,7 @@ impl SnapshotBuilder<'_> {realm.boolean_prototype(self.vm).shape(),];let mut sees_primitives = false;- let mut entries = Vec::new();+ let entries = self.snapshot.begin();let known_shape_slot = known_shape.and_then(|shape| cache.megamorphic_entry_for_shape(shape, 0));let slots = match known_shape_slot {Some(slot) => core::slice::from_ref(slot),@@ -497,7 +512,7 @@ impl SnapshotBuilder<'_> {native: self.native_accessor_target(function, cell, entry.getter == Some(function)),}});- entries.push(PropertyCacheEntrySnapshot {+ let row = PropertyCacheEntrySnapshot {entry_type,property_offset: entry.property_offset,shape_dictionary_generation: entry.shape.map_or(0, |key| key.dictionary_generation),@@ -538,12 +553,16 @@ impl SnapshotBuilder<'_> {accessor_function,property_holds_data: property_holds_data(&entry),holds_accessor: entry_holds_accessor(&entry),- });+ };+ self.snapshot.push(row);}if sees_primitives {- entries.clear();+ self.snapshot.drop_rows(&entries);+ }+ PropertyCacheSnapshot {+ kind,+ entries: self.snapshot.end(entries),}- PropertyCacheSnapshot { kind, entries }}/// What the global variable caches of `executable`, whose frames run in the realm of `caller`, know about the global@@ -554,10 +573,12 @@ impl SnapshotBuilder<'_> {let environment = realm.global_declarative_environment();let environment_serial = environment.environment_serial_number();let shape = object.shape();- let mut caches = Vec::with_capacity(executable.global_variable_caches().len());+ let caches = self.snapshot.begin();for cache in executable.global_variable_caches() {- caches.push(self.global_cache(cache, object, environment, environment_serial, shape, caller));+ let row = self.global_cache(cache, object, environment, environment_serial, shape, caller);+ self.snapshot.push(row);}+ let caches = self.snapshot.end(caches);GlobalsSnapshot {object: self.cell(object),declarative_environment: self.cell(environment),@@ -982,10 +1003,8 @@ impl SnapshotBuilder<'_> {shape: Gc<Shape>,) -> Option<(Gc<Shape>, LiteralFieldValues)> {let (shape, fields) = self.literal_field_definitions(constructor, shape, false)?;- Some((- shape,- fields.into_iter().map(|(offset, value, _)| (offset, value)).collect(),- ))+ let values = self.list(fields.into_iter().map(|(offset, value, _)| (offset, value)));+ Some((shape, values))}/// How InitializeInstanceElements of the derived constructor `constructor` defines its fields on objects of the@@ -1008,7 +1027,7 @@ impl SnapshotBuilder<'_> {}Some(DerivedInstanceFields {shape: self.cell(shape),- fields,+ fields: self.snapshot.add(&fields),})}@@ -1064,7 +1083,9 @@ impl SnapshotBuilder<'_> {if !function.function_environment_needed() {return Some(None);}- let template = function_environment_template(self.vm, function, |cell| self.cell(cell))?;+ let cells = &mut self.cells;+ let template =+ function_environment_template(self.vm, function, &mut self.snapshot, |cell| note_cell(cells, cell))?;let index = u32::try_from(self.environment_templates.len()).ok()?;self.environment_templates.push(template);Some(Some(index))@@ -1188,19 +1209,25 @@ impl SnapshotBuilder<'_> {&mut self,entry: &Entry,function: Gc<EcmascriptFunctionObject>,- ) -> Vec<Option<ClosureTemplateSnapshot>> {+ ) -> List<Option<ClosureTemplateSnapshot>> {if function.private_environment().is_some() {- return Vec::new();+ return List::empty();}let index = self.indices[&InlinedFunction::Ecmascript(function)];let defer_gc = self.defer_gc;- let templates = closure_templates(self.vm, entry.executable, function, defer_gc);+ let templates = closure_templates(self.vm, entry.executable, function, defer_gc, &mut self.snapshot);for (template_index, template) in templates.iter().enumerate() {if let Some((sample, _)) = template {self.closure_samples.push((index, template_index, *sample));}}- closure_template_snapshots(templates.into_inner(), |sample| self.cell(sample), defer_gc)+ let cells = &mut self.cells;+ closure_template_snapshots(+ templates.into_inner(),+ |sample| note_cell(cells, sample),+ defer_gc,+ &mut self.snapshot,+ )}/// The snapshot of an executable of the snapshot.@@ -1220,52 +1247,56 @@ impl SnapshotBuilder<'_> {// NB: Executables that never left the plain tier have no feedback arrays yet, and an inlined callee may be one.let feedback = executable.ensure_feedback();feedback.update_value_feedback();- let call = feedback- .call()- .iter()- .map(|call| self.call_feedback(call, entry))- .collect();- let keyed = feedback- .keyed()- .iter()- .map(|keyed| KeyedFeedbackSnapshot { bits: keyed.bits.get() })- .collect();+ let call = self.snapshot.begin();+ for call in feedback.call() {+ let row = self.call_feedback(call, entry);+ self.snapshot.push(row);+ }+ let call = self.snapshot.end(call);+ let keyed = self.list(+ feedback+ .keyed()+ .iter()+ .map(|keyed| KeyedFeedbackSnapshot { bits: keyed.bits.get() }),+ );let feedback = FeedbackSnapshot {- arith: feedback.arith().iter().map(core::cell::Cell::get).collect(),- value: feedback.value().iter().map(core::cell::Cell::get).collect(),- cache_value: feedback.cache_value().iter().map(core::cell::Cell::get).collect(),+ arith: self.list(feedback.arith().iter().map(core::cell::Cell::get)),+ value: self.list(feedback.value().iter().map(core::cell::Cell::get)),+ cache_value: self.list(feedback.cache_value().iter().map(core::cell::Cell::get)),call,keyed,- bound_arguments: core::mem::take(&mut self.bound_arguments),+ bound_arguments: self.snapshot.add(&self.bound_arguments),};+ self.bound_arguments.clear();let index = entry.function.and_then(|function| self.indices.get(&function));let construct_this_shape = index.and_then(|index| self.construct_this_shapes.get(index)).copied();let super_constructor = index.and_then(|index| self.super_constructors.get(index)).copied();- let literal_instance_fields = index.and_then(|index| self.literal_instance_fields.get(index)).cloned();- let derived_instance_fields = index.and_then(|index| self.derived_instance_fields.get(index)).cloned();+ let literal_instance_fields = index.and_then(|index| self.literal_instance_fields.get(index)).copied();+ let derived_instance_fields = index.and_then(|index| self.derived_instance_fields.get(index)).copied();let has_instance_elements =matches!(entry.function, Some(InlinedFunction::Ecmascript(function)) if function.has_class_data());- let property_caches = executable- .property_lookup_caches()- .iter()- .map(|cache| self.property_cache(cache, entry, construct_this_shape))- .collect();- let object_shape_caches = executable- .object_shape_caches()- .iter()- .map(|cache| {- let shape = cache.shape.get()?;- Some(ObjectShapeCacheSnapshot {- shape: self.shape(shape),- property_offsets: cache.property_offsets.borrow().clone(),- })- })- .collect();+ let property_caches = self.snapshot.begin();+ for cache in executable.property_lookup_caches() {+ let row = self.property_cache(cache, entry, construct_this_shape);+ self.snapshot.push(row);+ }+ let property_caches = self.snapshot.end(property_caches);+ let object_shape_caches = self.snapshot.begin();+ for cache in executable.object_shape_caches() {+ let row = cache.shape.get().map(|shape| ObjectShapeCacheSnapshot {+ shape: self.shape(shape),+ property_offsets: self.snapshot.add(&cache.property_offsets.borrow()),+ });+ self.snapshot.push(row);+ }+ let object_shape_caches = self.snapshot.end(object_shape_caches);+ let environment_templates = self.snapshot.add(&self.environment_templates);+ self.environment_templates.clear();let intrinsics = realm.intrinsics();ExecutableSnapshot {- bytecode: bytecode.to_vec(),+ bytecode: self.snapshot.add(bytecode),bytecode_address: bytecode.as_ptr() as u64,layout: FrameLayout {number_of_registers: executable.number_of_registers(),@@ -1274,25 +1305,22 @@ impl SnapshotBuilder<'_> {.expect("the constant count fits in u32"),number_of_arguments: executable.number_of_arguments(),},- constants: executable.constants().iter().map(|constant| constant.0).collect(),- exception_handlers: executable- .exception_handlers()- .iter()- .map(|handler| ExceptionHandler {- start_offset: handler.start_offset,- end_offset: handler.end_offset,- handler_offset: handler.handler_offset,- })- .collect(),- exit_sites: executable.jit_exit_sites_for_recompile(),+ constants: self.list(executable.constants().iter().map(|constant| constant.0)),+ exception_handlers: self.list(executable.exception_handlers().iter().map(|handler| ExceptionHandler {+ start_offset: handler.start_offset,+ end_offset: handler.end_offset,+ handler_offset: handler.handler_offset,+ })),+ exit_sites: self.snapshot.add(&executable.jit_exit_sites_for_recompile()),builtin_exit_sites: if entry.function.is_none() {- executable- .jit_builtin_exit_sites()- .into_iter()- .map(|(builtin, pc, kind)| (CellId(builtin), pc, kind))- .collect()+ self.list(+ executable+ .jit_builtin_exit_sites()+ .into_iter()+ .map(|(builtin, pc, kind)| (CellId(builtin), pc, kind)),+ )} else {- Vec::new()+ List::empty()},feedback,property_caches,@@ -1318,7 +1346,7 @@ impl SnapshotBuilder<'_> {.map(|function| self.captured_bindings(function, executable, realm)).unwrap_or_default(),mutable_bindings: arguments_function- .map(|function| mutable_bindings(function, executable))+ .map(|function| mutable_bindings(&mut self.snapshot, function, executable)).unwrap_or_default(),builtin: matches!(entry.function, Some(InlinedFunction::Builtin(_))),mapped_arguments_alias_parameters: arguments_function@@ -1331,15 +1359,15 @@ impl SnapshotBuilder<'_> {boolean_prototype: Some(self.cell(realm.boolean_prototype(vm))),object_shape_caches,closure_templates: match entry.function {- None => core::mem::take(&mut self.closure_templates),+ None => self.closure_templates,Some(InlinedFunction::Ecmascript(function)) => self.inlined_closure_templates(entry, function),- Some(InlinedFunction::Builtin(_)) => Vec::new(),+ Some(InlinedFunction::Builtin(_)) => List::empty(),},- environment_templates: core::mem::take(&mut self.environment_templates),+ environment_templates,lexical_environment_templates: if entry.function.is_none() {- core::mem::take(&mut self.lexical_environment_templates)+ self.lexical_environment_templates} else {- Vec::new()+ List::empty()},// NB: Builtins written in JavaScript never access global variables by name.globals: (!matches!(entry.function, Some(InlinedFunction::Builtin(_))))@@ -1350,25 +1378,22 @@ impl SnapshotBuilder<'_> {derived_instance_fields,// NB: Only the compiled function's own code creates bindings by name.identifiers: if entry.function.is_none() {- executable- .identifier_table()- .iter()- .map(|identifier| identifier.raw_identity() as u64)- .collect()+ self.list(+ executable+ .identifier_table()+ .iter()+ .map(|identifier| identifier.raw_identity() as u64),+ )} else {- Vec::new()+ List::empty()},- property_key_names: executable- .property_keys()- .iter()- .map(|key| {- if key.is_string() {- key.as_string().raw_identity() as u64- } else {- 0- }- })- .collect(),+ property_key_names: self.list(executable.property_keys().iter().map(|key| {+ if key.is_string() {+ key.as_string().raw_identity() as u64+ } else {+ 0+ }+ })),}}@@ -1381,9 +1406,9 @@ impl SnapshotBuilder<'_> {function: Gc<EcmascriptFunctionObject>,executable: Gc<Executable>,realm: Gc<Realm>,- ) -> Vec<(EnvironmentCoordinate, GlobalValueSnapshot)> {+ ) -> List<(EnvironmentCoordinate, GlobalValueSnapshot)> {if function.allocates_function_environment() || function.shared_data().closure_count() != ClosureCount::One {- return Vec::new();+ return List::empty();}let loads = &executable.jit_state()@@ -1396,9 +1421,14 @@ impl SnapshotBuilder<'_> {.filter(|&&(_, pc)| exit_sites.contains(&(pc, ExitKind::UnexpectedValue))).map(|&(coordinate, _)| coordinate).collect();- let mut bindings: Vec<(EnvironmentCoordinate, GlobalValueSnapshot)> = Vec::new();+ let bindings = self.snapshot.begin::<(EnvironmentCoordinate, GlobalValueSnapshot)>();for &(coordinate, _) in loads {- if changed.contains(&coordinate) || bindings.iter().any(|(captured, _)| *captured == coordinate) {+ let is_captured = self+ .snapshot+ .rows_of(&bindings)+ .iter()+ .any(|(captured, _)| *captured == coordinate);+ if changed.contains(&coordinate) || is_captured {continue;}let mut environment = function.environment();@@ -1419,28 +1449,33 @@ impl SnapshotBuilder<'_> {}let value = environment.get_initialized_binding_value_direct(coordinate.index as usize);if value.is_object() {- bindings.push((coordinate, self.global_value(value, realm, None)));+ let row = (coordinate, self.global_value(value, realm, None));+ self.snapshot.push(row);}}- bindings+ self.snapshot.end(bindings)}}/// The bindings of the environments of `function`'s closure that `executable` stores to and that are mutable in every/// instance of their environment: declared mutable, and never deleted. Its stores to them need no check of that. Like/// captured bindings, these are only found while the function has no other closure.-fn mutable_bindings(function: Gc<EcmascriptFunctionObject>, executable: Gc<Executable>) -> Vec<EnvironmentCoordinate> {+fn mutable_bindings(+ snapshot: &mut SnapshotWriter,+ function: Gc<EcmascriptFunctionObject>,+ executable: Gc<Executable>,+) -> List<EnvironmentCoordinate> {if function.allocates_function_environment() || function.shared_data().closure_count() != ClosureCount::One {- return Vec::new();+ return List::empty();}let stores = &executable.jit_state().captured_binding_accesses.get_or_init(|| captured_binding_accesses(&executable)).stores;- let mut bindings = Vec::new();+ let bindings = snapshot.begin();for &coordinate in stores {- if bindings.contains(&coordinate) {+ if snapshot.rows_of(&bindings).contains(&coordinate) {continue;}let mut environment = function.environment();@@ -1454,10 +1489,10 @@ fn mutable_bindings(function: Gc<EcmascriptFunctionObject>, executable: Gc<Execucontinue;};if environment.binding_is_declared_mutable(coordinate.index as usize) {- bindings.push(coordinate);+ snapshot.push(coordinate);}}- bindings+ snapshot.end(bindings)}/// The loads and stores of bindings of environments in `executable`, or none if its code may change its lexical@@ -1519,11 +1554,15 @@ pub fn capture_snapshot<'d>(..FunctionFrameFields::default()},};+ let mut snapshot = SnapshotWriter::new(+ super::compile_queue::spare_snapshot(),+ super::compile_queue::spare_open_lists(),+ );// NB: These allocate (and so may collect garbage), which they do before anything is captured.- let allocation = allocation_infos(vm, realm, defer_gc);+ let allocation = allocation_infos(vm, realm, defer_gc, &mut snapshot);// NB: Closures that top-level code creates have its environments, which the code does not know.let closure_templates = match function {- Some(function) => closure_templates(vm, executable, function, defer_gc),+ Some(function) => closure_templates(vm, executable, function, defer_gc, &mut snapshot),None => defer_gc.cover((0..executable.shared_function_data_count()).map(|_| None).collect()),};let closure_samples = closure_templates@@ -1533,6 +1572,7 @@ pub fn capture_snapshot<'d>(let mut builder = SnapshotBuilder {vm,defer_gc,+ snapshot,cells: (*allocation.cells).clone(),entries: vec![Entry {executable,@@ -1543,26 +1583,33 @@ pub fn capture_snapshot<'d>(indices: HashMap::new(),compiled_function: function,compiled_function_fields,- closure_templates: Vec::new(),+ closure_templates: List::empty(),closure_samples: Vec::new(),environment_templates: Vec::new(),bound_arguments: Vec::new(),- lexical_environment_templates: Vec::new(),+ lexical_environment_templates: List::empty(),construct_this_shapes: HashMap::new(),super_constructors: HashMap::new(),literal_instance_fields: HashMap::new(),derived_instance_fields: HashMap::new(),};- builder.closure_templates =- closure_template_snapshots(closure_templates.into_inner(), |sample| builder.cell(sample), defer_gc);+ let cells = &mut builder.cells;+ builder.closure_templates = closure_template_snapshots(+ closure_templates.into_inner(),+ |sample| note_cell(cells, sample),+ defer_gc,+ &mut builder.snapshot,+ );builder.lexical_environment_templates =- lexical_environment_templates(vm, executable, realm, |cell| builder.cell(cell));+ lexical_environment_templates(vm, executable, realm, &mut builder.snapshot, |cell| {+ note_cell(cells, cell)+ });// NB: executable_snapshot() appends the inlining candidates it finds.- let mut executables = Vec::new();let mut index = 0;while index < builder.entries.len() {let entry = builder.entries[index];- executables.push(builder.executable_snapshot(&entry));+ let row = builder.executable_snapshot(&entry);+ builder.snapshot.add_executable(row);index += 1;}// NB: Calls of closures the code creates can be inlined without feedback, as calls of the function its closure@@ -1578,16 +1625,19 @@ pub fn capture_snapshot<'d>(for (executable_index, template_index, sample) in samples {let creator = builder.entries[executable_index as usize];let inline_executable = builder.inline_executable_index(Some(sample.upcast::<CellHeader>()), &creator);- if let Some(Some(template)) = executables[executable_index as usize]- .closure_templates- .get_mut(template_index)- {+ // NB: A snapshot that had no room for an executable has no row for it (see `Snapshot::is_complete()`).+ let Some(executable) = builder.snapshot.executables.get(executable_index as usize) else {+ continue;+ };+ let templates = executable.closure_templates;+ if let Some(Some(template)) = builder.snapshot[templates].get_mut(template_index) {template.inline_executable = inline_executable;}}while index < builder.entries.len() {let entry = builder.entries[index];- executables.push(builder.executable_snapshot(&entry));+ let row = builder.executable_snapshot(&entry);+ builder.snapshot.add_executable(row);index += 1;}samples = core::mem::take(&mut builder.closure_samples);@@ -1610,10 +1660,17 @@ pub fn capture_snapshot<'d>(runtime.array_iterator_method_watchpoint_set_address =realm_watchpoints::array_iterator_method_watchpoint_set_address(realm);let options = &vm.jit.options;- let snapshot = Snapshot {- executables,- runtime,- options: CompileOptions {+ let SnapshotBuilder {+ snapshot,+ cells,+ entries,+ ..+ } = builder;+ let (mut snapshot, open_lists) = snapshot.finish();+ super::compile_queue::give_back_open_lists(open_lists);+ snapshot.runtime = runtime;+ snapshot.options = {+ CompileOptions {dump_ir: options.dump_ir,dump_passes: options.dump_passes,dump_asm: options.dump_asm,@@ -1633,14 +1690,13 @@ pub fn capture_snapshot<'d>(osr_at_every_loop: options.stress_osr,few_registers: options.stress_registers,},- },+ }};CapturedSnapshot {- snapshot: Box::new(snapshot),- cells: defer_gc.cover(builder.cells),+ snapshot,+ cells: defer_gc.cover(cells),snapshot_executables: defer_gc.cover(- builder- .entries+ entries.iter().map(|entry| SnapshotExecutable {executable: entry.executable,diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex 60038315f13..a24fd0d622b 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -476,6 +476,7 @@ fn compile(if sync {// NB: Nothing collects garbage while compiling on this thread, so the snapshot's cells stay alive.let result = super::compile_queue::compile(&snapshot);+ super::compile_queue::give_back_snapshot(snapshot);let memory = should_install(vm, &result).then(|| {let code = &result.as_ref().expect("the compile succeeded").code;let name = super::describe_executable(&executable);