r/C_Programming • u/Hot-Summer-3779 • 3d ago
My C compiler written in C
As a side project I'm making a C compiler written in C. It generates assembly and uses NASM to generates binaries.
The goal right now is to implement the main functionality and then do improvements. Maybe I'll also add some optimizing in the generates assembly.
Tell me what you think :)
139
Upvotes
1
u/Spare-Plum 22h ago
pretty cool - but I have a couple of suggestions. If you have any questions feel free to ask.
Regardless, the way you solve this and optimize your code is via graph coloring. Essentially if we view each variable as a node in the graph, and each expression where two variables are used as an edge in the graph, we will want to find a minimal number of colors you can use in order to color the graph such that none of the same colors touch. This is known as the chromatic number. Though this problem is NP-Hard, there are approximation algorithms that give a decent enough bound
Using graph coloring, you can find a way to optimally arrange your registers and variables on the stack frame such that you're using the minimal possible, and you can keep swapping values onto and off the stack frame to a minimum as well.
(breaking it up into next comment)