Skip to main content

BytecodeArray

Struct BytecodeArray 

Source
pub struct BytecodeArray { /* private fields */ }
Expand description

An immutable, compact representation of the bytecode for a single JavaScript function.

Wraps a shared [SharedBytecodeTemplate] behind a single Rc so that clone_for_closure only bumps one reference count instead of ~34. Only the per-instance closure_context and has_fn_props fields live directly on this struct.

Implementations§

Source§

impl BytecodeArray

Source

pub fn new( bytecodes: Vec<u8>, constant_pool: Vec<ConstantPoolEntry>, frame_size: u32, parameter_count: u32, source_positions: Vec<SourcePosition>, feedback_metadata: FeedbackMetadata, handler_table: Vec<HandlerTableEntry>, ) -> Self

Construct a new BytecodeArray.

  • bytecodes — the raw encoded bytecode produced by bytecodes::encode.
  • constant_pool — all literals referenced from the bytecode.
  • frame_size — number of virtual registers needed at runtime.
  • parameter_count — number of formal parameters.
  • source_positions — optional source-position table (may be empty).
  • feedback_metadata — inline-cache slot descriptor produced by the compiler (use FeedbackMetadata::empty when there are no IC slots).
  • handler_table — exception handler entries for try/catch/finally (use an empty Vec when there are no try blocks).
Source

pub fn cached_template_object(&self, bytecode_offset: u32) -> Option<JsValue>

Return a cached template object for the given bytecode offset, if any.

Source

pub fn cache_template_object(&self, bytecode_offset: u32, value: JsValue)

Cache a template object for the given bytecode offset.

Source

pub fn with_generator_flag(self, flag: bool) -> Self

Mark this BytecodeArray as belonging to a generator function.

Returns self so this can be chained onto BytecodeArray::new:

let ba = BytecodeArray::new(vec![], vec![], 0, 0, vec![], FeedbackMetadata::empty(), vec![])
    .with_generator_flag(true);
assert!(ba.is_generator());
Source

pub fn is_generator(&self) -> bool

Returns true if this bytecode belongs to a function* generator.

Source

pub fn with_async_flag(self, flag: bool) -> Self

Mark this BytecodeArray as belonging to an async function.

When combined with BytecodeArray::with_generator_flag this marks the function as an async generator (async function*).

Source

pub fn is_async(&self) -> bool

Returns true if this bytecode belongs to an async function or async function*.

Source

pub fn with_module_flag(self, flag: bool) -> Self

Mark this BytecodeArray as belonging to an ES module.

Source

pub fn is_module(&self) -> bool

Returns true if this bytecode belongs to an ES module.

Source

pub fn with_strict_flag(self, flag: bool) -> Self

Mark this BytecodeArray as compiled in strict mode.

Source

pub fn is_strict(&self) -> bool

Returns true if this bytecode was compiled in strict mode.

Source

pub fn with_arrow_flag(self, flag: bool) -> Self

Mark this BytecodeArray as belonging to an arrow function.

Arrow functions are not constructable — invoking them with new must throw a TypeError per ES §15.3.4.

Source

pub fn is_arrow(&self) -> bool

Returns true if this bytecode belongs to an arrow function (=>).

Source

pub fn has_trivial_body(&self) -> bool

Returns true when the function body is trivial — it only sets up the arguments binding and immediately returns undefined.

Empty constructors like function Base() {} match this pattern. The construct fast-path uses this to skip interpreter re-entry.

Source

pub fn set_top_level(&mut self, flag: bool)

Mark this bytecode as a top-level script.

Source

pub fn is_top_level(&self) -> bool

Returns true if this bytecode belongs to a top-level script.

Source

pub fn with_top_level_flag(self, flag: bool) -> Self

Builder-style: mark this bytecode as a top-level script.

Source

pub fn closure_context(&self) -> Option<&Rc<RefCell<JsContext>>>

Returns the captured closure context, if any.

Source

pub fn fusion_pattern_cache(&self) -> &OnceCell<Option<(usize, i64)>>

Returns the lazily-populated fusion-pattern analysis cache.

The [SpeculativeCallFusion] runtime stub calls OnceCell::get_or_init on the returned cell so that the expensive bytecode decode + pattern match runs at most once per template.

Source

pub fn set_closure_context(&mut self, ctx: Rc<RefCell<JsContext>>)

