Commit graph

118 commits

Author SHA1 Message Date
Andreas Kling
6ca94bd0b1 LibJS/Bytecode: Rename GetVariable => GetBinding 2024-05-14 21:46:36 +02:00
Andreas Kling
b7c04f999a LibJS/Bytecode: Split SetVariable into four separate instructions
Instead of SetVariable having 2x2 modes for variable/lexical and
initialize/set, those 4 modes are now separate instructions, which
makes each instruction much less branchy.
2024-05-14 21:46:36 +02:00
Andreas Kling
640f195a70 LibJS/Bytecode: Sort ENUMERATE_BYTECODE_OPS list 2024-05-14 21:46:36 +02:00
Aliaksandr Kalenik
caffd485b8 LibJS: Replace SetLocal instruction usage with Mov
No need for separate instuction to set a local.
2024-05-14 06:39:16 +02:00
Aliaksandr Kalenik
d79438a2a6 LibJS: Join locals, constants and registers into single vector
Merging registers, constants and locals into single vector means:
- Better data locality
- No need to check type in Interpreter::get() and Interpreter::set()
  which are very hot functions

Performance improvement is visible in almost all Octane and Kraken
tests.
2024-05-13 19:54:11 +02:00
Aliaksandr Kalenik
6fb1d9e516 LibJS: Stop using execute_ast_node() for class property evaluation
Instead, generate bytecode to execute their AST nodes and save the
resulting operands inside the NewClass instruction.

Moving property expression evaluation to happen before NewClass
execution also moves along creation of new private environment and
its population with private members (private members should be visible
during property evaluation).

Before:
- NewClass

After:
- CreatePrivateEnvironment
- AddPrivateName
- ...
- AddPrivateName
- NewClass
- LeavePrivateEnvironment
2024-05-12 19:10:25 +02:00
Aliaksandr Kalenik
a4f70986a0 LibJS: Emit bytecode for function declaration instantiation
By doing that all instructions required for instantiation are emitted
once in compilation and then reused for subsequent calls, instead of
running generic instantiation process for each call.
2024-05-11 11:43:05 +02:00
Andreas Kling
810a297626 LibJS/Bytecode: Remove Instruction::execute()
Just make sure everyone calls the instruction-specific execute_impl()
instead. :^)
2024-05-10 15:03:24 +00:00
Andreas Kling
7654da3851 LibJS/Bytecode: Do basic compare-and-jump peephole optimization
We now fuse sequences like [LessThan, JumpIf] to JumpLessThan.
This is only allowed for temporaries (i.e VM registers) with no other
references to them.
2024-05-10 15:03:24 +00:00
Andreas Kling
e43d96f310 LibJS/Bytecode: Remove Instruction::m_length field
Now that the interpreter is unrolled, we can advance the program counter
manually based on the current instruction type.

This makes most instructions a bit smaller. :^)
2024-05-07 09:15:40 +02:00
Andreas Kling
ce93000757 LibJS/Bytecode: Unroll the bytecode interpreter
This commit adds a HANDLE_INSTRUCTION macro that expands to everything
needed to handle a single instruction (invoking the handler function,
checking for exceptions, and advancing the program counter).

This gives a ~15% speed-up on a for loop microbenchmark, and makes
basically everything faster.
2024-05-07 09:15:40 +02:00
Andreas Kling
fae1527a18 LibJS/Bytecode: Turn JumpIf condition,@a,@next into JumpTrue/JumpFalse
If one of the jump targets is the very next block, we can convert the
jump instruction into a smaller JumpTrue or JumpFalse.
2024-05-07 09:15:40 +02:00
Andreas Kling
5a08544138 LibJS/Bytecode: Keep instruction source mappings in Executable
Instead of storing source offsets with each instruction, we now keep
them in a side table in Executable.

This shrinks each instruction by 8 bytes, further improving locality.
2024-05-07 09:15:40 +02:00
Andreas Kling
4cf4ea92a7 LibJS/Bytecode: Store Instruction length as u32
This makes every instruction 8 bytes smaller.
2024-05-07 09:15:40 +02:00
Andreas Kling
f6aee2b9e8 LibJS/Bytecode: Flatten bytecode to a contiguous representation
Instead of keeping bytecode as a set of disjoint basic blocks on the
malloc heap, bytecode is now a contiguous sequence of bytes(!)

The transformation happens at the end of Bytecode::Generator::generate()
and the only really hairy part is rerouting jump labels.

This required solving a few problems:

