Commit graph

281 commits

Author SHA1 Message Date
pwespi
6c471c5ef7 LibJS: Do not allow reassignment to local const variable 2026-02-09 21:06:46 +01:00
Andreas Kling
0aec6a12b4 LibJS: Use binary search for exception handler lookup
The exception handler table is sorted by start_offset, so use
binary_search instead of a linear scan. This matches the pattern
already used by source_range_at() in the same file.
2026-02-09 16:35:39 +01:00
Andreas Kling
51f67febe8 LibJS: Remove stale comment on Yield handler
This comment referenced the old runtime unwind context stack behavior
where a flag had to be set to prevent yield from going through a
finally statement. That mechanism was removed and finally is now
handled purely through explicit completion records in bytecode.
2026-02-09 16:35:39 +01:00
Andreas Kling
720fd567b1 LibJS: Collapse handler/finalizer into single exception handler target
After replacing the runtime unwind context stack with explicit
completion records for try/finally dispatch, the distinction between
"handler" (catch) and "finalizer" (finally) in the exception handler
table is no longer meaningful at runtime.

handle_exception() checked handler first, then finalizer, but they
did the exact same thing (set the PC). When both were present, the
finalizer was dead code.

Collapse both fields into a single handler_offset (now non-optional,
since an entry always has a target), remove the finalizer concept
from BasicBlock, UnwindContext, and ExceptionHandlers, and simplify
handle_exception() to a direct assignment.
2026-02-09 16:35:39 +01:00
Andreas Kling
6a3b71397b LibJS: Remove runtime unwind context stack and UnwindInfo struct
The runtime unwind context stack was pushed by EnterUnwindContext
and popped by LeaveUnwindContext. With both opcodes removed, it is
no longer read or written by anything.

Remove UnwindInfo, the unwind_contexts vector, its GC visit loop,
its copy in ExecutionContext::copy(), and the VERIFY assertions that
referenced it in handle_exception() and catch_exception().
2026-02-09 16:35:39 +01:00
Andreas Kling
cbca493b28 LibJS: Remove BlockBoundaryType::Unwind
With LeaveUnwindContext gone, the Unwind boundary type has no purpose.
Remove it from the enum and all start/end boundary calls.
2026-02-09 16:35:39 +01:00
Andreas Kling
5abe40874a LibJS: Remove LeaveUnwindContext opcode
LeaveUnwindContext popped the runtime unwind context stack. With the
stack being removed, all emission sites become dead code. Remove the
opcode and all its emissions.
2026-02-09 16:35:39 +01:00
Andreas Kling
e84a1fd6ad LibJS: Remove EnterUnwindContext opcode
EnterUnwindContext pushed an UnwindInfo and jumped to entry_point.
Without the stack push, it's just a Jump. Replace the single emission
site with a Jump and remove the opcode entirely.
2026-02-09 16:35:39 +01:00
Andreas Kling
c5956c78ce LibJS: Remove handler_called from UnwindInfo
This field was set but never read, making it dead code.
2026-02-09 16:35:39 +01:00
Andreas Kling
7f89158d20 LibJS: Replace implicit environment stack with explicit registers
Replace the saved_lexical_environments stack in ExecutionContextRareData
with explicit register-based environment tracking. Environments are now
stored in registers and restored via SetLexicalEnvironment, making the
environment flow visible in bytecode.

Key changes:
- Add GetLexicalEnvironment and SetLexicalEnvironment opcodes
- CreateLexicalEnvironment takes explicit parent and dst operands
- EnterObjectEnvironment stores new environment in a dst register
- NewClass takes an explicit class_environment operand
- Remove LeaveLexicalEnvironment opcode (instead: SetLexicalEnvironment)
- Remove saved_lexical_environments from ExecutionContextRareData
- Use a reserved register for the saved lexical environment to avoid
  dominance issues with lazily-emitted GetLexicalEnvironment
2026-02-09 16:35:39 +01:00
Andreas Kling
a439dc8490 LibJS: Use explicit completion records for try/finally dispatch
Each finally scope gets two registers (completion_type and
completion_value) that form an explicit completion record. Every path
into the finally body sets these before jumping, and a dispatch chain
after the finally body routes to the correct continuation.