Attach a captured closure context to this BytecodeArray.

Source

pub fn writes_closure_vars(&self) -> bool

Returns true if this function’s bytecode writes to any captured closure variable.

Source

pub fn has_fn_props(&self) -> bool

Returns true if fn_props_set has been called on this bytecode array (or any clone sharing the same has_fn_props flag).

Source

pub fn mark_has_fn_props(&self)

Mark that function-properties side-table entries exist for this bytecode array.

Source

pub fn with_writes_closure_vars(self, flag: bool) -> Self

Mark whether this function writes to captured closure variables.

Source

pub fn clone_for_closure(&self, ctx: Option<Rc<RefCell<JsContext>>>) -> Self

Create a lightweight clone for use as a closure, attaching the given closure context.

All immutable bytecode data (bytecodes, constant pool, source positions, etc.) is shared with the original via Rc, making this operation O(1) regardless of function size.

Source

pub fn self_name_register(&self) -> Option<i32>

Register index for a named function expression’s self-reference.

Source

pub fn with_self_name_register(self, reg: i32) -> Self

Set the self-name register for named function expressions.

Source

pub fn cached_construct_proto(&self) -> Option<JsValue>

Returns the cached constructor .prototype value, if populated.

Source

pub fn set_construct_proto_cache(&self, proto: JsValue)

Stores a constructor .prototype value for reuse on subsequent [[Construct]] calls.

Source

pub fn cached_construct_boilerplate(&self) -> Option<ConstructBoilerplate>

Returns a clone of the cached construct boilerplate, if populated.

Source

pub fn set_construct_boilerplate(&self, bp: ConstructBoilerplate)

Stores a construct boilerplate captured from the first successful [[Construct]] execution.

Source

pub fn clone_object_literal_template(&self, slot: u32) -> Option<PropertyMap>

If a cached object-literal template exists for slot, returns a fresh PropertyMap instantiated from it.

Source

pub fn promote_object_literal_template(&self, slot: u32) -> Option<PropertyMap>

If a Pending first-instance exists for slot, promotes it to Cached by capturing its finalised key layout and returns a template clone.

Returns None if no pending entry exists or the first instance has no properties (nothing worth caching).

Source

pub fn clone_object_literal_template_with_values( &self, slot: u32, values: Vec<JsValue>, ) -> Option<PropertyMap>

Like clone_object_literal_template but fills the new map with values directly instead of JsValue::Undefined.

This is the hot path for the fused CreateObjectLiteralWithProperties stub: because the caller already has all property values in template order, it skips the values-vec pool probe, the Undefined initialisation, and the per-property key comparison in try_template_fill.

Source

pub fn promote_object_literal_template_with_values( &self, slot: u32, values: Vec<JsValue>, ) -> Option<PropertyMap>

Like promote_object_literal_template but fills the promoted map with values directly.

Source

pub fn set_object_literal_pending( &self, slot: u32, map: Rc<RefCell<PropertyMap>>, )

Records a Pending first-instance for slot.

Source

pub fn clone_object_literal_template_pooled( &self, slot: u32, ) -> Option<Rc<RefCell<PropertyMap>>>

Like clone_object_literal_template but returns a pooled Rc<RefCell<PropertyMap>>, reusing the control-block and values Vec allocations when possible.

Source

pub unsafe fn clone_object_literal_template_pooled_unchecked( &self, slot: u32, ) -> Option<Rc<RefCell<PropertyMap>>>

Like [clone_object_literal_template_pooled] but bypasses the RefCell runtime borrow check on the template cache.

§Safety

Caller must ensure no mutable borrow of the object_literal_templates RefCell is active.

Source

pub unsafe fn clone_object_literal_template_with_values_pooled_unchecked( &self, slot: u32, values: &[JsValue], ) -> Option<Rc<RefCell<PropertyMap>>>

Like [clone_object_literal_template_with_values_pooled] but bypasses the RefCell runtime borrow check on the template cache.

§Safety

Caller must ensure no mutable borrow of the object_literal_templates RefCell is active.

Source

pub unsafe fn set_object_literal_pending_unchecked( &self, slot: u32, map_rc: Rc<RefCell<PropertyMap>>, )

Like [set_object_literal_pending] but bypasses the RefCell runtime borrow check.

§Safety

Caller must ensure no outstanding borrow of the object_literal_templates RefCell exists.

Source

