The LLVM Target-Independent Code Generator

1. Introduction
   - Required components in the code generator
   - The high-level design of the code generator
   - Using TableGen for target description
2. Target description classes
   - The `TargetMachine` class
   - The `TargetData` class
   - The `TargetLowering` class
   - The `MRegisterInfo` class
   - The `TargetInstrInfo` class
   - The `TargetFrameInfo` class
   - The `TargetJITInfo` class
3. Machine code description classes
   - The `MachineInstr` class
4. Target-independent code generation algorithms
   - Instruction Selection
     - Introduction to SelectionDAGs
     - SelectionDAG Code Generation Process
     - Initial SelectionDAG Construction
     - SelectionDAG Legalize Phase
     - SelectionDAG Optimization Phase
     - SelectionDAG Select Phase
     - Future directions for the SelectionDAG
5. Target description implementations
   - The X86 backend

Written by Chris Lattner

Warning: This is a work in progress.

Introduction

The LLVM target-independent code generator is a framework that provides a suite of reusable components for translating the LLVM internal representation to the machine code for a specified target -- either in assembly form (suitable for a static compiler) or in binary machine code format (usable for a JIT compiler). The LLVM target-independent code generator consists of five main components:

1. Abstract target description interfaces which capture important properties about various aspects of the machine, independently of how they will be used. These interfaces are defined in `include/llvm/Target/`.
2. Classes used to represent the machine code being generated for a target. These classes are intended to be abstract enough to represent the machine code for any target machine. These classes are defined in `include/llvm/CodeGen/`.
3. Target-independent algorithms used to implement various phases of native code generation (register allocation, scheduling, stack frame representation, etc). This code lives in `lib/CodeGen/`.
4. Implementations of the abstract target description interfaces for particular targets. These machine descriptions make use of the components provided by LLVM, and can optionally provide custom target-specific passes, to build complete code generators for a specific target. Target descriptions live in `lib/Target/`.
5. The target-independent JIT components. The LLVM JIT is completely target independent (it uses the `TargetJITInfo` structure to interface for target-specific issues. The code for the target-independent JIT lives in `lib/ExecutionEngine/JIT`.

Depending on which part of the code generator you are interested in working on, different pieces of this will be useful to you. In any case, you should be familiar with the target description and machine code representation classes. If you want to add a backend for a new target, you will need to implement the target description classes for your new target and understand the LLVM code representation. If you are interested in implementing a new code generation algorithm, it should only depend on the target-description and machine code representation classes, ensuring that it is portable.

Required components in the code generator

The two pieces of the LLVM code generator are the high-level interface to the code generator and the set of reusable components that can be used to build target-specific backends. The two most important interfaces (`TargetMachine` and `TargetData`) are the only ones that are required to be defined for a backend to fit into the LLVM system, but the others must be defined if the reusable code generator components are going to be used.

This design has two important implications. The first is that LLVM can support completely non-traditional code generation targets. For example, the C backend does not require register allocation, instruction selection, or any of the other standard components provided by the system. As such, it only implements these two interfaces, and does its own thing. Another example of a code generator like this is a (purely hypothetical) backend that converts LLVM to the GCC RTL form and uses GCC to emit machine code for a target.

This design also implies that it is possible to design and implement radically different code generators in the LLVM system that do not make use of any of the built-in components. Doing so is not recommended at all, but could be required for radically different targets that do not fit into the LLVM machine description model: programmable FPGAs for example.

Important Note: For historical reasons, the LLVM SparcV9 code generator uses almost entirely different code paths than described in this document. For this reason, there are some deprecated interfaces (such as `TargetRegInfo` and `TargetSchedInfo`), which are only used by the V9 backend and should not be used by any other targets. Also, all code in the `lib/Target/SparcV9` directory and subdirectories should be considered deprecated, and should not be used as the basis for future code generator work. The SparcV9 backend is slowly being merged into the rest of the target-independent code generators, but this is a low-priority process with no predictable completion date.

The high-level design of the code generator

The LLVM target-independent code generator is designed to support efficient and quality code generation for standard register-based microprocessors. Code generation in this model is divided into the following stages:

1. Instruction Selection - Determining an efficient implementation of the input LLVM code in the target instruction set. This stage produces the initial code for the program in the target instruction set, then makes use of virtual registers in SSA form and physical registers that represent any required register assignments due to target constraints or calling conventions.
2. SSA-based Machine Code Optimizations - This optional stage consists of a series of machine-code optimizations that operate on the SSA-form produced by the instruction selector. Optimizations like modulo-scheduling, normal scheduling, or peephole optimization work here.
3. Register Allocation - The target code is transformed from an infinite virtual register file in SSA form to the concrete register file used by the target. This phase introduces spill code and eliminates all virtual register references from the program.
4. Prolog/Epilog Code Insertion - Once the machine code has been generated for the function and the amount of stack space required is known (used for LLVM alloca's and spill slots), the prolog and epilog code for the function can be inserted and "abstract stack location references" can be eliminated. This stage is responsible for implementing optimizations like frame-pointer elimination and stack packing.
5. Late Machine Code Optimizations - Optimizations that operate on "final" machine code can go here, such as spill code scheduling and peephole optimizations.
6. Code Emission - The final stage actually puts out the code for the current function, either in the target assembler format or in machine code.

The code generator is based on the assumption that the instruction selector will use an optimal pattern matching selector to create high-quality sequences of native instructions. Alternative code generator designs based on pattern expansion and aggressive iterative peephole optimization are much slower. This design permits efficient compilation (important for JIT environments) and aggressive optimization (used when generating code offline) by allowing components of varying levels of sophistication to be used for any step of compilation.

In addition to these stages, target implementations can insert arbitrary target-specific passes into the flow. For example, the X86 target uses a special pass to handle the 80x87 floating point stack architecture. Other targets with unusual requirements can be supported with custom passes as needed.

Using TableGen for target description

The target description classes require a detailed description of the target architecture. These target descriptions often have a large amount of common information (e.g., an `add` instruction is almost identical to a `sub` instruction). In order to allow the maximum amount of commonality to be factored out, the LLVM code generator uses the TableGen tool to describe big chunks of the target machine, which allows the use of domain-specific and target-specific abstractions to reduce the amount of repetition.

Target description classes

The LLVM target description classes (which are located in the `include/llvm/Target` directory) provide an abstract description of the target machine; independent of any particular client. These classes are designed to capture the abstract properties of the target (such as the instructions and registers it has), and do not incorporate any particular pieces of code generation algorithms. These interfaces do not take interference graphs as inputs or other algorithm-specific data structures.

All of the target description classes (except the `TargetData` class) are designed to be subclassed by the concrete target implementation, and have virtual methods implemented. To get to these implementations, the `TargetMachine` class provides accessors that should be implemented by the target.

The `TargetMachine` class

The `TargetMachine` class provides virtual methods that are used to access the target-specific implementations of the various target description classes via the `get*Info` methods (`getInstrInfo`, `getRegisterInfo`, `getFrameInfo`, etc.). This class is designed to be specialized by a concrete target implementation (e.g., `X86TargetMachine`) which implements the various virtual methods. The only required target description class is the `TargetData` class, but if the code generator components are to be used, the other interfaces should be implemented as well.

The `TargetData` class

The `TargetData` class is the only required target description class, and it is the only class that is not extensible. You cannot derived a new class from it. `TargetData` specifies information about how the target lays out memory for structures, the alignment requirements for various data types, the size of pointers in the target, and whether the target is little-endian or big-endian.

The `TargetLowering` class

The `TargetLowering` class is used by SelectionDAG based instruction selectors primarily to describe how LLVM code should be lowered to SelectionDAG operations. Among other things, this class indicates:

- an initial register class to use for various ValueTypes,
- which operations are natively supported by the target machine,
- the return type of setcc operations, and
- the type to use for shift amounts, etc
.

The `MRegisterInfo` class

The `MRegisterInfo` class (which will eventually be renamed to `TargetRegisterInfo`) is used to describe the register file of the target and any interactions between the registers.

Registers in the code generator are represented in the code generator by unsigned numbers. Physical registers (those that actually exist in the target description) are unique small numbers, and virtual registers are generally large.

Each register in the processor description has an associated `MRegisterDesc` entry, which provides a textual name for the register (used for assembly output and debugging dumps), a set of aliases (used to indicate that one register overlaps with another), and some flag bits.

In addition to the per-register description, the `MRegisterInfo` class exposes a set of processor specific register classes (instances of the `TargetRegisterClass` class). Each register class contains sets of registers that have the same properties (for example, they are all 32-bit integer registers). Each SSA virtual register created by the instruction selector has an associated register class. When the register allocator runs, it replaces virtual registers with a physical register in the set.

The target-specific implementations of these classes is auto-generated from a TableGen description of the register file.

The `TargetInstrInfo` class
The `TargetFrameInfo` class
The `TargetJITInfo` class
Machine code description classes

At the high-level, LLVM code is translated to a machine specific representation formed out of MachineFunction, MachineBasicBlock, and `MachineInstr` instances (defined in include/llvm/CodeGen). This representation is completely target agnostic, representing instructions in their most abstract form: an opcode and a series of operands. This representation is designed to support both SSA representation for machine code, as well as a register allocated, non-SSA form.

The `MachineInstr` class

Target machine instructions are represented as instances of the `MachineInstr` class. This class is an extremely abstract way of representing machine instructions. In particular, it only keeps track of an opcode number and a set of operands.

The opcode number is a simple unsigned number that only has meaning to a specific backend. All of the instructions for a target should be defined in the `*InstrInfo.td` file for the target. The opcode enum values are auto-generated from this description. The `MachineInstr` class does not have any information about how to interpret the instruction (i.e., what the semantics of the instruction are): for that you must refer to the `TargetInstrInfo` class.

The operands of a machine instruction can be of several different types: they can be a register reference, constant integer, basic block reference, etc. In addition, a machine operand should be marked as a def or a use of the value (though only registers are allowed to be defs).

By convention, the LLVM code generator orders instruction operands so that all register definitions come before the register uses, even on architectures that are normally printed in other orders. For example, the SPARC add instruction: "`add %i1, %i2, %i3`" adds the "%i1", and "%i2" registers and stores the result into the "%i3" register. In the LLVM code generator, the operands should be stored as "`%i3, %i1, %i2`": with the destination first.

Keeping destination (definition) operands at the beginning of the operand list has several advantages. In particular, the debugging printer will print the instruction like this:

      %r3 = add %i1, %i2

If the first operand is a def, and it is also easier to create instructions whose only def is the first operand.

Using the `MachineInstrBuilder.h` functions

Machine instructions are created by using the `BuildMI` functions, located in the `include/llvm/CodeGen/MachineInstrBuilder.h` file. The `BuildMI` functions make it easy to build arbitrary machine instructions. Usage of the `BuildMI` functions look like this:

      // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
      // instruction.  The '1' specifies how many operands will be added.
      MachineInstr *MI = BuildMI(X86::MOV32ri, 1, DestReg).addImm(42);

      // Create the same instr, but insert it at the end of a basic block.
      MachineBasicBlock &MBB = ...
      BuildMI(MBB, X86::MOV32ri, 1, DestReg).addImm(42);

      // Create the same instr, but insert it before a specified iterator point.
      MachineBasicBlock::iterator MBBI = ...
      BuildMI(MBB, MBBI, X86::MOV32ri, 1, DestReg).addImm(42);

      // Create a 'cmp Reg, 0' instruction, no destination reg.
      MI = BuildMI(X86::CMP32ri, 2).addReg(Reg).addImm(0);
      // Create an 'sahf' instruction which takes no operands and stores nothing.
      MI = BuildMI(X86::SAHF, 0);

      // Create a self looping branch instruction.
      BuildMI(MBB, X86::JNE, 1).addMBB(&MBB);

The key thing to remember with the `BuildMI` functions is that you have to specify the number of operands that the machine instruction will take. This allows for efficient memory allocation. You also need to specify if operands default to be uses of values, not definitions. If you need to add a definition operand (other than the optional destination register), you must explicitly mark it as such.

Fixed (preassigned) registers

One important issue that the code generator needs to be aware of is the presence of fixed registers. In particular, there are often places in the instruction stream where the register allocator must arrange for a particular value to be in a particular register. This can occur due to limitations of the instruction set (e.g., the X86 can only do a 32-bit divide with the `EAX`/`EDX` registers), or external factors like calling conventions. In any case, the instruction selector should emit code that copies a virtual register into or out of a physical register when needed.

For example, consider this simple LLVM example:

      int %test(int %X, int %Y) {
        %Z = div int %X, %Y
        ret int %Z
      }

The X86 instruction selector produces this machine code for the div and ret (use "`llc X.bc -march=x86 -print-machineinstrs`" to get this):

            ;; Start of div
            %EAX = mov %reg1024           ;; Copy X (in reg1024) into EAX
            %reg1027 = sar %reg1024, 31
            %EDX = mov %reg1027           ;; Sign extend X into EDX
            idiv %reg1025                 ;; Divide by Y (in reg1025)
            %reg1026 = mov %EAX           ;; Read the result (Z) out of EAX

            ;; Start of ret
            %EAX = mov %reg1026           ;; 32-bit return value goes in EAX
            ret

By the end of code generation, the register allocator has coalesced the registers and deleted the resultant identity moves, producing the following code:

            ;; X is in EAX, Y is in ECX
            mov %EAX, %EDX
            sar %EDX, 31
            idiv %ECX
            ret

This approach is extremely general (if it can handle the X86 architecture, it can handle anything!) and allows all of the target specific knowledge about the instruction stream to be isolated in the instruction selector. Note that physical registers should have a short lifetime for good code generation, and all physical registers are assumed dead on entry and exit of basic blocks (before register allocation). Thus if you need a value to be live across basic block boundaries, it must live in a virtual register.

Machine code SSA form

`MachineInstr`'s are initially selected in SSA-form, and are maintained in SSA-form until register allocation happens. For the most part, this is trivially simple since LLVM is already in SSA form: LLVM PHI nodes become machine code PHI nodes, and virtual registers are only allowed to have a single definition.

After register allocation, machine code is no longer in SSA-form, as there are no virtual registers left in the code.

Target-independent code generation algorithms

This section documents the phases described in the high-level design of the code generator. It explains how they work and some of the rationale behind their design.

Instruction Selection

Instruction Selection is the process of translating LLVM code presented to the code generator into target-specific machine instructions. There are several well-known ways to do this in the literature. In LLVM there are two main forms: the old-style 'simple' instruction selector (which effectively peephole selects each LLVM instruction into a series of machine instructions), and the new SelectionDAG based instruction selector.

The 'simple' instruction selectors are tedious to write, require a lot of boiler plate code, and are difficult to get correct. Additionally, any optimizations written for a simple instruction selector cannot be used by other targets. For this reason, LLVM is moving to a new SelectionDAG based instruction selector, which is described in this section. If you are starting a new port, we recommend that you write the instruction selector using the SelectionDAG infrastructure.

In time, most of the target-specific code for instruction selection will be auto-generated from the target description (`*.td`) files. For now, however, the Select Phase must still be written by hand.

Introduction to SelectionDAGs

The SelectionDAG provides an abstraction for code representation in a way that is amenable to instruction selection using automatic techniques (e.g. dynamic-programming based optimal pattern matching selectors), It is also well suited to other phases of code generation; in particular, instruction scheduling. Additionally, the SelectionDAG provides a host representation where a large variety of very-low-level (but target-independent) optimizations may be performed: ones which require extensive information about the instructions efficiently supported by the target.

The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the `SDNode` class. The primary payload of the `SDNode` is its operation code (Opcode) that indicates what operation the node performs. The various operation node types are described at the top of the `include/llvm/CodeGen/SelectionDAGNodes.h` file. Depending on the operation, nodes may contain additional information (e.g. the condition code for a SETCC node) contained in a derived class.

Although most operations define a single value, each node in the graph may define multiple values. For example, a combined div/rem operation will define both the dividend and the remainder. Many other situations require multiple values as well. Each node also has some number of operands, which are edges to the node defining the used value. Because nodes may define multiple values, edges are represented by instances of the `SDOperand` class, which is a <SDNode, unsigned> pair, indicating the node and result value being used, respectively. Each value produced by an SDNode has an associated MVT::ValueType, indicating what type the value is.

SelectionDAGs contain two different kinds of values: those that represent data flow and those that represent control flow dependencies. Data values are simple edges with an integer or floating point value type. Control edges are represented as "chain" edges which are of type MVT::Other. These edges provide an ordering between nodes that have side effects (such as loads/stores/calls/return/etc). All nodes that have side effects should take a token chain as input and produce a new one as output. By convention, token chain inputs are always operand #0, and chain results are always the last value produced by an operation.

A SelectionDAG has designated "Entry" and "Root" nodes. The Entry node is always a marker node with an Opcode of ISD::EntryToken. The Root node is the final side-effecting node in the token chain. For example, in a single basic block function, this would be the return node.

One important concept for SelectionDAGs is the notion of a "legal" vs. "illegal" DAG. A legal DAG for a target is one that only uses supported operations and supported types. On PowerPC, for example, a DAG with any values of i1, i8, i16, or i64 type would be illegal. The legalize phase is responsible for turning an illegal DAG into a legal DAG.

SelectionDAG Instruction Selection Process

SelectionDAG-based instruction selection consists of the following steps:

1. Build initial DAG - This stage performs a simple translation from the input LLVM code to an illegal SelectionDAG.
2. Optimize SelectionDAG - This stage performs simple optimizations on the SelectionDAG to simplify it and recognize meta instructions (like rotates and div/rem pairs) for targets that support these meta operations. This makes the resultant code more efficient and the 'select instructions from DAG' phase (below) simpler.
3. Legalize SelectionDAG - This stage converts the illegal SelectionDAG to a legal SelectionDAG, by eliminating unsupported operations and data types.
4. Optimize SelectionDAG (#2) - This second run of the SelectionDAG optimized the newly legalized DAG, to eliminate inefficiencies introduced by legalization.
5. Select instructions from DAG - Finally, the target instruction selector matches the DAG operations to target instructions, emitting them and building the MachineFunction being compiled.

After all of these steps are complete, the SelectionDAG is destroyed and the rest of the code generation passes are run.

Initial SelectionDAG Construction

The initial SelectionDAG is naively peephole expanded from the LLVM input by the `SelectionDAGLowering` class in the SelectionDAGISel.cpp file. The intent of this pass is to expose as much low-level, target-specific details to the SelectionDAG as possible. This pass is mostly hard-coded (e.g. an LLVM add turns into an SDNode add while a geteelementptr is expanded into the obvious arithmetic). This pass requires target-specific hooks to lower calls and returns, varargs, etc. For these features, the TargetLowering interface is used.

SelectionDAG Legalize Phase

The Legalize phase is in charge of converting a DAG to only use the types and operations that are natively supported by the target. This involves two major tasks:

1. Convert values of unsupported types to values of supported types.

   There are two main ways of doing this: promoting a small type to a larger type (e.g. f32 -> f64, or i16 -> i32), and breaking up large integer types to smaller ones (e.g. implementing i64 with i32 operations where possible). Type conversions can insert sign and zero extensions as needed to make sure that the final code has the same behavior as the input.

2. Eliminate operations that are not supported by the target in a supported type.

   Targets often have wierd constraints, such as not supporting every operation on every supported datatype (e.g. X86 does not support byte conditional moves). Legalize takes care of either open-coding another sequence of operations to emulate the operation (this is known as expansion), promoting to a larger type that supports the operation (promotion), or using a target-specific hook to implement the legalization.

Instead of using a Legalize pass, we could require that every target-specific selector supports and expands every operator and type even if they are not supported and may require many instructions to implement (in fact, this is the approach taken by the "simple" selectors). However, using a Legalize pass allows all of the cannonicalization patterns to be shared across targets which makes it very easy to optimize the cannonicalized code because it is still in the form of a DAG.

SelectionDAG Optimization Phase

The SelectionDAG optimization phase is run twice for code generation: once immediately after the DAG is built and once after legalization. The first run of the pass allows the initial code to be cleaned up (e.g. performing optimizations that depend on knowing that the operators have restricted type inputs). The second run of the pass cleans up the messy code generated by the Legalize pass, allowing Legalize to be very simple since it can ignore many special cases.

One important class of optimizations that this pass will do in the future is optimizing inserted sign and zero extension instructions. Here are some good papers on the subject:

"Widening integer arithmetic"
Kevin Redwine and Norman Ramsey
International Conference on Compiler Construction (CC) 2004

"Effective sign extension elimination"
Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani
Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design and Implementation.

SelectionDAG Select Phase

The Select phase is the bulk of the target-specific code for instruction selection. This phase takes a legal SelectionDAG as input, and does simple pattern matching on the DAG to generate code. In time, the Select phase will be automatically generated from the target's InstrInfo.td file, which is why we want to make the Select phase as simple and mechanical as possible.

Future directions for the SelectionDAG

1. Optional whole-function selection.
2. Select is a graph translation phase.
3. Place the machine instructions resulting from Select according to register pressure or a schedule.
4. DAG Scheduling.
5. Auto-generate the Select phase from the target description (*.td) files.

SSA-based Machine Code Optimizations

To Be Written

Register Allocation

To Be Written

Prolog/Epilog Code Insertion

To Be Written

Late Machine Code Optimizations

To Be Written

Code Emission
Target description implementations

This section of the document explains features or design decisions that are specific to the code generator for a particular target.

The X86 backend

The X86 code generator lives in the `lib/Target/X86` directory. This code generator currently targets a generic P6-like processor. As such, it produces a few P6-and-above instructions (like conditional moves), but it does not make use of newer features like MMX or SSE. In the future, the X86 backend will have sub-target support added for specific processor families and implementations.

Representing X86 addressing modes in MachineInstrs

The x86 has a very flexible way of accessing memory. It is capable of forming memory addresses of the following expression directly in integer instructions (which use ModR/M addressing):

       Base+[1,2,4,8]*IndexReg+Disp32

In order to represent this, LLVM tracks no less than 4 operands for each memory operand of this form. This means that the "load" form of 'mov' has the following `MachineOperand`s in this order:

    Index:        0     |    1        2       3           4
    Meaning:   DestReg, | BaseReg,  Scale, IndexReg, Displacement
    OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg,   SignExtImm

Stores, and all other instructions, treat the four memory operands in the same way, in the same order.

Instruction naming

An instruction name consists of the base name, a default operand size, and a a character per operand with an optional special size. For example:

`ADD8rr` -> add, 8-bit register, 8-bit register
`IMUL16rmi` -> imul, 16-bit register, 16-bit memory, 16-bit immediate
`IMUL16rmi8` -> imul, 16-bit register, 16-bit memory, 8-bit immediate
`MOVSX32rm16` -> movsx, 32-bit register, 16-bit memory