But in x86-64, you have to destructure a struct into multiple pieces of data and pass them via registers. In x86 calling convention, structs are copied to the stack and their pointers are passed to functions. It feels somewhat magical because of its recursive nature.
Free c compiler internal code#
However, I don't feel I completely understand why this code behaves correctly. Although I already knew that the code should work in theory, it still made me happy when the code actually worked in a complicated test case like this. Both a struct containing an array and an array of a struct work. I'm able to create a pointer to a struct and dereference it. It seems it's working as it should I can define a struct containing a struct. It's harder to implement than primitive types, but it was easier than I expected. The struct is an object that can be larger than one word. added array subscription and pointer arithmetic.support array initialization expression.
added variables (implicitly assumed to be int).separate the parsing and the code generation phases.From the git log, it seems to have evolved this way. Every operation would require memory access, but it's OK at least for now.Īt first the compiler was about 20 lines long, and the only thing that was able to do is to read an integer from the standard input and then emit a program that immediately exits with the integer as exit code. It compiles source programs onto a stack machine that uses the machine stack as the stack. The implementation is pretty straightforward it doesn't even have register allocator. These sample programs are carefully crafted to not use unimplemented ones. Non-trivial programs, for example this one that solves the 8 queens puzzle, can compile and run. I made a good progress in the compiler implementation, and it's working surprisingly well. I've gotten better at handling pointers and arrays. Implementing these features is easy because this is the second time for me.
Here are some examples of code that work with the compiler:Īrrays are correctly decayed into pointers, so the code like this works too. It started working after writing about 1,000 lines of code. The code and its history are available at GitHub. This is a log when I was writing it from scratch by myself in 2012. I wrote a self-hosting C compiler which I named 8cc in 40 days. How I wrote a self-hosting C compiler in 40 days How I wrote a self-hosting C compiler in 40 days Rui Ueyama - December 2015