How to create a C compiler for custom CPU?

JustJeff picture JustJeff · Jan 2, 2012 · Viewed 18.7k times · Source

What would be the easiest way to create a C compiler for a custom CPU, assuming of course I already have an assembler for it?

Since a C compiler generates assembly, is there some way to just define standard bits and pieces of assembly code for the various C idioms, rebuild the compiler, and thereby obtain a cross compiler for the target hardware?

Preferably the compiler itself would be written in C, and build as a native executable for either Linux or Windows.

Please note: I am not asking how to write the compiler itself. I did take that course in college, I know about general compiler-compilers, etc. In this situation, I'd just like to configure some existing framework if at all possible. I don't want to modify the language, I just want to be able to target an arbitrary architecture. If the answer turns out to be "it doesn't work that way", that information will be useful to myself and anyone else who might make similar assumptions.

Answer

Pubby picture Pubby · Jan 2, 2012

Quick overview/tutorial on writing a LLVM backend.

This document describes techniques for writing backends for LLVM which convert the LLVM representation to machine assembly code or other languages.

[ . . . ]

To create a static compiler (one that emits text assembly), you need to implement the following:

  • Describe the register set.
  • Describe the instruction set.
  • Describe the target machine.
  • Implement the assembly printer for the architecture.
  • Implement an instruction selector for the architecture.