This replaces the old implicit protocol that relied on the exception
register, a saved_return_value register, and a scheduled_jump field
on ExecutionContext, allowing us to remove:

- 5 opcodes (ContinuePendingUnwind, ScheduleJump, LeaveFinally,
  RestoreScheduledJump, PrepareYield)
- 1 reserved register (saved_return_value)
- 2 ExecutionContext fields (scheduled_jump, previously_scheduled_jumps)
2026-02-09 08:51:12 +01:00
Andreas Kling
5cefa59116 LibJS: Fix evaluation order of computed property keys in object literals
The spec for PropertyDefinitionEvaluation requires that when evaluating
a property definition with a computed key (PropertyDefinition :
PropertyName : AssignmentExpression), the PropertyName is fully
evaluated (including ToPropertyKey, which calls ToPrimitive) before the
value's AssignmentExpression is evaluated.

Our bytecode compiler was evaluating the key expression first, then
the value expression, and only performing ToPropertyKey later inside
PutByValue at runtime. This meant user-observable side effects from
ToPrimitive (such as calling Symbol.toPrimitive or toString on the key
object) would fire after the value expression had already been
evaluated.

Fix this by using a new ToPrimitiveWithStringHint instruction that
performs ToPrimitive with string hint(!), and emitting it between the
key and value evaluations in ObjectExpression codegen.
After ToPrimitive, the key is already a primitive, so the subsequent
ToPropertyKey inside PutByValue becomes a no-op from the perspective
of user-observable side
effects.

Also update an existing test that was asserting the old (incorrect)
evaluation order, and add comprehensive new tests for computed property
key evaluation order.
2026-02-09 01:23:48 +01:00
Andreas Kling
bef09b899c LibJS: Fix object rest destructuring with MemberExpression target
When the rest element in an object destructuring assignment targets a
MemberExpression (e.g. `({a, ...t.rest} = obj)`), we were incorrectly
storing the original source object to the reference instead of the
rest object produced by CopyObjectExcludingProperties.

For example, `({a, ...t.rest} = {a:1, b:2, c:3})` would set t.rest
to `{a:1, b:2, c:3}` instead of the correct `{b:2, c:3}`.

The fix is to pass the result of CopyObjectExcludingProperties
to emit_store_to_reference instead of the original RHS.
2026-02-09 01:23:48 +01:00
Andreas Kling
7997267942 LibJS: Remove outdated FIXME comments about ToPropertyKey ordering
The FIXME comments suggested that ToPropertyKey was called at the wrong
time for computed super property access. However, extensive testing
shows that both Ladybird and V8 implement the correct ordering according
to the ECMA262 specification.

Remove the outdated FIXME comments and add comprehensive test coverage
for super property computed keys with Symbol.toPrimitive to prevent
regressions.
2026-02-09 01:23:48 +01:00
Andreas Kling
3eb03b4817 LibJS: Preserve this binding for tagged with identifiers
Route tagged template identifier lookup through
GetCalleeAndThisFromEnvironment only when the identifier is non-local.
Keep local and global identifiers on Identifier::generate_bytecode so
TDZ checks and ordinary undefined-this behavior stay intact.

Expand runtime coverage with a tagged-template TDZ regression case,
sequential with-binding calls, and getter-returned tag functions.
2026-02-09 01:23:48 +01:00
Andreas Kling
0c843b04e3 LibJS: Remove stale FIXME about sloppy-mode this in CallExpression
For non-Reference calls (e.g. (0, fn)(), (cond ? fn : x)()), the
codegen correctly passes undefined as the thisValue, matching step 2b
of EvaluateCall in the spec. OrdinaryCallBindThis then coerces
undefined to the global object in sloppy mode at runtime. Replace the
stale FIXME with a clarifying comment.

