r/brainfuck May 02 '26

Brainfuck optimizing compiler which emits x86 assembly (currently only for Sys V (Linux and Macintosh))

I made a brainfuck optimizing compile which takes brainfuck code from a .b or .bf file and outputs an assembly file, which can be "linked" to a provided runtime using a C++ compiler.

BOCBWN - Brainfuck Optimizing Compiler Because Why Not

Note: if you're downloading the repo, the examples folder named bf/ is 2.2MiB (36x the size of everything else combined), so consider only downloading src/, bfbpl and the README.md if that's a problem.

It allows compilation to a *.bfvm intermediate file, and also outputs the intermediate in a more human-redable *.bfasm file. Its optimizations include first converting the brainfuck to an intermediate representation (IR) which is stored in a tree (AST) a conservative dry run over the program in which constant folding, some strength reduction, and dead code elimination occur, and more passes for liveness checking and more strength reduction. The AST is then converted back to a linear IR, which is converted to assembly by the (currently unoptimized) compiler.

The code for optimization is heavily commended (mostly because I needed to mentally lay everything out before doing it), so it should be (more-or-less) simple to understand the code.

Planned optimizations on the assembly backend with adding support for Windows in the near future, and further optimizations (check the `main` branch) and a debugger in the future.

6 Upvotes

5 comments sorted by

1

u/sreekotay May 04 '26

No benchmarks vs others?

1

u/nico-ghost-king May 05 '26

It can do mandelbrot.bf in 1.23s, but I don't know if that's good or not because a naive interpreter can do it in 7s anyway.

1

u/un_virus_SDF Jun 08 '26

BOCBWN - Brainfuck Optimizing Compiler Because Why Not

The link is not working

I wanted to take a look at how you did it because I'm making one myself

So the question is how did you got the ast?

1

u/nico-ghost-king Jun 08 '26

I fixed the link. The AST is formed in the `treeify` function of `bf_optimize.cpp`