- The interpreter execution loop had to change quite a bit, since we
  were storing BasicBlock pointers all over the place, and control
  transfer was done by redirecting the interpreter's current block.

- Exception handlers & finalizers are now stored per-bytecode-range
  in a side table in Executable.

- The interpreter now has a plain program counter instead of a stream
  iterator. This actually makes error stack generation a bit nicer
  since we just have to deal with a number instead of reaching into
  the iterator.

This yields a 25% performance improvement on this microbenchmark:

    for (let i = 0; i < 1_000_000; ++i) { }

But basically everything gets faster. :^)
2024-05-07 09:15:40 +02:00
Hendiadyoin1
ada5027163 LibJS: Cleanup unwind state when transferring control out of a finalizer
This does two things:
* Clear exceptions when transferring control out of a finalizer
  Otherwise they would resurface at the end of the next finalizer
  (see test the new test case), or at the end of a function
* Pop one scheduled jump when transferring control out of a finalizer
  This removes one old FIXME
2024-05-02 07:27:45 +02:00
Hendiadyoin1
b4b9c4b383 LibJS: Restore scheduled jumps in catch blocks without finalizers 2024-05-02 07:27:45 +02:00
Andreas Kling
5b69413c4b Revert "LibJS/Bytecode: Bring back the bytecode optimization pipeline"
This reverts commit 5b29974bfa.
2024-03-06 08:39:29 +01:00
Andreas Kling
cf81bf48c6 Revert "LibJS/Bytecode: Add peephole optimization pass and fuse compare+jump"
This reverts commit 4438ec481c.

Fixes #23480.
2024-03-06 08:39:29 +01:00
Andreas Kling
c4a0afbe28 Revert "LibJS/Bytecode: Fuse [Not, JumpIf] instructions into JumpIfNot"
This reverts commit 795149e585.
2024-03-06 08:39:29 +01:00
Andreas Kling
795149e585 LibJS/Bytecode: Fuse [Not, JumpIf] instructions into JumpIfNot 2024-03-04 20:54:51 +01:00
Andreas Kling
4438ec481c LibJS/Bytecode: Add peephole optimization pass and fuse compare+jump
This patch adds a new "Peephole" pass for performing small, local
optimizations to bytecode.

We also introduce the first such optimization, fusing a sequence of
some comparison instruction FooCompare followed by a JumpIf into a
new set of JumpFooCompare instructions.

This gives a ~50% speed-up on the following microbenchmark:

    for (let i = 0; i < 10_000_000; ++i) {
    }

But more traditional benchmarks see a pretty sizable speed-up as well,
for example 15% on Kraken/ai-astar.js and 16% on Kraken/audio-dft.js :^)
2024-03-04 20:54:51 +01:00
Andreas Kling
5b29974bfa LibJS/Bytecode: Bring back the bytecode optimization pipeline
...minus the EliminateLoads pass, since it was not compatible with the
new bytecode format.
2024-03-04 20:54:51 +01:00
Andreas Kling
5813df21c8 LibJS/Bytecode: Make primitive bigints be constants
Instead of emitting a NewBigInt instruction to construct a primitive
bigint from a parsed literal, we now instantiate the BigInt on the heap
during codegen.
2024-03-03 22:27:44 +01:00
Andreas Kling
46d209c55b LibJS/Bytecode: Make primitive strings be constants
Instead of emitting a NewString instruction to construct a primitive
string from a parsed literal, we now instantiate the PrimitiveString on
the heap during codegen.
2024-03-03 22:27:44 +01:00
Andreas Kling
9d9b737a58 LibJS/Bytecode: Dedicated instructions for postfix increment/decrement
Instead of splitting the postfix variants into ToNumeric + Inc/Dec,
we now have dedicated PostfixIncrement and PostfixDecrement instructions
that handle both outputs in one go.
2024-02-20 21:25:18 +01:00
Andreas Kling
e46b217e42 LibJS/Bytecode: Move to a new bytecode format
This patch moves us away from the accumulator-based bytecode format to
one with explicit source and destination registers.

The new format has multiple benefits:

- ~25% faster on the Kraken and Octane benchmarks :^)
- Fewer instructions to accomplish the same thing
- Much easier for humans to read(!)

Because this change requires a fundamental shift in how bytecode is
generated, it is quite comprehensive.

Main implementation mechanism: generate_bytecode() virtual function now
takes an optional "preferred dst" operand, which allows callers to
communicate when they have an operand that would be optimal for the
result to go into. It also returns an optional "actual dst" operand,
which is where the completion value (if any) of the AST node is stored
after the node has "executed".

