1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
5 <title>The LLVM Target-Independent Code Generator</title>
6 <link rel="stylesheet" href="llvm.css" type="text/css">
10 <div class="doc_title">
11 The LLVM Target-Independent Code Generator
15 <li><a href="#introduction">Introduction</a>
17 <li><a href="#required">Required components in the code generator</a></li>
18 <li><a href="#high-level-design">The high-level design of the code
20 <li><a href="#tablegen">Using TableGen for target description</a></li>
23 <li><a href="#targetdesc">Target description classes</a>
25 <li><a href="#targetmachine">The <tt>TargetMachine</tt> class</a></li>
26 <li><a href="#targetdata">The <tt>TargetData</tt> class</a></li>
27 <li><a href="#targetlowering">The <tt>TargetLowering</tt> class</a></li>
28 <li><a href="#mregisterinfo">The <tt>MRegisterInfo</tt> class</a></li>
29 <li><a href="#targetinstrinfo">The <tt>TargetInstrInfo</tt> class</a></li>
30 <li><a href="#targetframeinfo">The <tt>TargetFrameInfo</tt> class</a></li>
31 <li><a href="#targetsubtarget">The <tt>TargetSubtarget</tt> class</a></li>
32 <li><a href="#targetjitinfo">The <tt>TargetJITInfo</tt> class</a></li>
35 <li><a href="#codegendesc">Machine code description classes</a>
37 <li><a href="#machineinstr">The <tt>MachineInstr</tt> class</a></li>
38 <li><a href="#machinebasicblock">The <tt>MachineBasicBlock</tt>
40 <li><a href="#machinefunction">The <tt>MachineFunction</tt> class</a></li>
43 <li><a href="#codegenalgs">Target-independent code generation algorithms</a>
45 <li><a href="#instselect">Instruction Selection</a>
47 <li><a href="#selectiondag_intro">Introduction to SelectionDAGs</a></li>
48 <li><a href="#selectiondag_process">SelectionDAG Code Generation
50 <li><a href="#selectiondag_build">Initial SelectionDAG
52 <li><a href="#selectiondag_legalize">SelectionDAG Legalize Phase</a></li>
53 <li><a href="#selectiondag_optimize">SelectionDAG Optimization
54 Phase: the DAG Combiner</a></li>
55 <li><a href="#selectiondag_select">SelectionDAG Select Phase</a></li>
56 <li><a href="#selectiondag_sched">SelectionDAG Scheduling and Formation
58 <li><a href="#selectiondag_future">Future directions for the
61 <li><a href="#codeemit">Code Emission</a>
63 <li><a href="#codeemit_asm">Generating Assembly Code</a></li>
64 <li><a href="#codeemit_bin">Generating Binary Machine Code</a></li>
68 <li><a href="#targetimpls">Target-specific Implementation Notes</a>
70 <li><a href="#x86">The X86 backend</a></li>
76 <div class="doc_author">
77 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
80 <div class="doc_warning">
81 <p>Warning: This is a work in progress.</p>
84 <!-- *********************************************************************** -->
85 <div class="doc_section">
86 <a name="introduction">Introduction</a>
88 <!-- *********************************************************************** -->
90 <div class="doc_text">
92 <p>The LLVM target-independent code generator is a framework that provides a
93 suite of reusable components for translating the LLVM internal representation to
94 the machine code for a specified target -- either in assembly form (suitable for
95 a static compiler) or in binary machine code format (usable for a JIT compiler).
96 The LLVM target-independent code generator consists of five main components:</p>
99 <li><a href="#targetdesc">Abstract target description</a> interfaces which
100 capture important properties about various aspects of the machine, independently
101 of how they will be used. These interfaces are defined in
102 <tt>include/llvm/Target/</tt>.</li>
104 <li>Classes used to represent the <a href="#codegendesc">machine code</a> being
105 generated for a target. These classes are intended to be abstract enough to
106 represent the machine code for <i>any</i> target machine. These classes are
107 defined in <tt>include/llvm/CodeGen/</tt>.</li>
109 <li><a href="#codegenalgs">Target-independent algorithms</a> used to implement
110 various phases of native code generation (register allocation, scheduling, stack
111 frame representation, etc). This code lives in <tt>lib/CodeGen/</tt>.</li>
113 <li><a href="#targetimpls">Implementations of the abstract target description
114 interfaces</a> for particular targets. These machine descriptions make use of
115 the components provided by LLVM, and can optionally provide custom
116 target-specific passes, to build complete code generators for a specific target.
117 Target descriptions live in <tt>lib/Target/</tt>.</li>
119 <li><a href="#jit">The target-independent JIT components</a>. The LLVM JIT is
120 completely target independent (it uses the <tt>TargetJITInfo</tt> structure to
121 interface for target-specific issues. The code for the target-independent
122 JIT lives in <tt>lib/ExecutionEngine/JIT</tt>.</li>
127 Depending on which part of the code generator you are interested in working on,
128 different pieces of this will be useful to you. In any case, you should be
129 familiar with the <a href="#targetdesc">target description</a> and <a
130 href="#codegendesc">machine code representation</a> classes. If you want to add
131 a backend for a new target, you will need to <a href="#targetimpls">implement the
132 target description</a> classes for your new target and understand the <a
133 href="LangRef.html">LLVM code representation</a>. If you are interested in
134 implementing a new <a href="#codegenalgs">code generation algorithm</a>, it
135 should only depend on the target-description and machine code representation
136 classes, ensuring that it is portable.
141 <!-- ======================================================================= -->
142 <div class="doc_subsection">
143 <a name="required">Required components in the code generator</a>
146 <div class="doc_text">
148 <p>The two pieces of the LLVM code generator are the high-level interface to the
149 code generator and the set of reusable components that can be used to build
150 target-specific backends. The two most important interfaces (<a
151 href="#targetmachine"><tt>TargetMachine</tt></a> and <a
152 href="#targetdata"><tt>TargetData</tt></a>) are the only ones that are
153 required to be defined for a backend to fit into the LLVM system, but the others
154 must be defined if the reusable code generator components are going to be
157 <p>This design has two important implications. The first is that LLVM can
158 support completely non-traditional code generation targets. For example, the C
159 backend does not require register allocation, instruction selection, or any of
160 the other standard components provided by the system. As such, it only
161 implements these two interfaces, and does its own thing. Another example of a
162 code generator like this is a (purely hypothetical) backend that converts LLVM
163 to the GCC RTL form and uses GCC to emit machine code for a target.</p>
165 <p>This design also implies that it is possible to design and
166 implement radically different code generators in the LLVM system that do not
167 make use of any of the built-in components. Doing so is not recommended at all,
168 but could be required for radically different targets that do not fit into the
169 LLVM machine description model: programmable FPGAs for example.</p>
171 <p><b>Important Note:</b> For historical reasons, the LLVM SparcV9 code
172 generator uses almost entirely different code paths than described in this
173 document. For this reason, there are some deprecated interfaces (such as
174 <tt>TargetSchedInfo</tt>), which are only used by the
175 V9 backend and should not be used by any other targets. Also, all code in the
176 <tt>lib/Target/SparcV9</tt> directory and subdirectories should be considered
177 deprecated, and should not be used as the basis for future code generator work.
178 The SparcV9 backend is slowly being merged into the rest of the
179 target-independent code generators, but this is a low-priority process with no
180 predictable completion date.</p>
184 <!-- ======================================================================= -->
185 <div class="doc_subsection">
186 <a name="high-level-design">The high-level design of the code generator</a>
189 <div class="doc_text">
191 <p>The LLVM target-independent code generator is designed to support efficient and
192 quality code generation for standard register-based microprocessors. Code
193 generation in this model is divided into the following stages:</p>
196 <li><b><a href="#instselect">Instruction Selection</a></b> - This phase
197 determines an efficient way to express the input LLVM code in the target
199 This stage produces the initial code for the program in the target instruction
200 set, then makes use of virtual registers in SSA form and physical registers that
201 represent any required register assignments due to target constraints or calling
202 conventions. This step turns the LLVM code into a DAG of target
205 <li><b><a href="#selectiondag_sched">Scheduling and Formation</a></b> - This
206 phase takes the DAG of target instructions produced by the instruction selection
207 phase, determines an ordering of the instructions, then emits the instructions
208 as <tt><a href="#machineinstr">MachineInstr</a></tt>s with that ordering. Note
209 that we describe this in the <a href="#instselect">instruction selection
210 section</a> because it operates on a <a
211 href="#selectiondag_intro">SelectionDAG</a>.
214 <li><b><a href="#ssamco">SSA-based Machine Code Optimizations</a></b> - This
215 optional stage consists of a series of machine-code optimizations that
216 operate on the SSA-form produced by the instruction selector. Optimizations
217 like modulo-scheduling or peephole optimization work here.
220 <li><b><a href="#regalloc">Register Allocation</a></b> - The
221 target code is transformed from an infinite virtual register file in SSA form
222 to the concrete register file used by the target. This phase introduces spill
223 code and eliminates all virtual register references from the program.</li>
225 <li><b><a href="#proepicode">Prolog/Epilog Code Insertion</a></b> - Once the
226 machine code has been generated for the function and the amount of stack space
227 required is known (used for LLVM alloca's and spill slots), the prolog and
228 epilog code for the function can be inserted and "abstract stack location
229 references" can be eliminated. This stage is responsible for implementing
230 optimizations like frame-pointer elimination and stack packing.</li>
232 <li><b><a href="#latemco">Late Machine Code Optimizations</a></b> - Optimizations
233 that operate on "final" machine code can go here, such as spill code scheduling
234 and peephole optimizations.</li>
236 <li><b><a href="#codeemit">Code Emission</a></b> - The final stage actually
237 puts out the code for the current function, either in the target assembler
238 format or in machine code.</li>
243 The code generator is based on the assumption that the instruction selector will
244 use an optimal pattern matching selector to create high-quality sequences of
245 native instructions. Alternative code generator designs based on pattern
247 aggressive iterative peephole optimization are much slower. This design
248 permits efficient compilation (important for JIT environments) and
249 aggressive optimization (used when generating code offline) by allowing
250 components of varying levels of sophistication to be used for any step of
254 In addition to these stages, target implementations can insert arbitrary
255 target-specific passes into the flow. For example, the X86 target uses a
256 special pass to handle the 80x87 floating point stack architecture. Other
257 targets with unusual requirements can be supported with custom passes as needed.
263 <!-- ======================================================================= -->
264 <div class="doc_subsection">
265 <a name="tablegen">Using TableGen for target description</a>
268 <div class="doc_text">
270 <p>The target description classes require a detailed description of the target
271 architecture. These target descriptions often have a large amount of common
272 information (e.g., an <tt>add</tt> instruction is almost identical to a
273 <tt>sub</tt> instruction).
274 In order to allow the maximum amount of commonality to be factored out, the LLVM
275 code generator uses the <a href="TableGenFundamentals.html">TableGen</a> tool to
276 describe big chunks of the target machine, which allows the use of
277 domain-specific and target-specific abstractions to reduce the amount of
281 <p>As LLVM continues to be developed and refined, we plan to move more and more
282 of the target description to be in <tt>.td</tt> form. Doing so gives us a
283 number of advantages. The most important is that it makes it easier to port
284 LLVM, because it reduces the amount of C++ code that has to be written and the
285 surface area of the code generator that needs to be understood before someone
286 can get in an get something working. Second, it is also important to us because
287 it makes it easier to change things: in particular, if tables and other things
288 are all emitted by tblgen, we only need to change one place (tblgen) to update
289 all of the targets to a new interface.</p>
293 <!-- *********************************************************************** -->
294 <div class="doc_section">
295 <a name="targetdesc">Target description classes</a>
297 <!-- *********************************************************************** -->
299 <div class="doc_text">
301 <p>The LLVM target description classes (which are located in the
302 <tt>include/llvm/Target</tt> directory) provide an abstract description of the
303 target machine; independent of any particular client. These classes are
304 designed to capture the <i>abstract</i> properties of the target (such as the
305 instructions and registers it has), and do not incorporate any particular pieces
306 of code generation algorithms.</p>
308 <p>All of the target description classes (except the <tt><a
309 href="#targetdata">TargetData</a></tt> class) are designed to be subclassed by
310 the concrete target implementation, and have virtual methods implemented. To
311 get to these implementations, the <tt><a
312 href="#targetmachine">TargetMachine</a></tt> class provides accessors that
313 should be implemented by the target.</p>
317 <!-- ======================================================================= -->
318 <div class="doc_subsection">
319 <a name="targetmachine">The <tt>TargetMachine</tt> class</a>
322 <div class="doc_text">
324 <p>The <tt>TargetMachine</tt> class provides virtual methods that are used to
325 access the target-specific implementations of the various target description
326 classes via the <tt>get*Info</tt> methods (<tt>getInstrInfo</tt>,
327 <tt>getRegisterInfo</tt>, <tt>getFrameInfo</tt>, etc.). This class is
328 designed to be specialized by
329 a concrete target implementation (e.g., <tt>X86TargetMachine</tt>) which
330 implements the various virtual methods. The only required target description
331 class is the <a href="#targetdata"><tt>TargetData</tt></a> class, but if the
332 code generator components are to be used, the other interfaces should be
333 implemented as well.</p>
338 <!-- ======================================================================= -->
339 <div class="doc_subsection">
340 <a name="targetdata">The <tt>TargetData</tt> class</a>
343 <div class="doc_text">
345 <p>The <tt>TargetData</tt> class is the only required target description class,
346 and it is the only class that is not extensible (you cannot derived a new
347 class from it). <tt>TargetData</tt> specifies information about how the target
348 lays out memory for structures, the alignment requirements for various data
349 types, the size of pointers in the target, and whether the target is
350 little-endian or big-endian.</p>
354 <!-- ======================================================================= -->
355 <div class="doc_subsection">
356 <a name="targetlowering">The <tt>TargetLowering</tt> class</a>
359 <div class="doc_text">
361 <p>The <tt>TargetLowering</tt> class is used by SelectionDAG based instruction
362 selectors primarily to describe how LLVM code should be lowered to SelectionDAG
363 operations. Among other things, this class indicates:
364 <ul><li>an initial register class to use for various ValueTypes</li>
365 <li>which operations are natively supported by the target machine</li>
366 <li>the return type of setcc operations</li>
367 <li>the type to use for shift amounts</li>
368 <li>various high-level characteristics, like whether it is profitable to turn
369 division by a constant into a multiplication sequence</li>
374 <!-- ======================================================================= -->
375 <div class="doc_subsection">
376 <a name="mregisterinfo">The <tt>MRegisterInfo</tt> class</a>
379 <div class="doc_text">
381 <p>The <tt>MRegisterInfo</tt> class (which will eventually be renamed to
382 <tt>TargetRegisterInfo</tt>) is used to describe the register file of the
383 target and any interactions between the registers.</p>
385 <p>Registers in the code generator are represented in the code generator by
386 unsigned numbers. Physical registers (those that actually exist in the target
387 description) are unique small numbers, and virtual registers are generally
388 large. Note that register #0 is reserved as a flag value.</p>
390 <p>Each register in the processor description has an associated
391 <tt>TargetRegisterDesc</tt> entry, which provides a textual name for the register
392 (used for assembly output and debugging dumps) and a set of aliases (used to
393 indicate that one register overlaps with another).
396 <p>In addition to the per-register description, the <tt>MRegisterInfo</tt> class
397 exposes a set of processor specific register classes (instances of the
398 <tt>TargetRegisterClass</tt> class). Each register class contains sets of
399 registers that have the same properties (for example, they are all 32-bit
400 integer registers). Each SSA virtual register created by the instruction
401 selector has an associated register class. When the register allocator runs, it
402 replaces virtual registers with a physical register in the set.</p>
405 The target-specific implementations of these classes is auto-generated from a <a
406 href="TableGenFundamentals.html">TableGen</a> description of the register file.
411 <!-- ======================================================================= -->
412 <div class="doc_subsection">
413 <a name="targetinstrinfo">The <tt>TargetInstrInfo</tt> class</a>
416 <div class="doc_text">
417 <p>The <tt>TargetInstrInfo</tt> class is used to describe the machine
418 instructions supported by the target. It is essentially an array of
419 <tt>TargetInstrDescriptor</tt> objects, each of which describes one
420 instruction the target supports. Descriptors define things like the mnemonic
421 for the opcode, the number of operands, the list of implicit register uses
422 and defs, whether the instruction has certain target-independent properties
423 (accesses memory, is commutable, etc), and holds any target-specific flags.</p>
426 <!-- ======================================================================= -->
427 <div class="doc_subsection">
428 <a name="targetframeinfo">The <tt>TargetFrameInfo</tt> class</a>
431 <div class="doc_text">
432 <p>The <tt>TargetFrameInfo</tt> class is used to provide information about the
433 stack frame layout of the target. It holds the direction of stack growth,
434 the known stack alignment on entry to each function, and the offset to the
435 locals area. The offset to the local area is the offset from the stack
436 pointer on function entry to the first location where function data (local
437 variables, spill locations) can be stored.</p>
440 <!-- ======================================================================= -->
441 <div class="doc_subsection">
442 <a name="targetsubtarget">The <tt>TargetSubtarget</tt> class</a>
445 <div class="doc_text">
452 <!-- ======================================================================= -->
453 <div class="doc_subsection">
454 <a name="targetjitinfo">The <tt>TargetJITInfo</tt> class</a>
457 <!-- *********************************************************************** -->
458 <div class="doc_section">
459 <a name="codegendesc">Machine code description classes</a>
461 <!-- *********************************************************************** -->
463 <div class="doc_text">
466 At the high-level, LLVM code is translated to a machine specific representation
467 formed out of <a href="#machinefunction">MachineFunction</a>,
468 <a href="#machinebasicblock">MachineBasicBlock</a>, and <a
469 href="#machineinstr"><tt>MachineInstr</tt></a> instances
470 (defined in include/llvm/CodeGen). This representation is completely target
471 agnostic, representing instructions in their most abstract form: an opcode and a
472 series of operands. This representation is designed to support both SSA
473 representation for machine code, as well as a register allocated, non-SSA form.
478 <!-- ======================================================================= -->
479 <div class="doc_subsection">
480 <a name="machineinstr">The <tt>MachineInstr</tt> class</a>
483 <div class="doc_text">
485 <p>Target machine instructions are represented as instances of the
486 <tt>MachineInstr</tt> class. This class is an extremely abstract way of
487 representing machine instructions. In particular, it only keeps track of
488 an opcode number and a set of operands.</p>
490 <p>The opcode number is a simple unsigned number that only has meaning to a
491 specific backend. All of the instructions for a target should be defined in
492 the <tt>*InstrInfo.td</tt> file for the target. The opcode enum values
493 are auto-generated from this description. The <tt>MachineInstr</tt> class does
494 not have any information about how to interpret the instruction (i.e., what the
495 semantics of the instruction are): for that you must refer to the
496 <tt><a href="#targetinstrinfo">TargetInstrInfo</a></tt> class.</p>
498 <p>The operands of a machine instruction can be of several different types:
499 they can be a register reference, constant integer, basic block reference, etc.
500 In addition, a machine operand should be marked as a def or a use of the value
501 (though only registers are allowed to be defs).</p>
503 <p>By convention, the LLVM code generator orders instruction operands so that
504 all register definitions come before the register uses, even on architectures
505 that are normally printed in other orders. For example, the SPARC add
506 instruction: "<tt>add %i1, %i2, %i3</tt>" adds the "%i1", and "%i2" registers
507 and stores the result into the "%i3" register. In the LLVM code generator,
508 the operands should be stored as "<tt>%i3, %i1, %i2</tt>": with the destination
511 <p>Keeping destination (definition) operands at the beginning of the operand
512 list has several advantages. In particular, the debugging printer will print
513 the instruction like this:</p>
519 <p>If the first operand is a def, and it is also easier to <a
520 href="#buildmi">create instructions</a> whose only def is the first
525 <!-- _______________________________________________________________________ -->
526 <div class="doc_subsubsection">
527 <a name="buildmi">Using the <tt>MachineInstrBuilder.h</tt> functions</a>
530 <div class="doc_text">
532 <p>Machine instructions are created by using the <tt>BuildMI</tt> functions,
533 located in the <tt>include/llvm/CodeGen/MachineInstrBuilder.h</tt> file. The
534 <tt>BuildMI</tt> functions make it easy to build arbitrary machine
535 instructions. Usage of the <tt>BuildMI</tt> functions look like this:
539 // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
540 // instruction. The '1' specifies how many operands will be added.
541 MachineInstr *MI = BuildMI(X86::MOV32ri, 1, DestReg).addImm(42);
543 // Create the same instr, but insert it at the end of a basic block.
544 MachineBasicBlock &MBB = ...
545 BuildMI(MBB, X86::MOV32ri, 1, DestReg).addImm(42);
547 // Create the same instr, but insert it before a specified iterator point.
548 MachineBasicBlock::iterator MBBI = ...
549 BuildMI(MBB, MBBI, X86::MOV32ri, 1, DestReg).addImm(42);
551 // Create a 'cmp Reg, 0' instruction, no destination reg.
552 MI = BuildMI(X86::CMP32ri, 2).addReg(Reg).addImm(0);
553 // Create an 'sahf' instruction which takes no operands and stores nothing.
554 MI = BuildMI(X86::SAHF, 0);
556 // Create a self looping branch instruction.
557 BuildMI(MBB, X86::JNE, 1).addMBB(&MBB);
561 The key thing to remember with the <tt>BuildMI</tt> functions is that you have
562 to specify the number of operands that the machine instruction will take. This
563 allows for efficient memory allocation. You also need to specify if operands
564 default to be uses of values, not definitions. If you need to add a definition
565 operand (other than the optional destination register), you must explicitly
571 <!-- _______________________________________________________________________ -->
572 <div class="doc_subsubsection">
573 <a name="fixedregs">Fixed (preassigned) registers</a>
576 <div class="doc_text">
578 <p>One important issue that the code generator needs to be aware of is the
579 presence of fixed registers. In particular, there are often places in the
580 instruction stream where the register allocator <em>must</em> arrange for a
581 particular value to be in a particular register. This can occur due to
582 limitations of the instruction set (e.g., the X86 can only do a 32-bit divide
583 with the <tt>EAX</tt>/<tt>EDX</tt> registers), or external factors like calling
584 conventions. In any case, the instruction selector should emit code that
585 copies a virtual register into or out of a physical register when needed.</p>
587 <p>For example, consider this simple LLVM example:</p>
590 int %test(int %X, int %Y) {
596 <p>The X86 instruction selector produces this machine code for the div
598 "<tt>llc X.bc -march=x86 -print-machineinstrs</tt>" to get this):</p>
602 %EAX = mov %reg1024 ;; Copy X (in reg1024) into EAX
603 %reg1027 = sar %reg1024, 31
604 %EDX = mov %reg1027 ;; Sign extend X into EDX
605 idiv %reg1025 ;; Divide by Y (in reg1025)
606 %reg1026 = mov %EAX ;; Read the result (Z) out of EAX
609 %EAX = mov %reg1026 ;; 32-bit return value goes in EAX
613 <p>By the end of code generation, the register allocator has coalesced
614 the registers and deleted the resultant identity moves, producing the
618 ;; X is in EAX, Y is in ECX
625 <p>This approach is extremely general (if it can handle the X86 architecture,
626 it can handle anything!) and allows all of the target specific
627 knowledge about the instruction stream to be isolated in the instruction
628 selector. Note that physical registers should have a short lifetime for good
629 code generation, and all physical registers are assumed dead on entry and
630 exit of basic blocks (before register allocation). Thus if you need a value
631 to be live across basic block boundaries, it <em>must</em> live in a virtual
636 <!-- _______________________________________________________________________ -->
637 <div class="doc_subsubsection">
638 <a name="ssa">Machine code SSA form</a>
641 <div class="doc_text">
643 <p><tt>MachineInstr</tt>'s are initially selected in SSA-form, and
644 are maintained in SSA-form until register allocation happens. For the most
645 part, this is trivially simple since LLVM is already in SSA form: LLVM PHI nodes
646 become machine code PHI nodes, and virtual registers are only allowed to have a
647 single definition.</p>
649 <p>After register allocation, machine code is no longer in SSA-form, as there
650 are no virtual registers left in the code.</p>
654 <!-- ======================================================================= -->
655 <div class="doc_subsection">
656 <a name="machinebasicblock">The <tt>MachineBasicBlock</tt> class</a>
659 <div class="doc_text">
661 <p>The <tt>MachineBasicBlock</tt> class contains a list of machine instructions
662 (<a href="#machineinstr">MachineInstr</a> instances). It roughly corresponds to
663 the LLVM code input to the instruction selector, but there can be a one-to-many
664 mapping (i.e. one LLVM basic block can map to multiple machine basic blocks).
665 The MachineBasicBlock class has a "<tt>getBasicBlock</tt>" method, which returns
666 the LLVM basic block that it comes from.
671 <!-- ======================================================================= -->
672 <div class="doc_subsection">
673 <a name="machinefunction">The <tt>MachineFunction</tt> class</a>
676 <div class="doc_text">
678 <p>The <tt>MachineFunction</tt> class contains a list of machine basic blocks
679 (<a href="#machinebasicblock">MachineBasicBlock</a> instances). It corresponds
680 one-to-one with the LLVM function input to the instruction selector. In
681 addition to a list of basic blocks, the <tt>MachineFunction</tt> contains a
682 the MachineConstantPool, MachineFrameInfo, MachineFunctionInfo,
683 SSARegMap, and a set of live in and live out registers for the function. See
684 <tt>MachineFunction.h</tt> for more information.
691 <!-- *********************************************************************** -->
692 <div class="doc_section">
693 <a name="codegenalgs">Target-independent code generation algorithms</a>
695 <!-- *********************************************************************** -->
697 <div class="doc_text">
699 <p>This section documents the phases described in the <a
700 href="#high-level-design">high-level design of the code generator</a>. It
701 explains how they work and some of the rationale behind their design.</p>
705 <!-- ======================================================================= -->
706 <div class="doc_subsection">
707 <a name="instselect">Instruction Selection</a>
710 <div class="doc_text">
712 Instruction Selection is the process of translating LLVM code presented to the
713 code generator into target-specific machine instructions. There are several
714 well-known ways to do this in the literature. In LLVM there are two main forms:
715 the SelectionDAG based instruction selector framework and an old-style 'simple'
716 instruction selector (which effectively peephole selects each LLVM instruction
717 into a series of machine instructions). We recommend that all targets use the
718 SelectionDAG infrastructure.
721 <p>Portions of the DAG instruction selector are generated from the target
722 description files (<tt>*.td</tt>) files. Eventually, we aim for the entire
723 instruction selector to be generated from these <tt>.td</tt> files.</p>
726 <!-- _______________________________________________________________________ -->
727 <div class="doc_subsubsection">
728 <a name="selectiondag_intro">Introduction to SelectionDAGs</a>
731 <div class="doc_text">
734 The SelectionDAG provides an abstraction for code representation in a way that
735 is amenable to instruction selection using automatic techniques
736 (e.g. dynamic-programming based optimal pattern matching selectors), It is also
737 well suited to other phases of code generation; in particular,
738 instruction scheduling (SelectionDAG's are very close to scheduling DAGs
739 post-selection). Additionally, the SelectionDAG provides a host representation
740 where a large variety of very-low-level (but target-independent)
741 <a href="#selectiondag_optimize">optimizations</a> may be
742 performed: ones which require extensive information about the instructions
743 efficiently supported by the target.
747 The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the
748 <tt>SDNode</tt> class. The primary payload of the <tt>SDNode</tt> is its
749 operation code (Opcode) that indicates what operation the node performs and
750 the operands to the operation.
751 The various operation node types are described at the top of the
752 <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt> file.</p>
754 <p>Although most operations define a single value, each node in the graph may
755 define multiple values. For example, a combined div/rem operation will define
756 both the dividend and the remainder. Many other situations require multiple
757 values as well. Each node also has some number of operands, which are edges
758 to the node defining the used value. Because nodes may define multiple values,
759 edges are represented by instances of the <tt>SDOperand</tt> class, which is
760 a <SDNode, unsigned> pair, indicating the node and result
761 value being used, respectively. Each value produced by an SDNode has an
762 associated MVT::ValueType, indicating what type the value is.
766 SelectionDAGs contain two different kinds of values: those that represent data
767 flow and those that represent control flow dependencies. Data values are simple
768 edges with an integer or floating point value type. Control edges are
769 represented as "chain" edges which are of type MVT::Other. These edges provide
770 an ordering between nodes that have side effects (such as
771 loads/stores/calls/return/etc). All nodes that have side effects should take a
772 token chain as input and produce a new one as output. By convention, token
773 chain inputs are always operand #0, and chain results are always the last
774 value produced by an operation.</p>
777 A SelectionDAG has designated "Entry" and "Root" nodes. The Entry node is
778 always a marker node with an Opcode of ISD::EntryToken. The Root node is the
779 final side-effecting node in the token chain. For example, in a single basic
780 block function, this would be the return node.
784 One important concept for SelectionDAGs is the notion of a "legal" vs. "illegal"
785 DAG. A legal DAG for a target is one that only uses supported operations and
786 supported types. On a 32-bit PowerPC, for example, a DAG with any values of i1,
788 or i64 type would be illegal, as would a DAG that uses a SREM or UREM operation.
789 The <a href="#selectiondag_legalize">legalize</a>
790 phase is responsible for turning an illegal DAG into a legal DAG.
794 <!-- _______________________________________________________________________ -->
795 <div class="doc_subsubsection">
796 <a name="selectiondag_process">SelectionDAG Instruction Selection Process</a>
799 <div class="doc_text">
802 SelectionDAG-based instruction selection consists of the following steps:
806 <li><a href="#selectiondag_build">Build initial DAG</a> - This stage performs
807 a simple translation from the input LLVM code to an illegal SelectionDAG.
809 <li><a href="#selectiondag_optimize">Optimize SelectionDAG</a> - This stage
810 performs simple optimizations on the SelectionDAG to simplify it and
811 recognize meta instructions (like rotates and div/rem pairs) for
812 targets that support these meta operations. This makes the resultant code
813 more efficient and the 'select instructions from DAG' phase (below) simpler.
815 <li><a href="#selectiondag_legalize">Legalize SelectionDAG</a> - This stage
816 converts the illegal SelectionDAG to a legal SelectionDAG, by eliminating
817 unsupported operations and data types.</li>
818 <li><a href="#selectiondag_optimize">Optimize SelectionDAG (#2)</a> - This
819 second run of the SelectionDAG optimized the newly legalized DAG, to
820 eliminate inefficiencies introduced by legalization.</li>
821 <li><a href="#selectiondag_select">Select instructions from DAG</a> - Finally,
822 the target instruction selector matches the DAG operations to target
823 instructions. This process translates the target-independent input DAG into
824 another DAG of target instructions.</li>
825 <li><a href="#selectiondag_sched">SelectionDAG Scheduling and Formation</a>
826 - The last phase assigns a linear order to the instructions in the
827 target-instruction DAG and emits them into the MachineFunction being
828 compiled. This step uses traditional prepass scheduling techniques.</li>
831 <p>After all of these steps are complete, the SelectionDAG is destroyed and the
832 rest of the code generation passes are run.</p>
834 <p>One great way to visualize what is going on here is to take advantage of a
835 few LLC command line options. In particular, the <tt>-view-isel-dags</tt>
836 option pops up a window with the SelectionDAG input to the Select phase for all
837 of the code compiled (if you only get errors printed to the console while using
838 this, you probably <a href="ProgrammersManual.html#ViewGraph">need to configure
839 your system</a> to add support for it). The <tt>-view-sched-dags</tt> option
840 views the SelectionDAG output from the Select phase and input to the Scheduler
845 <!-- _______________________________________________________________________ -->
846 <div class="doc_subsubsection">
847 <a name="selectiondag_build">Initial SelectionDAG Construction</a>
850 <div class="doc_text">
853 The initial SelectionDAG is naively peephole expanded from the LLVM input by
854 the <tt>SelectionDAGLowering</tt> class in the SelectionDAGISel.cpp file. The
855 intent of this pass is to expose as much low-level, target-specific details
856 to the SelectionDAG as possible. This pass is mostly hard-coded (e.g. an LLVM
857 add turns into an SDNode add while a geteelementptr is expanded into the obvious
858 arithmetic). This pass requires target-specific hooks to lower calls and
859 returns, varargs, etc. For these features, the <a
860 href="#targetlowering">TargetLowering</a> interface is
866 <!-- _______________________________________________________________________ -->
867 <div class="doc_subsubsection">
868 <a name="selectiondag_legalize">SelectionDAG Legalize Phase</a>
871 <div class="doc_text">
873 <p>The Legalize phase is in charge of converting a DAG to only use the types and
874 operations that are natively supported by the target. This involves two major
878 <li><p>Convert values of unsupported types to values of supported types.</p>
879 <p>There are two main ways of doing this: converting small types to
880 larger types ("promoting"), and breaking up large integer types
881 into smaller ones ("expanding"). For example, a target might require
882 that all f32 values are promoted to f64 and that all i1/i8/i16 values
883 are promoted to i32. The same target might require that all i64 values
884 be expanded into i32 values. These changes can insert sign and zero
886 needed to make sure that the final code has the same behavior as the
888 <p>A target implementation tells the legalizer which types are supported
889 (and which register class to use for them) by calling the
890 "addRegisterClass" method in its TargetLowering constructor.</p>
893 <li><p>Eliminate operations that are not supported by the target.</p>
894 <p>Targets often have weird constraints, such as not supporting every
895 operation on every supported datatype (e.g. X86 does not support byte
896 conditional moves and PowerPC does not support sign-extending loads from
897 a 16-bit memory location). Legalize takes care by open-coding
898 another sequence of operations to emulate the operation ("expansion"), by
899 promoting to a larger type that supports the operation
900 (promotion), or using a target-specific hook to implement the
901 legalization (custom).</p>
902 <p>A target implementation tells the legalizer which operations are not
903 supported (and which of the above three actions to take) by calling the
904 "setOperationAction" method in its TargetLowering constructor.</p>
909 Prior to the existance of the Legalize pass, we required that every
910 target <a href="#selectiondag_optimize">selector</a> supported and handled every
911 operator and type even if they are not natively supported. The introduction of
912 the Legalize phase allows all of the
913 cannonicalization patterns to be shared across targets, and makes it very
914 easy to optimize the cannonicalized code because it is still in the form of
920 <!-- _______________________________________________________________________ -->
921 <div class="doc_subsubsection">
922 <a name="selectiondag_optimize">SelectionDAG Optimization Phase: the DAG
926 <div class="doc_text">
929 The SelectionDAG optimization phase is run twice for code generation: once
930 immediately after the DAG is built and once after legalization. The first run
931 of the pass allows the initial code to be cleaned up (e.g. performing
932 optimizations that depend on knowing that the operators have restricted type
933 inputs). The second run of the pass cleans up the messy code generated by the
934 Legalize pass, which allows Legalize to be very simple (it can focus on making
935 code legal instead of focusing on generating <i>good</i> and legal code).
939 One important class of optimizations performed is optimizing inserted sign and
940 zero extension instructions. We currently use ad-hoc techniques, but could move
941 to more rigorous techniques in the future. Here are some good
942 papers on the subject:</p>
945 "<a href="http://www.eecs.harvard.edu/~nr/pubs/widen-abstract.html">Widening
946 integer arithmetic</a>"<br>
947 Kevin Redwine and Norman Ramsey<br>
948 International Conference on Compiler Construction (CC) 2004
953 "<a href="http://portal.acm.org/citation.cfm?doid=512529.512552">Effective
954 sign extension elimination</a>"<br>
955 Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani<br>
956 Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design
962 <!-- _______________________________________________________________________ -->
963 <div class="doc_subsubsection">
964 <a name="selectiondag_select">SelectionDAG Select Phase</a>
967 <div class="doc_text">
969 <p>The Select phase is the bulk of the target-specific code for instruction
970 selection. This phase takes a legal SelectionDAG as input,
971 pattern matches the instructions supported by the target to this DAG, and
972 produces a new DAG of target code. For example, consider the following LLVM
976 %t1 = add float %W, %X
977 %t2 = mul float %t1, %Y
978 %t3 = add float %t2, %Z
981 <p>This LLVM code corresponds to a SelectionDAG that looks basically like this:
985 (fadd:f32 (fmul:f32 (fadd:f32 W, X), Y), Z)
988 <p>If a target supports floating pointer multiply-and-add (FMA) operations, one
989 of the adds can be merged with the multiply. On the PowerPC, for example, the
990 output of the instruction selector might look like this DAG:</p>
993 (FMADDS (FADDS W, X), Y, Z)
997 The FMADDS instruction is a ternary instruction that multiplies its first two
998 operands and adds the third (as single-precision floating-point numbers). The
999 FADDS instruction is a simple binary single-precision add instruction. To
1000 perform this pattern match, the PowerPC backend includes the following
1001 instruction definitions:
1005 def FMADDS : AForm_1<59, 29,
1006 (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRC, F4RC:$FRB),
1007 "fmadds $FRT, $FRA, $FRC, $FRB",
1008 [<b>(set F4RC:$FRT, (fadd (fmul F4RC:$FRA, F4RC:$FRC),
1009 F4RC:$FRB))</b>]>;
1010 def FADDS : AForm_2<59, 21,
1011 (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRB),
1012 "fadds $FRT, $FRA, $FRB",
1013 [<b>(set F4RC:$FRT, (fadd F4RC:$FRA, F4RC:$FRB))</b>]>;
1016 <p>The portion of the instruction definition in bold indicates the pattern used
1017 to match the instruction. The DAG operators (like <tt>fmul</tt>/<tt>fadd</tt>)
1018 are defined in the <tt>lib/Target/TargetSelectionDAG.td</tt> file.
1019 "<tt>F4RC</tt>" is the register class of the input and result values.<p>
1021 <p>The TableGen DAG instruction selector generator reads the instruction
1022 patterns in the .td and automatically builds parts of the pattern matching code
1023 for your target. It has the following strengths:</p>
1026 <li>At compiler-compiler time, it analyzes your instruction patterns and tells
1027 you if your patterns make sense or not.</li>
1028 <li>It can handle arbitrary constraints on operands for the pattern match. In
1029 particular, it is straight-forward to say things like "match any immediate
1030 that is a 13-bit sign-extended value". For examples, see the
1031 <tt>immSExt16</tt> and related tblgen classes in the PowerPC backend.</li>
1032 <li>It knows several important identities for the patterns defined. For
1033 example, it knows that addition is commutative, so it allows the
1034 <tt>FMADDS</tt> pattern above to match "<tt>(fadd X, (fmul Y, Z))</tt>" as
1035 well as "<tt>(fadd (fmul X, Y), Z)</tt>", without the target author having
1036 to specially handle this case.</li>
1037 <li>It has a full-featured type-inferencing system. In particular, you should
1038 rarely have to explicitly tell the system what type parts of your patterns
1039 are. In the FMADDS case above, we didn't have to tell tblgen that all of
1040 the nodes in the pattern are of type 'f32'. It was able to infer and
1041 propagate this knowledge from the fact that F4RC has type 'f32'.</li>
1042 <li>Targets can define their own (and rely on built-in) "pattern fragments".
1043 Pattern fragments are chunks of reusable patterns that get inlined into your
1044 patterns during compiler-compiler time. For example, the integer "(not x)"
1045 operation is actually defined as a pattern fragment that expands as
1046 "(xor x, -1)", since the SelectionDAG does not have a native 'not'
1047 operation. Targets can define their own short-hand fragments as they see
1048 fit. See the definition of 'not' and 'ineg' for examples.</li>
1049 <li>In addition to instructions, targets can specify arbitrary patterns that
1050 map to one or more instructions, using the 'Pat' class. For example,
1051 the PowerPC has no way to load an arbitrary integer immediate into a
1052 register in one instruction. To tell tblgen how to do this, it defines:
1055 // Arbitrary immediate support. Implement in terms of LIS/ORI.
1056 def : Pat<(i32 imm:$imm),
1057 (ORI (LIS (HI16 imm:$imm)), (LO16 imm:$imm))>;
1060 If none of the single-instruction patterns for loading an immediate into a
1061 register match, this will be used. This rule says "match an arbitrary i32
1062 immediate, turning it into an ORI ('or a 16-bit immediate') and an LIS
1063 ('load 16-bit immediate, where the immediate is shifted to the left 16
1064 bits') instruction". To make this work, the LO16/HI16 node transformations
1065 are used to manipulate the input immediate (in this case, take the high or
1066 low 16-bits of the immediate).
1068 <li>While the system does automate a lot, it still allows you to write custom
1069 C++ code to match special cases, in case there is something that is hard
1074 While it has many strengths, the system currently has some limitations,
1075 primarily because it is a work in progress and is not yet finished:
1079 <li>Overall, there is no way to define or match SelectionDAG nodes that define
1080 multiple values (e.g. ADD_PARTS, LOAD, CALL, etc). This is the biggest
1081 reason that you currently still <i>have to</i> write custom C++ code for
1082 your instruction selector.</li>
1083 <li>There is no great way to support match complex addressing modes yet. In the
1084 future, we will extend pattern fragments to allow them to define multiple
1085 values (e.g. the four operands of the <a href="#x86_memory">X86 addressing
1086 mode</a>). In addition, we'll extend fragments so that a fragment can match
1087 multiple different patterns.</li>
1088 <li>We don't automatically infer flags like isStore/isLoad yet.</li>
1089 <li>We don't automatically generate the set of supported registers and
1090 operations for the <a href="#"selectiondag_legalize>Legalizer</a> yet.</li>
1091 <li>We don't have a way of tying in custom legalized nodes yet.</li>
1094 <p>Despite these limitations, the instruction selector generator is still quite
1095 useful for most of the binary and logical operations in typical instruction
1096 sets. If you run into any problems or can't figure out how to do something,
1097 please let Chris know!</p>
1101 <!-- _______________________________________________________________________ -->
1102 <div class="doc_subsubsection">
1103 <a name="selectiondag_sched">SelectionDAG Scheduling and Formation Phase</a>
1106 <div class="doc_text">
1108 <p>The scheduling phase takes the DAG of target instructions from the selection
1109 phase and assigns an order. The scheduler can pick an order depending on
1110 various constraints of the machines (i.e. order for minimal register pressure or
1111 try to cover instruction latencies). Once an order is established, the DAG is
1112 converted to a list of <a href="#machineinstr">MachineInstr</a>s and the
1113 Selection DAG is destroyed.
1116 <p>Note that this phase is logically seperate from the instruction selection
1117 phase, but is tied to it closely in the code because it operates on
1122 <!-- _______________________________________________________________________ -->
1123 <div class="doc_subsubsection">
1124 <a name="selectiondag_future">Future directions for the SelectionDAG</a>
1127 <div class="doc_text">
1130 <li>Optional function-at-a-time selection.</li>
1131 <li>Auto-generate entire selector from .td file.</li>
1137 <!-- ======================================================================= -->
1138 <div class="doc_subsection">
1139 <a name="ssamco">SSA-based Machine Code Optimizations</a>
1141 <div class="doc_text"><p>To Be Written</p></div>
1142 <!-- ======================================================================= -->
1143 <div class="doc_subsection">
1144 <a name="regalloc">Register Allocation</a>
1146 <div class="doc_text"><p>To Be Written</p></div>
1147 <!-- ======================================================================= -->
1148 <div class="doc_subsection">
1149 <a name="proepicode">Prolog/Epilog Code Insertion</a>
1151 <div class="doc_text"><p>To Be Written</p></div>
1152 <!-- ======================================================================= -->
1153 <div class="doc_subsection">
1154 <a name="latemco">Late Machine Code Optimizations</a>
1156 <div class="doc_text"><p>To Be Written</p></div>
1157 <!-- ======================================================================= -->
1158 <div class="doc_subsection">
1159 <a name="codeemit">Code Emission</a>
1163 <!-- _______________________________________________________________________ -->
1164 <div class="doc_subsubsection">
1165 <a name="codeemit_asm">Generating Assembly Code</a>
1168 <div class="doc_text">
1173 <!-- _______________________________________________________________________ -->
1174 <div class="doc_subsubsection">
1175 <a name="codeemit_bin">Generating Binary Machine Code</a>
1178 <div class="doc_text">
1179 <p>For the JIT or .o file writer</p>
1183 <!-- *********************************************************************** -->
1184 <div class="doc_section">
1185 <a name="targetimpls">Target-specific Implementation Notes</a>
1187 <!-- *********************************************************************** -->
1189 <div class="doc_text">
1191 <p>This section of the document explains features or design decisions that
1192 are specific to the code generator for a particular target.</p>
1197 <!-- ======================================================================= -->
1198 <div class="doc_subsection">
1199 <a name="x86">The X86 backend</a>
1202 <div class="doc_text">
1205 The X86 code generator lives in the <tt>lib/Target/X86</tt> directory. This
1206 code generator currently targets a generic P6-like processor. As such, it
1207 produces a few P6-and-above instructions (like conditional moves), but it does
1208 not make use of newer features like MMX or SSE. In the future, the X86 backend
1209 will have sub-target support added for specific processor families and
1210 implementations.</p>
1214 <!-- _______________________________________________________________________ -->
1215 <div class="doc_subsubsection">
1216 <a name="x86_tt">X86 Target Triples Supported</a>
1219 <div class="doc_text">
1221 The following are the known target triples that are supported by the X86
1222 backend. This is not an exhaustive list, but it would be useful to add those
1227 <li><b>i686-pc-linux-gnu</b> - Linux</li>
1228 <li><b>i386-unknown-freebsd5.3</b> - FreeBSD 5.3</li>
1229 <li><b>i686-pc-cygwin</b> - Cygwin on Win32</li>
1230 <li><b>i686-pc-mingw32</b> - MingW on Win32</li>
1231 <li><b>i686-apple-darwin*</b> - Apple Darwin on X86</li>
1236 <!-- _______________________________________________________________________ -->
1237 <div class="doc_subsubsection">
1238 <a name="x86_memory">Representing X86 addressing modes in MachineInstrs</a>
1241 <div class="doc_text">
1243 <p>The x86 has a very flexible way of accessing memory. It is capable of
1244 forming memory addresses of the following expression directly in integer
1245 instructions (which use ModR/M addressing):</p>
1248 Base+[1,2,4,8]*IndexReg+Disp32
1251 <p>In order to represent this, LLVM tracks no less than 4 operands for each
1252 memory operand of this form. This means that the "load" form of 'mov' has the
1253 following <tt>MachineOperand</tt>s in this order:</p>
1257 Meaning: DestReg, | BaseReg, Scale, IndexReg, Displacement
1258 OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg, SignExtImm
1261 <p>Stores, and all other instructions, treat the four memory operands in the
1262 same way, in the same order.</p>
1266 <!-- _______________________________________________________________________ -->
1267 <div class="doc_subsubsection">
1268 <a name="x86_names">Instruction naming</a>
1271 <div class="doc_text">
1274 An instruction name consists of the base name, a default operand size, and a
1275 a character per operand with an optional special size. For example:</p>
1278 <tt>ADD8rr</tt> -> add, 8-bit register, 8-bit register<br>
1279 <tt>IMUL16rmi</tt> -> imul, 16-bit register, 16-bit memory, 16-bit immediate<br>
1280 <tt>IMUL16rmi8</tt> -> imul, 16-bit register, 16-bit memory, 8-bit immediate<br>
1281 <tt>MOVSX32rm16</tt> -> movsx, 32-bit register, 16-bit memory
1286 <!-- *********************************************************************** -->
1289 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1290 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1291 <a href="http://validator.w3.org/check/referer"><img
1292 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /></a>
1294 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1295 <a href="http://llvm.cs.uiuc.edu">The LLVM Compiler Infrastructure</a><br>
1296 Last modified: $Date$