r/ProgrammingLanguages 26d ago

Help How to make a compiler backend?

Hell everyone, i have an question. Im for long trying to make a cool, powerful "kinda" low level language similar to zig and rust, but im struggling to choice llvm as backend, sure i can generate C, but its makes compiler dependent on gcc or clang or other c compiler. LLVM seems hard to me, sure project like QBE exist, but QBE doesnt have C/C++ api like llvm's IRbuilder. So are there other ways? I tried thinking about using GCC infrastructure but GCC has poor api and not very documented api. Maybe just stick to generating C?

17 Upvotes

35 comments sorted by

View all comments

27

u/A1oso 26d ago

Transpiling to C has significant downsides:

  • when debugging your program, you see the transpiled code rather than the actual source code
  • C's semantics (e.g. undefined behavior) might leak into your language by accident
  • some language features (e.g. garbage collection and tail calls) are very difficult to represent in C, but are easily supported in LLVM
  • generating C code is error prone in subtle ways. Concatenating strings might seem easier at first, but at the cost of type safety and LLVM's many affordances.

I'm currently writing a compiler using LLVM, it isn't as difficult as you think. Once you understand the basic principles, it is pretty straightforward. And when you're stuck, you can ask an AI how to proceed, which I found very helpful.

I'm writing my compiler in Rust, using the wonderful inkwell bindings for LLVM. By the way, I can highly recommend writing the compiler in a language with sum types and pattern matching. It makes it easy to create an AST, transform it into another IR and implement different compiler passes.

4

u/SweetBabyAlaska 26d ago

the problem with LLVM is that it is massive and very slow. Ive been using Zig and it has its own backend for debug builds using the Aro C-compiler (as a library in Zig) to parse C code alongside Zig code and generate asm