One thing of note that's new: because instructions can now take locals
as operands, this means we got rid of the GetLocal instruction.
A side-effect of that is we have to think about the temporal deadzone
(TDZ) a bit differently for locals (GetLocal would previously check
for empty values and interpret that as a TDZ access and throw).
We now insert special ThrowIfTDZ instructions in places where a local
access may be in the TDZ, to maintain the correct behavior.

There are a number of progressions and regressions from this test:

A number of async generator tests have been accidentally fixed while
converting the implementation to the new bytecode format. It didn't
seem useful to preserve bugs in the original code when converting it.

Some "does eval() return the correct completion value" tests have
regressed, in particular ones related to propagating the appropriate
completion after control flow statements like continue and break.
These are all fairly obscure issues, and I believe we can continue
working on them separately.

The net test262 result is a progression though. :^)
2024-02-19 21:45:27 +01:00
Andreas Kling
3466771492 LibJS/Bytecode: Add Bytecode::Operand
An Operand is either a register, a local, or a constant (index into the
executable's constant table)
2024-02-19 21:45:27 +01:00
Ali Mohammad Pur
5e1499d104 Everywhere: Rename {Deprecated => Byte}String
This commit un-deprecates DeprecatedString, and repurposes it as a byte
string.
As the null state has already been removed, there are no other
particularly hairy blockers in repurposing this type as a byte string
(what it _really_ is).

This commit is auto-generated:
  $ xs=$(ack -l \bDeprecatedString\b\|deprecated_string AK Userland \
    Meta Ports Ladybird Tests Kernel)
  $ perl -pie 's/\bDeprecatedString\b/ByteString/g;
    s/deprecated_string/byte_string/g' $xs
  $ clang-format --style=file -i \
    $(git diff --name-only | grep \.cpp\|\.h)
  $ gn format $(git ls-files '*.gn' '*.gni')
2023-12-17 18:25:10 +03:30
Andreas Kling
350e6c54d7 LibJS: Remove dedicated iterator result instructions in favor of GetById
When iterating over an iterable, we get back a JS object with the fields
"value" and "done".

Before this change, we've had two dedicated instructions for retrieving
the two fields: IteratorResultValue and IteratorResultDone. These had no
fast path whatsoever and just did a generic [[Get]] access to fetch the
corresponding property values.

By replacing the instructions with GetById("value") and GetById("done"),
they instantly get caching and JIT fast paths for free, making iterating
over iterables much faster. :^)

26% speed-up on this microbenchmark:

    function go(a) {
        for (const p of a) {
        }
    }
    const a = [];
    a.length = 1_000_000;
    go(a);
2023-12-07 18:12:24 +01:00
Andreas Kling
4699c81fc1 LibJS: Stop converting between Object <-> IteratorRecord all the time
This patch makes IteratorRecord an Object. Although it's not exposed to
author code, this does allow us to store it in a VM register.

Now that we can store it in a VM register, we don't need to convert it
back and forth between IteratorRecord and Object when accessing it from
bytecode.

The big win here is avoiding 3 [[Get]] accesses on every iteration step
of for..of loops. There are also a bunch of smaller efficiencies gained.

20% speed-up on this microbenchmark:

    function go(a) {
        for (const p of a) {
        }
    }
    const a = [];
    a.length = 1_000_000;
    go(a);
2023-12-07 14:06:34 +01:00
Andreas Kling
ecfcc9aef3 LibJS: Make Bytecode::Executable GC-allocated
This is a step towards making ExecutionContext easier to allocate.
2023-11-29 09:48:18 +01:00
Idan Horowitz
f19349e1b6 LibJS: Instantiate primitive array expressions using a single operation
This will not meaningfully affect short array literals, but it does
give us a bit of extra perf when evaluating huge array expressions like
in Kraken/imaging-darkroom.js
2023-11-18 08:37:34 +01:00
Andreas Kling
cfdb8a2756 LibJS/JIT: Update "unwind context" stack in JIT code
Until now, the unwind context stack has not been maintained by jitted
code, which meant we were unable to support the `with` statement.
This is a first step towards supporting that by making jitted code
call out to C++ to update the unwind context stack when entering/leaving
unwind contexts.