Also add comprehensive tests for this-value behavior in non-Reference
call patterns (comma, ternary, logical, assignment, nullish coalescing)
in both sloppy and strict mode.
2026-02-08 20:59:20 +01:00
Andreas Kling
8c541380dd LibJS: Remove stale FIXMEs about SetFunctionName and MakeConstructor
Both SetFunctionName and MakeConstructor are already performed by
ECMAScriptFunctionObject::initialize() when the object is created
via create_from_function_node:

- SetFunctionName: The name is passed to SharedFunctionInstanceData,
  and initialize() creates the "name" property from it.
- MakeConstructor: has_constructor() returns true for all normal
  non-arrow functions, m_constructor_kind defaults to Base, and
  m_may_need_lazy_prototype_instantiation handles the prototype
  property creation lazily.
2026-02-08 20:59:20 +01:00
Andreas Kling
b7091ba35a LibJS: Remove stale FIXME about NamedEvaluation in assignment
The FIXME claimed that IsAnonymousFunctionDefinition + NamedEvaluation
was missing for simple assignment expressions like `x = function() {}`.
However, the code directly below the FIXME already implements this
correctly via emit_named_evaluation_if_anonymous_function.
2026-02-08 20:59:20 +01:00
Andreas Kling
690ba5299b LibJS: Pass the global object as receiver in GetGlobal
The GetGlobal bytecode optimization bypasses the normal environment
record lookup for global variable access. When a global property is
an accessor (getter), the receiver passed to the getter must be the
global object, not undefined.

The spec's Get(O, P) abstract operation is defined as O.[[Get]](P, O),
meaning the object itself is always the receiver. The global
environment's GetBindingValue delegates to its object record's
GetBindingValue, which calls Get(bindingObject, N), so the receiver
should be the binding object (the global object).

Both the cached path (calling the getter directly from get_direct)
and the non-cached path (calling internal_get) were passing
js_undefined() as the receiver. This caused strict-mode getters on
global properties to receive undefined as their this-value instead
of globalThis.

Notably, the corresponding SetGlobal paths already correctly passed
&binding_object for setter calls.
2026-02-08 20:59:20 +01:00
Andreas Kling
710f1bdb74 LibJS: Produce negative zero from i32 multiplication fast path
The i32 multiplication fast path in Mul::execute_impl was producing
+0 instead of -0 when one operand was negative and the other was
zero (e.g. `var a = -1, b = 0; a * b`).

This happened because i32 can't represent -0, so `Value(0)` was
always positive zero. We now fall through to the double path when
the i32 result is zero, which correctly handles the sign.

Also add comprehensive multiplication tests covering negative zero,
basic arithmetic, large integers, type coercion, NaN, and Infinity.
2026-02-08 20:59:20 +01:00
dosisod
dab739771f LibJS: Reduce number of template literal op codes
There is no need to concat empty string literals when building template
literals. Now strings will only be concatenated if they need to be.

To handle the edge case where the first segment is not a string
literal, a new `ToString` op code has been added to ensure the value is
a string concatenating more strings.

In addition, basic const folding is now supported for template literal
constants (templates with no interpolated values), which is commonly
used for multi-line string constants.
2026-01-31 18:24:02 +01:00
dosisod
2c3077b878 LibJS: Dead code elimination for always truthy/falsey conditions
This improves and expands the ability to do dead code elimination on
conditions which are always truthy or falsey.

The following cases are now optimized:
* `if (true){}` -> Only emit `if` block, ignore `else`
* `if (false){}` -> Only emit `else if`/`else` block
* `while (false){}` -> Ignore `while` loop entirely
* `for (x;false;){}` -> Only emit `x` (if it exists), skip `for` block
* Ternary -> Directly return left/right hand side if condition is const
2026-01-31 18:22:40 +01:00
Andreas Kling
5674f8bbe0 LibJS: Limit eval() deoptimization to the containing function scope
Previously, when direct eval() was called, we would mark the entire
environment chain as "permanently screwed by eval", disabling variable
access caching all the way up to the global scope.

This was overly conservative. According to the ECMAScript specification,
a sloppy direct eval() can only inject var declarations into its
containing function's variable environment - it cannot inject variables
into parent function scopes.

This patch makes two changes:

