elikaski / BF-it

A C-like language to Brainfuck compiler, written in Python
MIT License
121 stars 11 forks source link

Make local variables in functions a bit more optimized. #49

Open NeeEoo opened 3 years ago

NeeEoo commented 3 years ago
int add(int a, int b) {
     return a + b; 
}
int add_optimized(int a, int b) {
     return a%% + b%%; 
}

int main() {
    add(4, 5);
    add_optimized(4, 5);
}

Code for add(4, 5)

>[-]>[-]++++>[-]+++++>[-]>[-]<<<[>>+>+<<<-]>>>[<<<+>>>-]>[-]<<<[>>+>+<<<-]>>>[<<<+>>>-]<[<+>-]<<<<[-]>>>[<<<+>>>-]<<<<

Code for add_optimized(4, 5)

>[-]>[-]++++>[-]+++++>[-]>[-]<<<[>>+>+<<<-]>>>[-]>[-]<<<[>>+>+<<<-]>>[<+>-]<<<<[-]>>>[<<<+>>>-]<<<<

The compiler could make the local (not global) variables used in the return expression, be more optimized by not making the variable not be copied back.

It could be made so it only optimizes the return expression if it doesn't assign values or use the same variable twice. Since if the return expression is a + y*f + a/2, if it applied the optimization the second use of the a variable would be zero. If it should be able to optimize it, it should be able to find the last use of the variable. So the resulting expression would be a + y%% * f%% + a%%/2

It might be a good thing to make a flag named OPTIMIZE_LEVEL in the build flags file. And that flag could be changed with a cli flag such as -O1 and that sets OPTIMIZE_LEVEL to 1. The default value would be 0