pub fn promote_object_literal_template_pooled( &self, slot: u32, ) -> Option<Rc<RefCell<PropertyMap>>>

Like promote_object_literal_template but returns a pooled Rc<RefCell<PropertyMap>>.

Pre-warms the pool after promotion for the same reason as [promote_object_literal_template_with_values_pooled].

Source

pub fn clone_object_literal_template_with_values_pooled( &self, slot: u32, values: &[JsValue], ) -> Option<Rc<RefCell<PropertyMap>>>

Like clone_object_literal_template_with_values but returns a pooled Rc<RefCell<PropertyMap>>.

Source

pub fn promote_object_literal_template_with_values_pooled( &self, slot: u32, values: &[JsValue], ) -> Option<Rc<RefCell<PropertyMap>>>

Like promote_object_literal_template_with_values but returns a pooled Rc<RefCell<PropertyMap>>.

After promoting the template, pre-warms the object pool so that subsequent IC-hit iterations in the same invocation can skip per-object allocation entirely.

Source

pub fn shared_mega_load_ic(&self) -> Option<Box<MegamorphicIc>>

Returns a clone of the shared megamorphic load IC, if one has been populated by a previous invocation.

Source

pub fn set_shared_mega_load_ic(&self, ic: Box<MegamorphicIc>)

Writes back a megamorphic load IC to the shared cache so that subsequent invocations start warm.

Source

pub fn shared_mega_store_ic(&self) -> Option<Box<MegamorphicIc>>

Returns a clone of the shared megamorphic store IC, if one has been populated by a previous invocation.

Source

pub fn set_shared_mega_store_ic(&self, ic: Box<MegamorphicIc>)

Writes back a megamorphic store IC to the shared cache so that subsequent invocations start warm.

Source

pub fn shared_proto_load_ic(&self) -> Option<Box<ProtoIcCache>>

Returns a clone of the shared prototype-chain load IC, if populated.

Source

pub fn set_shared_proto_load_ic(&self, ic: Box<ProtoIcCache>)

Writes back a prototype-chain load IC to the shared cache.

Source

pub fn shared_global_ic(&self) -> Option<Box<Vec<Option<(usize, u64)>>>>

Returns a clone of the shared global variable IC, if populated.

Source

pub fn set_shared_global_ic(&self, ic: Box<Vec<Option<(usize, u64)>>>)

Writes back a global variable IC to the shared cache.

Source

pub fn bytecodes(&self) -> &[u8]

The raw encoded bytecode bytes.

Source

pub fn constant_pool(&self) -> &[ConstantPoolEntry]

The constant pool for this function.

Source

pub fn frame_size(&self) -> u32

Number of virtual registers required by this function’s frame.

Source

pub fn parameter_count(&self) -> u32

Number of formal parameters declared by this function.

Source

pub fn bytecode_count(&self) -> usize

Number of decoded bytecode instructions after peephole fusion.

Returns usize::MAX for malformed bytecode so hot-path callers can conservatively skip optimizations that depend on a valid instruction count.

Source

pub fn has_exception_handler(&self) -> bool

Returns true when this function has at least one exception handler.

Source

pub fn function_length(&self) -> u32

Function.prototype.length for this function.

Source

pub fn with_function_length(self, length: u32) -> Self

Set Function.prototype.length metadata.

Source

pub fn function_name(&self) -> &str

Declared or inferred function name.

Source

pub fn with_function_name(self, name: impl Into<String>) -> Self

Set the declared or inferred function name.

Source

pub fn source_text(&self) -> Option<&str>

Source text used by Function.prototype.toString(), if any.

Source

pub fn with_source_text(self, source_text: impl Into<String>) -> Self

Set the source text used by Function.prototype.toString().

Source

pub fn binding_registers(&self) -> &HashMap<String, i32>

Visible binding-to-register mapping for direct eval().

Source

pub fn with_binding_registers( self, binding_registers: HashMap<String, i32>, ) -> Self

Set the binding-to-register mapping used by direct eval().

Source

pub fn source_positions(&self) -> &[SourcePosition]

The source-position table (may be empty if debug info was stripped).

Source

pub fn feedback_metadata(&self) -> &FeedbackMetadata

The compile-time feedback metadata for all inline-cache slots.

Source

pub fn feedback_vector_snapshot(&self) -> FeedbackVector

Return a snapshot of the current runtime feedback vector.