1. Stop propagating the "screwed by eval" flag at function boundaries.
   When set_permanently_screwed_by_eval() hits a FunctionEnvironment or
   GlobalEnvironment, it no longer continues to outer environments.

2. Check each environment during cache lookup traversal. If any
   environment in the path is marked as screwed, we bail to the slow
   path. This catches the case where we're inside a function with eval
   and have a cached coordinate pointing to an outer scope.

The second change is necessary because eval can create local variables
that shadow outer bindings. When looking up a variable from inside a
function that called eval, we can't trust cached coordinates that point
to outer scopes, since eval may have created a closer binding.

This improves performance for code with nested functions where an inner
function uses eval but parent functions perform many variable accesses.
The parent functions can now use cached environment coordinates.

All 29 new tests verify behavior matches V8.
2026-01-27 10:58:39 +01:00
Andreas Kling
81bee185e6 LibJS: Replace source map HashMap with sorted Vector
Bytecode source map entries are always added in order of increasing
bytecode offset, and lookups only happen during error handling (a cold
path). This makes a sorted vector with binary search a better fit than
a hash map.

This change reduces memory overhead and speeds up bytecode generation
by avoiding hash table operations during compilation. Lookups remain
fast via binary search, and since source_range_at() is only called
when generating stack traces, the O(log n) lookup is acceptable.
2026-01-26 19:37:42 +01:00
Andreas Kling
d488f9f12f LibJS: Narrow bytecode source map offsets from size_t to u32
Add VERIFY guards to catch bytecode programs that exceed u32::max bytes
and narrow the bytecode_offset parameter in add_source_map_entry() to
u32. This is a preparatory change for optimizing source map storage.
2026-01-26 19:37:42 +01:00
Jelle Raaijmakers
e3faa9b5ad LibJS: Move tests to /Tests/LibJS 2026-01-22 07:46:48 -05:00
dosisod
ac8cc6d24b LibJS: Constant fold LogicalExpression
Logical expressions like `true || false` are now constant folded. This
also allows for dead code elimination if we know the right-hand side of
the expression will never be evaluated (such as `false && f()` or
`true || f()`).

In the test suites, the values are now being constant folded at compile
time. To ensure that the actual evaluation logic is being called
properly, I had to duplicate the tests and call them via a function so
the compiler would not optimize the evaluation logic away.

This also demotes `NaN` and `Infinity` identifiers to `nan` and
`inf` double literals, which will further help with const folding.
2026-01-22 08:47:18 +01:00
dosisod
5a8d71fb02 LibJS: Optimize double boolean not (!!) operation
This is a common way to convert a value to a boolean. Instead of doing
a boolean conversion and 2 negate operations, we replace this with a
single `ToBoolean` op code.
2026-01-22 08:45:42 +01:00
dosisod
bc823878c7 LibJS: Add bytecode IR regression tests
This adds a new `test-js-bytecode` target which ensures that codegen
changes do not impact emitted bytecode IR, or if it does, it is known
and the tests are updated accordingly.

Similar to the LibWeb tests, the tests are stored in the following
format:

* `Libraries/LibJS/Bytecode/Tests/input`: Input `.js` files
* `Libraries/LibJS/Bytecode/Tests/expected`: Expected `.txt` bytecode
* `Libraries/LibJS/Bytecode/Tests/output`: Emitted `.txt` bytecode

The `output` dir is git-ignored, but stores the output so you can diff
and inspect failed tests more easily.

There is only one test so far, which is a baseline test that should not
change dramatically unless we change the bytecode output format.
2026-01-22 08:44:24 +01:00
Andreas Kling
986e30a140 LibJS: Fix object literal shape caching for numeric string keys
Numeric string keys like "0" are converted to numeric property keys and
stored in indexed storage rather than shape-based storage. The shape
caching optimization introduced in 505fe0a977 didn't account for this,
causing properties with numeric keys to be lost on subsequent calls.

The fix excludes object literals with numeric string keys from the
shape caching fast path by checking if any key would become a numeric
property index.
2026-01-21 10:49:34 +01:00
Andreas Kling
4d92c4d71a LibJS: Skip initializing constant slots in ExecutionContext
Every function call allocates an ExecutionContext with a trailing array
of Values for registers, locals, constants, and arguments. Previously,
the constructor would initialize all slots to js_special_empty_value(),
but constant slots were then immediately overwritten by the interpreter
copying in values from the Executable before execution began.

