HoneyPony / jaylox

A compiler/transpiler targetting C, for the Lox language from Crafting Interpreters
0 stars 0 forks source link

Simple 'fence' optimization #3

Open HoneyPony opened 3 months ago

HoneyPony commented 3 months ago

The idea here is that, instead of having specialized functions for things like arithmetic operations, we just directly generate code like:

// expr: subtract
jay_check_numerical(jay_stack_ptr[-2]);
jay_check_numerical(jay_stack_ptr[-1]);
jay_stack_ptr[-2] = JAY_AS_NUMBER(jay_stack_ptr[-2]) - JAY_AS_NUMBER(jay_stack_ptr[-1]);
jay_stack_ptr -= 1;

Then, we can very easily check if one if the inner expressions is an expression that MUST produce a number, and simply elide that 'check'. Obviously, this is still a little bit slower than if we don't go through the stack at all, but it's an easy optimization.

In fact, it should be relatively straightforward to bridge from doing that to just checking the operands in a larger expression and then directly generating an arithmetic expression. But this simple optimization could be done just with some very basic pattern matching in the compiler.

HoneyPony commented 3 months ago

One very interesting thing:

Just adding the fence generation, without even implementing fence elision, already speeds up fib.lox (inside ci_benchmarks) to almost 4/5 as much time.

It's possible that this just lets the compiler see the idea itself. But, we might as well implement fence elision to see if that helps.