Source

pub fn feedback_state(&self, slot: u32) -> Option<InlineCacheState>

Return the current inline-cache state for slot.

Source

pub fn feedback_transition( &self, slot: u32, new_state: InlineCacheState, ) -> bool

Advance the feedback state for slot if new_state is hotter.

Source

pub fn set_feedback_state(&self, slot: u32, state: InlineCacheState) -> bool

Overwrite the feedback state for slot.

Source

pub fn handler_table(&self) -> &[HandlerTableEntry]

The per-function exception handler table.

Each entry maps a [try_start, try_end) instruction-index range to a handler entry point. Entries are ordered so that the innermost handler for any given instruction always appears before outer handlers.

After the peephole pass compacts instructions, this returns the remapped table with post-compaction indices.

Source

pub fn instructions(&self) -> StatorResult<Vec<Instruction>>

Decode the bytecode stream and return the list of Instructions.

Returns an error if the byte stream is malformed.

Source

pub fn decoded_instructions( &self, ) -> StatorResult<(&'_ [Instruction], &'_ [usize], &'_ [Option<usize>])>

Decode the bytecode stream once and return cached instructions, byte offsets, and pre-computed jump targets on subsequent calls.

Source

pub fn get_constant(&self, index: u32) -> Option<&ConstantPoolEntry>

Look up a constant-pool entry by zero-based index.

Returns None if index is out of range.

Source

pub fn source_position_for( &self, bytecode_offset: u32, ) -> Option<&SourcePosition>

Return the SourcePosition that covers bytecode_offset, or None if the source-position table is empty or no entry precedes the offset.

The table must be sorted by bytecode_offset (ascending). The lookup uses binary search and returns the last entry whose bytecode_offset is ≤ the given offset.

Source

pub fn increment_invocation_count(&self) -> u32

Atomically increment the invocation counter and return the new value.

All clones of this BytecodeArray share the same counter via the inner Rc, so every copy — whether still held in a JsValue::Function or already moved into an crate::interpreter::InterpreterFrame — increments the same counter.

Source

pub fn invocation_count(&self) -> u32

Returns the current invocation count without modifying it.

Source

pub fn store_jit_code(&self, cached: CachedExecutableCode)

Store baseline-JIT cached executable code produced by the compiler.

cached is a [CachedExecutableCode] that owns a persistent mmap’d page of executable memory.

All clones of this BytecodeArray share the same JIT cache.

Source

pub fn has_any_jit_code(&self) -> bool

Fast check for whether any JIT tier has compiled code for this function.

Checks the fast boolean flags for baseline, Maglev, and Turbofan tiers using short-circuit evaluation to avoid unnecessary atomic loads when an earlier tier is already compiled.

Source

pub fn has_baseline_jit_code(&self) -> bool

Returns true when baseline JIT code has been cached for this function.

Source

pub fn try_get_jit_code(&self) -> Ref<'_, Option<CachedExecutableCode>>

Borrows the cached JIT executable code, or returns None if baseline compilation has not been triggered yet.

The caller can call [CachedExecutableCode::execute] on the borrowed reference without cloning or allocating executable memory.

Source

pub fn has_maglev_jit_code(&self) -> bool

Returns true when Maglev JIT code has been cached for this function.

Source

pub fn has_all_maglev_jit_code(&self) -> bool

Returns true when this function and all nested functions in its constant pool have Maglev JIT code compiled or have had compilation attempted (including degenerate/failed compilations).

This is useful for benchmark warmup: an outer script may have Maglev code while a closure it defines does not yet, so checking only the outer BytecodeArray gives a false positive.

Inner functions whose compilation was attempted but failed (degenerate graphs) are treated as “done” — the warmup should not block forever waiting for code that will never be produced.

Source

pub fn maglev_jit_cache_arc(&self) -> MaglevJitCodeCache

Returns an Arc clone of the Maglev JIT code cache.

The background compilation thread receives this Arc and writes the compiled code into it when compilation succeeds.

Source

pub fn maglev_jit_code_flag(&self) -> Arc<AtomicBool>

Returns an Arc clone of the Maglev JIT-code-ready flag.

The background compilation thread sets this to true after storing compiled code, so the hot dispatch path can skip the mutex lock.

Source

pub fn try_start_maglev_compile(&self) -> bool

Attempt to atomically mark this function as having a Maglev compilation in flight.

Returns true if the caller successfully claimed the compilation slot (the previous state was false); returns false if a compilation was already started or has been scheduled by another caller.

Source

pub fn maglev_compile_attempted(&self) -> bool

Returns true if a Maglev compilation has been attempted for this function (regardless of whether it succeeded or failed).

Source

pub fn has_turbofan_jit_code(&self) -> bool

Returns true if Turbofan compilation has finished and compiled code is available.

Source

pub fn turbofan_jit_cache_arc(&self) -> TurbofanJitCodeCache

Returns an Arc clone of the Turbofan JIT code cache.

The background compilation thread receives this Arc and writes the compiled TurbofanCompiledCode into it when compilation succeeds.

Source

pub fn turbofan_jit_code_flag(&self) -> Arc<AtomicBool>

Returns an Arc clone of the Turbofan JIT-code-ready flag.

The background compilation thread sets this to true after storing compiled code, so the hot dispatch path can skip the mutex lock.

Source

pub fn try_start_turbofan_compile(&self) -> bool

Attempt to atomically mark this function as having a Turbofan compilation in flight.

Returns true if the caller successfully claimed the compilation slot (the previous state was false); returns false if a compilation was already started or has been scheduled by another caller.

Source

pub fn jit_executable_cache(&self) -> &JitExecutableCache

Returns a shared reference to the persistent executable JIT code cache.

On the first call after baseline JIT compilation, the cache is empty and the caller should populate it via JitExecutableCode::new. Subsequent calls return the cached executable code directly.

Source

pub fn maglev_executable_cache(&self) -> &MaglevExecutableCache

Returns a reference to the cached Maglev executable code.

The cache is lazily initialised on first Maglev execution from the raw compiled code bytes.

Source

pub fn jit_baseline_has_deopted(&self) -> bool

Returns true if baseline JIT code has deopted at least once, indicating the generated code contains unsupported opcodes and should not be re-attempted.

Source

pub fn mark_jit_baseline_deopted(&self)

Mark this function’s baseline JIT code as having deopted.

Once set, the interpreter will skip all baseline JIT execution attempts for this function to avoid the overhead of repeatedly entering and immediately exiting always-deopting code.

Source

pub fn jit_maglev_has_deopted(&self) -> bool

Returns true if Maglev JIT code should NOT be attempted right now.

This is true in two cases:

  1. The total deopt count exceeds [MAX_MAGLEV_DEOPT_RETRIES].
  2. The function is in an exponential cooldown period after a recent deopt (invocation_count < next_try_at).
Source

pub fn maglev_deopt_count(&self) -> u32

Returns the current Maglev deopt count for diagnostics.

Source

pub fn mark_jit_maglev_deopted(&self)

Increment the Maglev deopt counter and set a minimal cooldown (1 interpreter invocation) before retrying JIT. This gives the interpreter exactly one iteration to warm ICs while retrying aggressively. After [MAX_MAGLEV_DEOPT_RETRIES] the interpreter will permanently skip Maglev for this function.

Source

pub fn reset_maglev_deopt_count(&self)

Reset the Maglev deopt counter, allowing re-optimization.

Called when the Maglev executable cache is re-initialised (e.g., after recompilation with better type feedback).

Source

pub fn maglev_next_try_at(&self) -> u32

Returns the current next_try_at value for diagnostics.

Source

pub fn set_maglev_next_try_at(&self, val: u32)

Sets the next_try_at threshold. Setting this to u32::MAX effectively blocks Maglev for this function until the counter is reset.

Source

pub fn set_jit_disabled(&self, disabled: bool)

Enable or disable JIT tier execution for this function and nested functions.

Source

pub fn jit_disabled(&self) -> bool

Returns true if this function is currently blocked from Maglev execution.

Source

pub fn has_maglev_executable_cached(&self) -> bool

Returns true if the Maglev executable cache has been populated.

Trait Implementations§

Source§

impl Clone for BytecodeArray

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BytecodeArray

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for BytecodeArray

Source§

fn eq(&self, other: &Self) -> bool

Two BytecodeArrays are equal when their static bytecode and metadata are identical. The tiering state (invocation_count, jit_code, has_jit_code, maglev_jit_code, has_maglev_jit_code_flag, turbofan_jit_code, has_turbofan_jit_code_flag) and runtime caches (template_cache) are intentionally excluded from the comparison.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V