To eliminate this redundant initialization, we rearrange the layout from
[registers | constants | locals] to [registers | locals | constants].
This groups registers and locals together at the front, allowing us to
initialize only those slots while leaving constant slots uninitialized
until they're populated with their actual values.

This reduces the per-call initialization cost from O(registers + locals
+ constants) to O(registers + locals).

Also tightens up the types involved (size_t -> u32) and adds VERIFYs to
guard against overflow when computing the combined slot counts, and to
ensure the total fits within the 29-bit operand index field.
2026-01-19 10:48:12 +01:00
Andreas Kling
505fe0a977 LibJS: Add shape caching for object literal instantiation
When a function creates object literals with simple property names,
we now cache the resulting shape after the first instantiation. On
subsequent calls, we create the object with the cached shape directly
and write property values at their known offsets.

This avoids repeated shape transitions and property offset lookups
for a common JavaScript pattern.

The optimization uses two new bytecode instructions:
- CacheObjectShape: Captures the final shape after object construction
- InitObjectLiteralProperty: Writes properties using cached offsets

Only "simple" object literals are optimized (string literal keys with
simple value expressions). Complex cases like computed properties,
getters/setters, and spread elements use the existing slow path.

3.4x speedup on a microbenchmark that repeatedly instantiates an object
literal with 26 properties. Small progressions on various benchmarks.
2026-01-10 00:56:51 +01:00
Andreas Kling
4b556feecf LibJS: Take snapshot of prototype chain validity later in GetById
We were snapshotting it a bit earlier than necessary, and if we ended up
hitting one of the inline caches, copying the validity was wasted work.
2026-01-09 09:16:50 +01:00
Andreas Kling
d66273b12a LibJS: Add % (modulo) fast path in bytecode interpreter
We can avoid the expensive call to fmod() in various cases when we have
Int32 values on both sides of the operator.
2026-01-09 09:16:50 +01:00
Andreas Kling
f558cd9f0d LibJS: Add inline caching for object literal instantiation
When instantiating an object literal, we go through the list of
properties and add them one by one to the new object. However, we were
totally neglecting to cache the shape transitions incurred by this
process, even though we had allocated a PropertyLookupCache for it.

1.25x speedup on Octane/splay.js and just generally very useful.
2026-01-08 00:26:57 +01:00
Andreas Kling
7dad7e10ee LibJS: Pre-size arrays created by NewArray and NewPrimitiveArray
We know the length they're gonna end up with up front since we're
instantiating array literals. Pre-sizing them allows us to skip
incremental resizing of the property storage.
2026-01-08 00:26:57 +01:00
Andreas Kling
a9cc425cde LibJS+LibWeb: Add missing GC marking visits
This adds visit_edges(Cell::Visitor&) methods to various helper structs
that contain GC pointers, and makes sure they are called from owning
GC-heap-allocated objects as needed.

These were found by our Clang plugin after expanding its capabilities.
The added rules will be enforced by CI going forward.
2026-01-07 12:48:58 +01:00
Luke Wilde
c4c9ac08ad LibJS: Follow the spec more closely for tagged template literals
This resolves a FIXME in its code generation, particularly for:
- Caching the template object
- Setting the correct property attributes
- Freezing the resulting objects

This allows archive.org to load, which uses the Lit library.

The Lit library caches these template objects to determine if a
template has changed, allowing it to determine to do a full template
rerender or only partially update the rendering. Before, we would
always cause a full rerender on update because we didn't return the
same template object.

This caused issues with archive.org's code, I believe particularly with
its router library, where we would constantly detach and reattach nodes
unexpectedly, ending up with the page content not being attached to the
router's custom element.
2026-01-06 23:25:36 +01:00
Andreas Kling
c516715e62 LibJS: Fix AddOwnProperty IC cache applying to non-extensible objects
The AddOwnProperty inline cache would incorrectly apply to frozen,
sealed, or non-extensible objects because it only checked if the
object's shape matched the cached "from_shape", not whether the object
was actually extensible.

