Generating IR from the AST
The LLVM code generator takes a module in LLVM IR as input and turns it into object code or assembly text. We need to transform the AST representation into IR. To implement an IR code generator, we will look at a simple example first and then develop the classes needed for the code generator. The complete implementation will be divided into three classes:
CodeGenerator
CGModule
CGProcedure
The CodeGenerator
class is the general interface used by the compiler driver. The CGModule
and CGProcedure
classes hold the state required for generating the IR code for a compilation unit and a single function.
We’ll begin by looking at the Clang-generated IR.
Understanding the IR code
Before generating the IR code, it’s good to know the main elements of the IR language. In Chapter 2, The Structure of a Compiler, we had a brief look at IR. An easy way to get more knowledge of IR is to study the output from clang
. For example...