We also introduce a new "Catch" bytecode instruction that moves the
current exception into the accumulator. It's always emitted at the start
of a "catch" block.
2023-11-12 14:21:41 +01:00
Simon Wanner
dd466ec83a LibJS/Bytecode: Remove the PushDeclarativeEnvironment instruction 2023-11-03 07:31:11 +01:00
Simon Wanner
fb7b4b9c59 LibJS/JIT: Provide source location information for JIT code
This works by walking a backtrace until the currently executing
native executable is found, and then mapping the native address
to its bytecode instruction.
2023-10-31 07:07:17 +01:00
Andreas Kling
c14db6ab12 LibJS: Make Executable ref-counted and let instruction iterator co-own it
This ensures that the instruction stream pointed at by the instruction
iterator remains valid as long as the iterator exists.
2023-10-03 08:23:33 +02:00
Andreas Kling
031ec98803 LibJS: Streamline InstructionStreamIterator
Nuke all the per-instruction bounds checking when iterating instructions
by using raw pointers instead of indexing into a ReadonlyBytes.

The interpreter loop already checks that we're in-bounds anyway.
2023-09-28 06:09:16 +02:00
Andreas Kling
3d5cd23393 LibJS: Remove unused Instruction::is_terminator() 2023-09-21 16:19:13 +02:00
Andreas Kling
a7c1af08ca LibJS: Store bytecode instruction length in instruction itself
Instead of running a big switch statement on the opcode when checking
how long an instruction is, we now simply store that in a member
variable at construction time for instant access.

This yields a 10.2% speed-up on Kraken/ai-astar :^)
2023-09-14 16:11:14 +02:00
Andreas Kling
1c06111cbd LibJS: Add file & line number to bytecode VM stack traces :^)
This works by adding source start/end offset to every bytecode
instruction. In the future we can make this more efficient by keeping
a map of bytecode ranges to source ranges in the Executable instead,
but let's just get traces working first.

Co-Authored-By: Andrew Kaster <akaster@serenityos.org>
2023-09-02 15:37:53 +02:00
Andreas Kling
e91bdedc93 LibJS: Use correct this value when callee is a with binding
If we're inside of a `with` statement scope, we have to take care to
extract the correct `this` value for use in calls when calling a method
on the binding object via an Identifier instead of a MemberExpression.

This makes Vue.js work way better in the bytecode VM. :^)

Also, 1 new pass on test262.
2023-08-01 16:08:21 +02:00
Timothy Flynn
77d7f715e3 LibJS+CI: Remove bytecode optimization passes for now
These passes have not been shown to actually optimize any JS, and tests
have become very flaky with optimizations enabled. Until some measurable
benefit is shown, remove the optimization passes to reduce overhead of
maintaining bytecode operations and to reduce CI churn. The framework
for optimizations will live on in git history, and can be restored once
proven useful.
2023-07-21 19:47:36 +03:30
Luke Wilde
d66eb4e3ba LibJS/Bytecode: Add Await and AsyncIteratorClose instructions 2023-07-15 01:08:52 +02:00
Gabriel Dinner-David
d29bd55b48 LibJS: Implement import.meta for bytecode 2023-07-14 06:06:04 +02:00
Aliaksandr Kalenik
3661d674ae LibJS: Add optimized GetGlobal instruction to access global variables
Using a special instruction to access global variables allows skipping
the environment chain traversal for them and going directly to the
module/global environment. Currently, this instruction only caches the
offset for bindings that belong to the global object environment.
However, there is also an opportunity to cache the offset in the global
declarative record.

This change results in a 57% increase in speed for
imaging-gaussian-blur.js in Kraken.
2023-07-12 16:03:16 +02:00
Timothy Flynn
23daf5097b LibJS/Bytecode: Generate bytecode for deleting super properties 2023-07-07 18:11:51 +02:00
Luke Wilde
b271d9a6bf LibJS/Bytecode: Use proper this for receiver in get/set for super expr
Summary:
    Diff Tests:
        +14     -2     -12 📝
2023-07-06 08:54:46 +02:00
Aliaksandr Kalenik
ae3a7fd4b8 LibJS: Update bytecode generator to use local variables
- Update ECMAScriptFunctionObject::function_declaration_instantiation
  to initialize local variables
- Introduce GetLocal, SetLocal, TypeofLocal that will be used to
  operate on local variables.
- Update bytecode generator to emit instructions for local variables
2023-07-05 21:03:01 +02:00
Andreas Kling
e87d84f883 LibJS/Bytecode: Support in binary operator for private fields
11 new passes on test262. :^)
2023-07-05 15:39:25 +02:00