Since Object.freeze(), Object.seal(), and Object.preventExtensions()
don't change the object's shape, a normal empty object {} and a
frozen Object.freeze({}) would share the same shape. The IC cache
populated from adding a property to the normal object would then be
incorrectly used for the frozen object, allowing property addition
to what should be a non-extensible object.

The fix adds an extensibility check before applying the AddOwnProperty
cache. Also adds comprehensive tests for dictionary shapes and
non-extensible object IC behavior.
2026-01-06 00:11:28 +01:00
Aliaksandr Kalenik
711100e3b7 LibJS: Avoid unnecessary NewArray in yield* iterator method calls
Use `Op::Call` directly instead of creating a single-element array and
using `CallWithArgumentArray` when calling iterator methods (`next`,
`throw`, `return`) in `yield*` expressions.
2025-12-28 19:12:15 +01:00
Andreas Kling
ce0a16d11c LibJS: Simplify how we know which builtin a FunctionObject represents
Instead of storing a list of builtin function objects with the realm,
just move the builtin field from NativeFunction up to FunctionObject.

Now you can ask any FunctionObject for its builtin(), and we no longer
need the get_builtin_value() API.

Fixes 10 test262 tests that were querying the realm builtins at a
bad time.

Regressed in 54b755126c.
2025-12-25 23:59:21 +01:00
Andreas Kling
e7e3c21123 LibJS: Shift PropertyLookupCache::types when finding a new slot
This regressed in c258282094 and broke
the polymorphic lookup cache, which was caught by the pic-* tests in
our MicroBench suite.
2025-12-21 13:00:35 -06:00
Andreas Kling
c258282094 LibJS: Shrink PropertyLookupCache by putting types in its own array
We have so many inline caches that this kind of thing becomes profitable
on complex pages. Also the memory access pattern is slightly nicer for
polymorphic caches.

Reduces memory usage on my x.com home feed by 4.9 MiB.
2025-12-21 10:06:04 -06:00
Andreas Kling
138b8f9607 LibJS: Shrink PropertyLookupCache::Entry size by tweaking layout
Reorder members and use u32 instead of Optional<u32> for things that
didn't actually need the "empty" state other than for assertions.

Reduces memory usage on my x.com home feed by 9.9 MiB.
2025-12-21 10:06:04 -06:00
Andreas Kling
ece0b72e3c LibJS: Don't set [[HomeObject]] for non-method object properties
This fixes an issue where we'd incorrectly retain objects via the
[[HomeObject]] slot. This common pattern was affected:

    Object.defineProperty(o, "foo", {
        get: function() { return 123; }
    });

Above, the object literal would get assigned to the [[HomeObject]]
slot even though "get" is not a "method" per the spec.

This frees about 30,000 objects on my x.com home feed.
2025-12-17 12:50:17 -06:00
Andreas Kling
ee9e24d1dd LibJS: Add dedicated bytecode instruction for x|0 (ToInt32)
This operation is a very common technique to force a value to become
a 32-bit integer.
2025-12-15 08:57:00 -06:00
Andreas Kling
bfe5a87c99 LibJS: Skip some hot bounds checks in the interpreter
Let's allow ourselves to trust the number of property lookup caches
present, along with a few other things.
2025-12-14 08:40:22 -06:00
Andreas Kling
65447faec9 LibJS: Avoid three PropertyKey copies in the interpreter 2025-12-14 08:40:22 -06:00
Andreas Kling
2a776f1d70 LibJS: Put the PropertyLookupCache's shape in a local
This avoids the extra check in Weak::operator->() a bunch of times.
2025-12-14 08:40:22 -06:00
Andreas Kling
54b755126c LibJS: Skip generic call when using regexp builtins in StringPrototype
For StringPrototype functions that defer to RegExpPrototype builtins,
we can skip the generic call stuff (eliding the execution context etc)
and just call the builtin directly.

1.03x speedup on Octane/regexp.js
2025-12-13 13:51:12 -06:00