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
62 <li><a href="#regalloc">Register Allocation</a>
64 <li><a href="#regAlloc_represent">How registers are represented in
66 <li><a href="#regAlloc_howTo">Mapping virtual registers to physical
68 <li><a href="#regAlloc_twoAddr">Handling two address instructions</a></li>
69 <li><a href="#regAlloc_ssaDecon">The SSA deconstruction phase</a></li>
70 <li><a href="#regAlloc_fold">Instruction folding</a></li>
71 <li><a href="#regAlloc_builtIn">Built in register allocators</a></li>
73 <li><a href="#codeemit">Code Emission</a>
75 <li><a href="#codeemit_asm">Generating Assembly Code</a></li>
76 <li><a href="#codeemit_bin">Generating Binary Machine Code</a></li>
80 <li><a href="#targetimpls">Target-specific Implementation Notes</a>
82 <li><a href="#x86">The X86 backend</a></li>
88 <div class="doc_author">
89 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>,
90 <a href="mailto:isanbard@gmail.com">Bill Wendling</a>, and
91 <a href="mailto:pronesto@gmail.com">Fernando Magno Quintao
95 <div class="doc_warning">
96 <p>Warning: This is a work in progress.</p>
99 <!-- *********************************************************************** -->
100 <div class="doc_section">
101 <a name="introduction">Introduction</a>
103 <!-- *********************************************************************** -->
105 <div class="doc_text">
107 <p>The LLVM target-independent code generator is a framework that provides a
108 suite of reusable components for translating the LLVM internal representation to
109 the machine code for a specified target—either in assembly form (suitable
110 for a static compiler) or in binary machine code format (usable for a JIT
111 compiler). The LLVM target-independent code generator consists of five main
115 <li><a href="#targetdesc">Abstract target description</a> interfaces which
116 capture important properties about various aspects of the machine, independently
117 of how they will be used. These interfaces are defined in
118 <tt>include/llvm/Target/</tt>.</li>
120 <li>Classes used to represent the <a href="#codegendesc">machine code</a> being
121 generated for a target. These classes are intended to be abstract enough to
122 represent the machine code for <i>any</i> target machine. These classes are
123 defined in <tt>include/llvm/CodeGen/</tt>.</li>
125 <li><a href="#codegenalgs">Target-independent algorithms</a> used to implement
126 various phases of native code generation (register allocation, scheduling, stack
127 frame representation, etc). This code lives in <tt>lib/CodeGen/</tt>.</li>
129 <li><a href="#targetimpls">Implementations of the abstract target description
130 interfaces</a> for particular targets. These machine descriptions make use of
131 the components provided by LLVM, and can optionally provide custom
132 target-specific passes, to build complete code generators for a specific target.
133 Target descriptions live in <tt>lib/Target/</tt>.</li>
135 <li><a href="#jit">The target-independent JIT components</a>. The LLVM JIT is
136 completely target independent (it uses the <tt>TargetJITInfo</tt> structure to
137 interface for target-specific issues. The code for the target-independent
138 JIT lives in <tt>lib/ExecutionEngine/JIT</tt>.</li>
143 Depending on which part of the code generator you are interested in working on,
144 different pieces of this will be useful to you. In any case, you should be
145 familiar with the <a href="#targetdesc">target description</a> and <a
146 href="#codegendesc">machine code representation</a> classes. If you want to add
147 a backend for a new target, you will need to <a href="#targetimpls">implement the
148 target description</a> classes for your new target and understand the <a
149 href="LangRef.html">LLVM code representation</a>. If you are interested in
150 implementing a new <a href="#codegenalgs">code generation algorithm</a>, it
151 should only depend on the target-description and machine code representation
152 classes, ensuring that it is portable.
157 <!-- ======================================================================= -->
158 <div class="doc_subsection">
159 <a name="required">Required components in the code generator</a>
162 <div class="doc_text">
164 <p>The two pieces of the LLVM code generator are the high-level interface to the
165 code generator and the set of reusable components that can be used to build
166 target-specific backends. The two most important interfaces (<a
167 href="#targetmachine"><tt>TargetMachine</tt></a> and <a
168 href="#targetdata"><tt>TargetData</tt></a>) are the only ones that are
169 required to be defined for a backend to fit into the LLVM system, but the others
170 must be defined if the reusable code generator components are going to be
173 <p>This design has two important implications. The first is that LLVM can
174 support completely non-traditional code generation targets. For example, the C
175 backend does not require register allocation, instruction selection, or any of
176 the other standard components provided by the system. As such, it only
177 implements these two interfaces, and does its own thing. Another example of a
178 code generator like this is a (purely hypothetical) backend that converts LLVM
179 to the GCC RTL form and uses GCC to emit machine code for a target.</p>
181 <p>This design also implies that it is possible to design and
182 implement radically different code generators in the LLVM system that do not
183 make use of any of the built-in components. Doing so is not recommended at all,
184 but could be required for radically different targets that do not fit into the
185 LLVM machine description model: FPGAs for example.</p>
189 <!-- ======================================================================= -->
190 <div class="doc_subsection">
191 <a name="high-level-design">The high-level design of the code generator</a>
194 <div class="doc_text">
196 <p>The LLVM target-independent code generator is designed to support efficient and
197 quality code generation for standard register-based microprocessors. Code
198 generation in this model is divided into the following stages:</p>
201 <li><b><a href="#instselect">Instruction Selection</a></b> - This phase
202 determines an efficient way to express the input LLVM code in the target
204 This stage produces the initial code for the program in the target instruction
205 set, then makes use of virtual registers in SSA form and physical registers that
206 represent any required register assignments due to target constraints or calling
207 conventions. This step turns the LLVM code into a DAG of target
210 <li><b><a href="#selectiondag_sched">Scheduling and Formation</a></b> - This
211 phase takes the DAG of target instructions produced by the instruction selection
212 phase, determines an ordering of the instructions, then emits the instructions
213 as <tt><a href="#machineinstr">MachineInstr</a></tt>s with that ordering. Note
214 that we describe this in the <a href="#instselect">instruction selection
215 section</a> because it operates on a <a
216 href="#selectiondag_intro">SelectionDAG</a>.
219 <li><b><a href="#ssamco">SSA-based Machine Code Optimizations</a></b> - This
220 optional stage consists of a series of machine-code optimizations that
221 operate on the SSA-form produced by the instruction selector. Optimizations
222 like modulo-scheduling or peephole optimization work here.
225 <li><b><a href="#regalloc">Register Allocation</a></b> - The
226 target code is transformed from an infinite virtual register file in SSA form
227 to the concrete register file used by the target. This phase introduces spill
228 code and eliminates all virtual register references from the program.</li>
230 <li><b><a href="#proepicode">Prolog/Epilog Code Insertion</a></b> - Once the
231 machine code has been generated for the function and the amount of stack space
232 required is known (used for LLVM alloca's and spill slots), the prolog and
233 epilog code for the function can be inserted and "abstract stack location
234 references" can be eliminated. This stage is responsible for implementing
235 optimizations like frame-pointer elimination and stack packing.</li>
237 <li><b><a href="#latemco">Late Machine Code Optimizations</a></b> - Optimizations
238 that operate on "final" machine code can go here, such as spill code scheduling
239 and peephole optimizations.</li>
241 <li><b><a href="#codeemit">Code Emission</a></b> - The final stage actually
242 puts out the code for the current function, either in the target assembler
243 format or in machine code.</li>
247 <p>The code generator is based on the assumption that the instruction selector
248 will use an optimal pattern matching selector to create high-quality sequences of
249 native instructions. Alternative code generator designs based on pattern
250 expansion and aggressive iterative peephole optimization are much slower. This
251 design permits efficient compilation (important for JIT environments) and
252 aggressive optimization (used when generating code offline) by allowing
253 components of varying levels of sophistication to be used for any step of
256 <p>In addition to these stages, target implementations can insert arbitrary
257 target-specific passes into the flow. For example, the X86 target uses a
258 special pass to handle the 80x87 floating point stack architecture. Other
259 targets with unusual requirements can be supported with custom passes as
265 <!-- ======================================================================= -->
266 <div class="doc_subsection">
267 <a name="tablegen">Using TableGen for target description</a>
270 <div class="doc_text">
272 <p>The target description classes require a detailed description of the target
273 architecture. These target descriptions often have a large amount of common
274 information (e.g., an <tt>add</tt> instruction is almost identical to a
275 <tt>sub</tt> instruction).
276 In order to allow the maximum amount of commonality to be factored out, the LLVM
277 code generator uses the <a href="TableGenFundamentals.html">TableGen</a> tool to
278 describe big chunks of the target machine, which allows the use of
279 domain-specific and target-specific abstractions to reduce the amount of
282 <p>As LLVM continues to be developed and refined, we plan to move more and more
283 of the target description to the <tt>.td</tt> form. Doing so gives us a
284 number of advantages. The most important is that it makes it easier to port
285 LLVM because it reduces the amount of C++ code that has to be written, and the
286 surface area of the code generator that needs to be understood before someone
287 can get something working. Second, it makes it easier to change things. In
288 particular, if tables and other things are all emitted by <tt>tblgen</tt>, we
289 only need a change in one place (<tt>tblgen</tt>) to update all of the targets
290 to a new interface.</p>
294 <!-- *********************************************************************** -->
295 <div class="doc_section">
296 <a name="targetdesc">Target description classes</a>
298 <!-- *********************************************************************** -->
300 <div class="doc_text">
302 <p>The LLVM target description classes (located in the
303 <tt>include/llvm/Target</tt> directory) provide an abstract description of the
304 target machine independent of any particular client. These classes are
305 designed to capture the <i>abstract</i> properties of the target (such as the
306 instructions and registers it has), and do not incorporate any particular pieces
307 of code generation algorithms.</p>
309 <p>All of the target description classes (except the <tt><a
310 href="#targetdata">TargetData</a></tt> class) are designed to be subclassed by
311 the concrete target implementation, and have virtual methods implemented. To
312 get to these implementations, the <tt><a
313 href="#targetmachine">TargetMachine</a></tt> class provides accessors that
314 should be implemented by the target.</p>
318 <!-- ======================================================================= -->
319 <div class="doc_subsection">
320 <a name="targetmachine">The <tt>TargetMachine</tt> class</a>
323 <div class="doc_text">
325 <p>The <tt>TargetMachine</tt> class provides virtual methods that are used to
326 access the target-specific implementations of the various target description
327 classes via the <tt>get*Info</tt> methods (<tt>getInstrInfo</tt>,
328 <tt>getRegisterInfo</tt>, <tt>getFrameInfo</tt>, etc.). This class is
329 designed to be specialized by
330 a concrete target implementation (e.g., <tt>X86TargetMachine</tt>) which
331 implements the various virtual methods. The only required target description
332 class is the <a href="#targetdata"><tt>TargetData</tt></a> class, but if the
333 code generator components are to be used, the other interfaces should be
334 implemented as well.</p>
339 <!-- ======================================================================= -->
340 <div class="doc_subsection">
341 <a name="targetdata">The <tt>TargetData</tt> class</a>
344 <div class="doc_text">
346 <p>The <tt>TargetData</tt> class is the only required target description class,
347 and it is the only class that is not extensible (you cannot derived a new
348 class from it). <tt>TargetData</tt> specifies information about how the target
349 lays out memory for structures, the alignment requirements for various data
350 types, the size of pointers in the target, and whether the target is
351 little-endian or big-endian.</p>
355 <!-- ======================================================================= -->
356 <div class="doc_subsection">
357 <a name="targetlowering">The <tt>TargetLowering</tt> class</a>
360 <div class="doc_text">
362 <p>The <tt>TargetLowering</tt> class is used by SelectionDAG based instruction
363 selectors primarily to describe how LLVM code should be lowered to SelectionDAG
364 operations. Among other things, this class indicates:</p>
367 <li>an initial register class to use for various <tt>ValueType</tt>s</li>
368 <li>which operations are natively supported by the target machine</li>
369 <li>the return type of <tt>setcc</tt> operations</li>
370 <li>the type to use for shift amounts</li>
371 <li>various high-level characteristics, like whether it is profitable to turn
372 division by a constant into a multiplication sequence</li>
377 <!-- ======================================================================= -->
378 <div class="doc_subsection">
379 <a name="mregisterinfo">The <tt>MRegisterInfo</tt> class</a>
382 <div class="doc_text">
384 <p>The <tt>MRegisterInfo</tt> class (which will eventually be renamed to
385 <tt>TargetRegisterInfo</tt>) is used to describe the register file of the
386 target and any interactions between the registers.</p>
388 <p>Registers in the code generator are represented in the code generator by
389 unsigned integers. Physical registers (those that actually exist in the target
390 description) are unique small numbers, and virtual registers are generally
391 large. Note that register #0 is reserved as a flag value.</p>
393 <p>Each register in the processor description has an associated
394 <tt>TargetRegisterDesc</tt> entry, which provides a textual name for the
395 register (used for assembly output and debugging dumps) and a set of aliases
396 (used to indicate whether one register overlaps with another).
399 <p>In addition to the per-register description, the <tt>MRegisterInfo</tt> class
400 exposes a set of processor specific register classes (instances of the
401 <tt>TargetRegisterClass</tt> class). Each register class contains sets of
402 registers that have the same properties (for example, they are all 32-bit
403 integer registers). Each SSA virtual register created by the instruction
404 selector has an associated register class. When the register allocator runs, it
405 replaces virtual registers with a physical register in the set.</p>
408 The target-specific implementations of these classes is auto-generated from a <a
409 href="TableGenFundamentals.html">TableGen</a> description of the register file.
414 <!-- ======================================================================= -->
415 <div class="doc_subsection">
416 <a name="targetinstrinfo">The <tt>TargetInstrInfo</tt> class</a>
419 <div class="doc_text">
420 <p>The <tt>TargetInstrInfo</tt> class is used to describe the machine
421 instructions supported by the target. It is essentially an array of
422 <tt>TargetInstrDescriptor</tt> objects, each of which describes one
423 instruction the target supports. Descriptors define things like the mnemonic
424 for the opcode, the number of operands, the list of implicit register uses
425 and defs, whether the instruction has certain target-independent properties
426 (accesses memory, is commutable, etc), and holds any target-specific
430 <!-- ======================================================================= -->
431 <div class="doc_subsection">
432 <a name="targetframeinfo">The <tt>TargetFrameInfo</tt> class</a>
435 <div class="doc_text">
436 <p>The <tt>TargetFrameInfo</tt> class is used to provide information about the
437 stack frame layout of the target. It holds the direction of stack growth,
438 the known stack alignment on entry to each function, and the offset to the
439 local area. The offset to the local area is the offset from the stack
440 pointer on function entry to the first location where function data (local
441 variables, spill locations) can be stored.</p>
444 <!-- ======================================================================= -->
445 <div class="doc_subsection">
446 <a name="targetsubtarget">The <tt>TargetSubtarget</tt> class</a>
449 <div class="doc_text">
450 <p>The <tt>TargetSubtarget</tt> class is used to provide information about the
451 specific chip set being targeted. A sub-target informs code generation of
452 which instructions are supported, instruction latencies and instruction
453 execution itinerary; i.e., which processing units are used, in what order, and
458 <!-- ======================================================================= -->
459 <div class="doc_subsection">
460 <a name="targetjitinfo">The <tt>TargetJITInfo</tt> class</a>
463 <div class="doc_text">
464 <p>The <tt>TargetJITInfo</tt> class exposes an abstract interface used by the
465 Just-In-Time code generator to perform target-specific activities, such as
466 emitting stubs. If a <tt>TargetMachine</tt> supports JIT code generation, it
467 should provide one of these objects through the <tt>getJITInfo</tt>
471 <!-- *********************************************************************** -->
472 <div class="doc_section">
473 <a name="codegendesc">Machine code description classes</a>
475 <!-- *********************************************************************** -->
477 <div class="doc_text">
479 <p>At the high-level, LLVM code is translated to a machine specific
480 representation formed out of
481 <a href="#machinefunction"><tt>MachineFunction</tt></a>,
482 <a href="#machinebasicblock"><tt>MachineBasicBlock</tt></a>, and <a
483 href="#machineinstr"><tt>MachineInstr</tt></a> instances
484 (defined in <tt>include/llvm/CodeGen</tt>). This representation is completely
485 target agnostic, representing instructions in their most abstract form: an
486 opcode and a series of operands. This representation is designed to support
487 both an SSA representation for machine code, as well as a register allocated,
492 <!-- ======================================================================= -->
493 <div class="doc_subsection">
494 <a name="machineinstr">The <tt>MachineInstr</tt> class</a>
497 <div class="doc_text">
499 <p>Target machine instructions are represented as instances of the
500 <tt>MachineInstr</tt> class. This class is an extremely abstract way of
501 representing machine instructions. In particular, it only keeps track of
502 an opcode number and a set of operands.</p>
504 <p>The opcode number is a simple unsigned integer that only has meaning to a
505 specific backend. All of the instructions for a target should be defined in
506 the <tt>*InstrInfo.td</tt> file for the target. The opcode enum values
507 are auto-generated from this description. The <tt>MachineInstr</tt> class does
508 not have any information about how to interpret the instruction (i.e., what the
509 semantics of the instruction are); for that you must refer to the
510 <tt><a href="#targetinstrinfo">TargetInstrInfo</a></tt> class.</p>
512 <p>The operands of a machine instruction can be of several different types:
513 a register reference, a constant integer, a basic block reference, etc. In
514 addition, a machine operand should be marked as a def or a use of the value
515 (though only registers are allowed to be defs).</p>
517 <p>By convention, the LLVM code generator orders instruction operands so that
518 all register definitions come before the register uses, even on architectures
519 that are normally printed in other orders. For example, the SPARC add
520 instruction: "<tt>add %i1, %i2, %i3</tt>" adds the "%i1", and "%i2" registers
521 and stores the result into the "%i3" register. In the LLVM code generator,
522 the operands should be stored as "<tt>%i3, %i1, %i2</tt>": with the destination
525 <p>Keeping destination (definition) operands at the beginning of the operand
526 list has several advantages. In particular, the debugging printer will print
527 the instruction like this:</p>
529 <div class="doc_code">
535 <p>Also if the first operand is a def, it is easier to <a
536 href="#buildmi">create instructions</a> whose only def is the first
541 <!-- _______________________________________________________________________ -->
542 <div class="doc_subsubsection">
543 <a name="buildmi">Using the <tt>MachineInstrBuilder.h</tt> functions</a>
546 <div class="doc_text">
548 <p>Machine instructions are created by using the <tt>BuildMI</tt> functions,
549 located in the <tt>include/llvm/CodeGen/MachineInstrBuilder.h</tt> file. The
550 <tt>BuildMI</tt> functions make it easy to build arbitrary machine
551 instructions. Usage of the <tt>BuildMI</tt> functions look like this:</p>
553 <div class="doc_code">
555 // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
556 // instruction. The '1' specifies how many operands will be added.
557 MachineInstr *MI = BuildMI(X86::MOV32ri, 1, DestReg).addImm(42);
559 // Create the same instr, but insert it at the end of a basic block.
560 MachineBasicBlock &MBB = ...
561 BuildMI(MBB, X86::MOV32ri, 1, DestReg).addImm(42);
563 // Create the same instr, but insert it before a specified iterator point.
564 MachineBasicBlock::iterator MBBI = ...
565 BuildMI(MBB, MBBI, X86::MOV32ri, 1, DestReg).addImm(42);
567 // Create a 'cmp Reg, 0' instruction, no destination reg.
568 MI = BuildMI(X86::CMP32ri, 2).addReg(Reg).addImm(0);
569 // Create an 'sahf' instruction which takes no operands and stores nothing.
570 MI = BuildMI(X86::SAHF, 0);
572 // Create a self looping branch instruction.
573 BuildMI(MBB, X86::JNE, 1).addMBB(&MBB);
577 <p>The key thing to remember with the <tt>BuildMI</tt> functions is that you
578 have to specify the number of operands that the machine instruction will take.
579 This allows for efficient memory allocation. You also need to specify if
580 operands default to be uses of values, not definitions. If you need to add a
581 definition operand (other than the optional destination register), you must
582 explicitly mark it as such:</p>
584 <div class="doc_code">
586 MI.addReg(Reg, MachineOperand::Def);
592 <!-- _______________________________________________________________________ -->
593 <div class="doc_subsubsection">
594 <a name="fixedregs">Fixed (preassigned) registers</a>
597 <div class="doc_text">
599 <p>One important issue that the code generator needs to be aware of is the
600 presence of fixed registers. In particular, there are often places in the
601 instruction stream where the register allocator <em>must</em> arrange for a
602 particular value to be in a particular register. This can occur due to
603 limitations of the instruction set (e.g., the X86 can only do a 32-bit divide
604 with the <tt>EAX</tt>/<tt>EDX</tt> registers), or external factors like calling
605 conventions. In any case, the instruction selector should emit code that
606 copies a virtual register into or out of a physical register when needed.</p>
608 <p>For example, consider this simple LLVM example:</p>
610 <div class="doc_code">
612 int %test(int %X, int %Y) {
619 <p>The X86 instruction selector produces this machine code for the <tt>div</tt>
620 and <tt>ret</tt> (use
621 "<tt>llc X.bc -march=x86 -print-machineinstrs</tt>" to get this):</p>
623 <div class="doc_code">
626 %EAX = mov %reg1024 ;; Copy X (in reg1024) into EAX
627 %reg1027 = sar %reg1024, 31
628 %EDX = mov %reg1027 ;; Sign extend X into EDX
629 idiv %reg1025 ;; Divide by Y (in reg1025)
630 %reg1026 = mov %EAX ;; Read the result (Z) out of EAX
633 %EAX = mov %reg1026 ;; 32-bit return value goes in EAX
638 <p>By the end of code generation, the register allocator has coalesced
639 the registers and deleted the resultant identity moves producing the
642 <div class="doc_code">
644 ;; X is in EAX, Y is in ECX
652 <p>This approach is extremely general (if it can handle the X86 architecture,
653 it can handle anything!) and allows all of the target specific
654 knowledge about the instruction stream to be isolated in the instruction
655 selector. Note that physical registers should have a short lifetime for good
656 code generation, and all physical registers are assumed dead on entry to and
657 exit from basic blocks (before register allocation). Thus, if you need a value
658 to be live across basic block boundaries, it <em>must</em> live in a virtual
663 <!-- _______________________________________________________________________ -->
664 <div class="doc_subsubsection">
665 <a name="ssa">Machine code in SSA form</a>
668 <div class="doc_text">
670 <p><tt>MachineInstr</tt>'s are initially selected in SSA-form, and
671 are maintained in SSA-form until register allocation happens. For the most
672 part, this is trivially simple since LLVM is already in SSA form; LLVM PHI nodes
673 become machine code PHI nodes, and virtual registers are only allowed to have a
674 single definition.</p>
676 <p>After register allocation, machine code is no longer in SSA-form because there
677 are no virtual registers left in the code.</p>
681 <!-- ======================================================================= -->
682 <div class="doc_subsection">
683 <a name="machinebasicblock">The <tt>MachineBasicBlock</tt> class</a>
686 <div class="doc_text">
688 <p>The <tt>MachineBasicBlock</tt> class contains a list of machine instructions
689 (<tt><a href="#machineinstr">MachineInstr</a></tt> instances). It roughly
690 corresponds to the LLVM code input to the instruction selector, but there can be
691 a one-to-many mapping (i.e. one LLVM basic block can map to multiple machine
692 basic blocks). The <tt>MachineBasicBlock</tt> class has a
693 "<tt>getBasicBlock</tt>" method, which returns the LLVM basic block that it
698 <!-- ======================================================================= -->
699 <div class="doc_subsection">
700 <a name="machinefunction">The <tt>MachineFunction</tt> class</a>
703 <div class="doc_text">
705 <p>The <tt>MachineFunction</tt> class contains a list of machine basic blocks
706 (<tt><a href="#machinebasicblock">MachineBasicBlock</a></tt> instances). It
707 corresponds one-to-one with the LLVM function input to the instruction selector.
708 In addition to a list of basic blocks, the <tt>MachineFunction</tt> contains a
709 a <tt>MachineConstantPool</tt>, a <tt>MachineFrameInfo</tt>, a
710 <tt>MachineFunctionInfo</tt>, a <tt>SSARegMap</tt>, and a set of live in and
711 live out registers for the function. See
712 <tt>include/llvm/CodeGen/MachineFunction.h</tt> for more information.</p>
716 <!-- *********************************************************************** -->
717 <div class="doc_section">
718 <a name="codegenalgs">Target-independent code generation algorithms</a>
720 <!-- *********************************************************************** -->
722 <div class="doc_text">
724 <p>This section documents the phases described in the <a
725 href="#high-level-design">high-level design of the code generator</a>. It
726 explains how they work and some of the rationale behind their design.</p>
730 <!-- ======================================================================= -->
731 <div class="doc_subsection">
732 <a name="instselect">Instruction Selection</a>
735 <div class="doc_text">
737 Instruction Selection is the process of translating LLVM code presented to the
738 code generator into target-specific machine instructions. There are several
739 well-known ways to do this in the literature. In LLVM there are two main forms:
740 the SelectionDAG based instruction selector framework and an old-style 'simple'
741 instruction selector, which effectively peephole selects each LLVM instruction
742 into a series of machine instructions. We recommend that all targets use the
743 SelectionDAG infrastructure.
746 <p>Portions of the DAG instruction selector are generated from the target
747 description (<tt>*.td</tt>) files. Our goal is for the entire instruction
748 selector to be generated from these <tt>.td</tt> files.</p>
751 <!-- _______________________________________________________________________ -->
752 <div class="doc_subsubsection">
753 <a name="selectiondag_intro">Introduction to SelectionDAGs</a>
756 <div class="doc_text">
758 <p>The SelectionDAG provides an abstraction for code representation in a way
759 that is amenable to instruction selection using automatic techniques
760 (e.g. dynamic-programming based optimal pattern matching selectors). It is also
761 well-suited to other phases of code generation; in particular,
762 instruction scheduling (SelectionDAG's are very close to scheduling DAGs
763 post-selection). Additionally, the SelectionDAG provides a host representation
764 where a large variety of very-low-level (but target-independent)
765 <a href="#selectiondag_optimize">optimizations</a> may be
766 performed; ones which require extensive information about the instructions
767 efficiently supported by the target.</p>
769 <p>The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the
770 <tt>SDNode</tt> class. The primary payload of the <tt>SDNode</tt> is its
771 operation code (Opcode) that indicates what operation the node performs and
772 the operands to the operation.
773 The various operation node types are described at the top of the
774 <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt> file.</p>
776 <p>Although most operations define a single value, each node in the graph may
777 define multiple values. For example, a combined div/rem operation will define
778 both the dividend and the remainder. Many other situations require multiple
779 values as well. Each node also has some number of operands, which are edges
780 to the node defining the used value. Because nodes may define multiple values,
781 edges are represented by instances of the <tt>SDOperand</tt> class, which is
782 a <tt><SDNode, unsigned></tt> pair, indicating the node and result
783 value being used, respectively. Each value produced by an <tt>SDNode</tt> has
784 an associated <tt>MVT::ValueType</tt> indicating what type the value is.</p>
786 <p>SelectionDAGs contain two different kinds of values: those that represent
787 data flow and those that represent control flow dependencies. Data values are
788 simple edges with an integer or floating point value type. Control edges are
789 represented as "chain" edges which are of type <tt>MVT::Other</tt>. These edges
790 provide an ordering between nodes that have side effects (such as
791 loads, stores, calls, returns, etc). All nodes that have side effects should
792 take a token chain as input and produce a new one as output. By convention,
793 token chain inputs are always operand #0, and chain results are always the last
794 value produced by an operation.</p>
796 <p>A SelectionDAG has designated "Entry" and "Root" nodes. The Entry node is
797 always a marker node with an Opcode of <tt>ISD::EntryToken</tt>. The Root node
798 is the final side-effecting node in the token chain. For example, in a single
799 basic block function it would be the return node.</p>
801 <p>One important concept for SelectionDAGs is the notion of a "legal" vs.
802 "illegal" DAG. A legal DAG for a target is one that only uses supported
803 operations and supported types. On a 32-bit PowerPC, for example, a DAG with
804 a value of type i1, i8, i16, or i64 would be illegal, as would a DAG that uses a
805 SREM or UREM operation. The
806 <a href="#selectiondag_legalize">legalize</a> phase is responsible for turning
807 an illegal DAG into a legal DAG.</p>
811 <!-- _______________________________________________________________________ -->
812 <div class="doc_subsubsection">
813 <a name="selectiondag_process">SelectionDAG Instruction Selection Process</a>
816 <div class="doc_text">
818 <p>SelectionDAG-based instruction selection consists of the following steps:</p>
821 <li><a href="#selectiondag_build">Build initial DAG</a> - This stage
822 performs a simple translation from the input LLVM code to an illegal
824 <li><a href="#selectiondag_optimize">Optimize SelectionDAG</a> - This stage
825 performs simple optimizations on the SelectionDAG to simplify it, and
826 recognize meta instructions (like rotates and <tt>div</tt>/<tt>rem</tt>
827 pairs) for targets that support these meta operations. This makes the
828 resultant code more efficient and the <a href="#selectiondag_select">select
829 instructions from DAG</a> phase (below) simpler.</li>
830 <li><a href="#selectiondag_legalize">Legalize SelectionDAG</a> - This stage
831 converts the illegal SelectionDAG to a legal SelectionDAG by eliminating
832 unsupported operations and data types.</li>
833 <li><a href="#selectiondag_optimize">Optimize SelectionDAG (#2)</a> - This
834 second run of the SelectionDAG optimizes the newly legalized DAG to
835 eliminate inefficiencies introduced by legalization.</li>
836 <li><a href="#selectiondag_select">Select instructions from DAG</a> - Finally,
837 the target instruction selector matches the DAG operations to target
838 instructions. This process translates the target-independent input DAG into
839 another DAG of target instructions.</li>
840 <li><a href="#selectiondag_sched">SelectionDAG Scheduling and Formation</a>
841 - The last phase assigns a linear order to the instructions in the
842 target-instruction DAG and emits them into the MachineFunction being
843 compiled. This step uses traditional prepass scheduling techniques.</li>
846 <p>After all of these steps are complete, the SelectionDAG is destroyed and the
847 rest of the code generation passes are run.</p>
849 <p>One great way to visualize what is going on here is to take advantage of a
850 few LLC command line options. In particular, the <tt>-view-isel-dags</tt>
851 option pops up a window with the SelectionDAG input to the Select phase for all
852 of the code compiled (if you only get errors printed to the console while using
853 this, you probably <a href="ProgrammersManual.html#ViewGraph">need to configure
854 your system</a> to add support for it). The <tt>-view-sched-dags</tt> option
855 views the SelectionDAG output from the Select phase and input to the Scheduler
860 <!-- _______________________________________________________________________ -->
861 <div class="doc_subsubsection">
862 <a name="selectiondag_build">Initial SelectionDAG Construction</a>
865 <div class="doc_text">
867 <p>The initial SelectionDAG is naïvely peephole expanded from the LLVM
868 input by the <tt>SelectionDAGLowering</tt> class in the
869 <tt>lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp</tt> file. The intent of this
870 pass is to expose as much low-level, target-specific details to the SelectionDAG
871 as possible. This pass is mostly hard-coded (e.g. an LLVM <tt>add</tt> turns
872 into an <tt>SDNode add</tt> while a <tt>geteelementptr</tt> is expanded into the
873 obvious arithmetic). This pass requires target-specific hooks to lower calls,
874 returns, varargs, etc. For these features, the
875 <tt><a href="#targetlowering">TargetLowering</a></tt> interface is used.</p>
879 <!-- _______________________________________________________________________ -->
880 <div class="doc_subsubsection">
881 <a name="selectiondag_legalize">SelectionDAG Legalize Phase</a>
884 <div class="doc_text">
886 <p>The Legalize phase is in charge of converting a DAG to only use the types and
887 operations that are natively supported by the target. This involves two major
891 <li><p>Convert values of unsupported types to values of supported types.</p>
892 <p>There are two main ways of doing this: converting small types to
893 larger types ("promoting"), and breaking up large integer types
894 into smaller ones ("expanding"). For example, a target might require
895 that all f32 values are promoted to f64 and that all i1/i8/i16 values
896 are promoted to i32. The same target might require that all i64 values
897 be expanded into i32 values. These changes can insert sign and zero
898 extensions as needed to make sure that the final code has the same
899 behavior as the input.</p>
900 <p>A target implementation tells the legalizer which types are supported
901 (and which register class to use for them) by calling the
902 <tt>addRegisterClass</tt> method in its TargetLowering constructor.</p>
905 <li><p>Eliminate operations that are not supported by the target.</p>
906 <p>Targets often have weird constraints, such as not supporting every
907 operation on every supported datatype (e.g. X86 does not support byte
908 conditional moves and PowerPC does not support sign-extending loads from
909 a 16-bit memory location). Legalize takes care of this by open-coding
910 another sequence of operations to emulate the operation ("expansion"), by
911 promoting one type to a larger type that supports the operation
912 ("promotion"), or by using a target-specific hook to implement the
913 legalization ("custom").</p>
914 <p>A target implementation tells the legalizer which operations are not
915 supported (and which of the above three actions to take) by calling the
916 <tt>setOperationAction</tt> method in its <tt>TargetLowering</tt>
921 <p>Prior to the existance of the Legalize pass, we required that every target
922 <a href="#selectiondag_optimize">selector</a> supported and handled every
923 operator and type even if they are not natively supported. The introduction of
924 the Legalize phase allows all of the cannonicalization patterns to be shared
925 across targets, and makes it very easy to optimize the cannonicalized code
926 because it is still in the form of a DAG.</p>
930 <!-- _______________________________________________________________________ -->
931 <div class="doc_subsubsection">
932 <a name="selectiondag_optimize">SelectionDAG Optimization Phase: the DAG
936 <div class="doc_text">
938 <p>The SelectionDAG optimization phase is run twice for code generation: once
939 immediately after the DAG is built and once after legalization. The first run
940 of the pass allows the initial code to be cleaned up (e.g. performing
941 optimizations that depend on knowing that the operators have restricted type
942 inputs). The second run of the pass cleans up the messy code generated by the
943 Legalize pass, which allows Legalize to be very simple (it can focus on making
944 code legal instead of focusing on generating <em>good</em> and legal code).</p>
946 <p>One important class of optimizations performed is optimizing inserted sign
947 and zero extension instructions. We currently use ad-hoc techniques, but could
948 move to more rigorous techniques in the future. Here are some good papers on
952 "<a href="http://www.eecs.harvard.edu/~nr/pubs/widen-abstract.html">Widening
953 integer arithmetic</a>"<br>
954 Kevin Redwine and Norman Ramsey<br>
955 International Conference on Compiler Construction (CC) 2004
960 "<a href="http://portal.acm.org/citation.cfm?doid=512529.512552">Effective
961 sign extension elimination</a>"<br>
962 Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani<br>
963 Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design
969 <!-- _______________________________________________________________________ -->
970 <div class="doc_subsubsection">
971 <a name="selectiondag_select">SelectionDAG Select Phase</a>
974 <div class="doc_text">
976 <p>The Select phase is the bulk of the target-specific code for instruction
977 selection. This phase takes a legal SelectionDAG as input, pattern matches the
978 instructions supported by the target to this DAG, and produces a new DAG of
979 target code. For example, consider the following LLVM fragment:</p>
981 <div class="doc_code">
983 %t1 = add float %W, %X
984 %t2 = mul float %t1, %Y
985 %t3 = add float %t2, %Z
989 <p>This LLVM code corresponds to a SelectionDAG that looks basically like
992 <div class="doc_code">
994 (fadd:f32 (fmul:f32 (fadd:f32 W, X), Y), Z)
998 <p>If a target supports floating point multiply-and-add (FMA) operations, one
999 of the adds can be merged with the multiply. On the PowerPC, for example, the
1000 output of the instruction selector might look like this DAG:</p>
1002 <div class="doc_code">
1004 (FMADDS (FADDS W, X), Y, Z)
1008 <p>The <tt>FMADDS</tt> instruction is a ternary instruction that multiplies its
1009 first two operands and adds the third (as single-precision floating-point
1010 numbers). The <tt>FADDS</tt> instruction is a simple binary single-precision
1011 add instruction. To perform this pattern match, the PowerPC backend includes
1012 the following instruction definitions:</p>
1014 <div class="doc_code">
1016 def FMADDS : AForm_1<59, 29,
1017 (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRC, F4RC:$FRB),
1018 "fmadds $FRT, $FRA, $FRC, $FRB",
1019 [<b>(set F4RC:$FRT, (fadd (fmul F4RC:$FRA, F4RC:$FRC),
1020 F4RC:$FRB))</b>]>;
1021 def FADDS : AForm_2<59, 21,
1022 (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRB),
1023 "fadds $FRT, $FRA, $FRB",
1024 [<b>(set F4RC:$FRT, (fadd F4RC:$FRA, F4RC:$FRB))</b>]>;
1028 <p>The portion of the instruction definition in bold indicates the pattern used
1029 to match the instruction. The DAG operators (like <tt>fmul</tt>/<tt>fadd</tt>)
1030 are defined in the <tt>lib/Target/TargetSelectionDAG.td</tt> file.
1031 "<tt>F4RC</tt>" is the register class of the input and result values.<p>
1033 <p>The TableGen DAG instruction selector generator reads the instruction
1034 patterns in the <tt>.td</tt> file and automatically builds parts of the pattern
1035 matching code for your target. It has the following strengths:</p>
1038 <li>At compiler-compiler time, it analyzes your instruction patterns and tells
1039 you if your patterns make sense or not.</li>
1040 <li>It can handle arbitrary constraints on operands for the pattern match. In
1041 particular, it is straight-forward to say things like "match any immediate
1042 that is a 13-bit sign-extended value". For examples, see the
1043 <tt>immSExt16</tt> and related <tt>tblgen</tt> classes in the PowerPC
1045 <li>It knows several important identities for the patterns defined. For
1046 example, it knows that addition is commutative, so it allows the
1047 <tt>FMADDS</tt> pattern above to match "<tt>(fadd X, (fmul Y, Z))</tt>" as
1048 well as "<tt>(fadd (fmul X, Y), Z)</tt>", without the target author having
1049 to specially handle this case.</li>
1050 <li>It has a full-featured type-inferencing system. In particular, you should
1051 rarely have to explicitly tell the system what type parts of your patterns
1052 are. In the <tt>FMADDS</tt> case above, we didn't have to tell
1053 <tt>tblgen</tt> that all of the nodes in the pattern are of type 'f32'. It
1054 was able to infer and propagate this knowledge from the fact that
1055 <tt>F4RC</tt> has type 'f32'.</li>
1056 <li>Targets can define their own (and rely on built-in) "pattern fragments".
1057 Pattern fragments are chunks of reusable patterns that get inlined into your
1058 patterns during compiler-compiler time. For example, the integer
1059 "<tt>(not x)</tt>" operation is actually defined as a pattern fragment that
1060 expands as "<tt>(xor x, -1)</tt>", since the SelectionDAG does not have a
1061 native '<tt>not</tt>' operation. Targets can define their own short-hand
1062 fragments as they see fit. See the definition of '<tt>not</tt>' and
1063 '<tt>ineg</tt>' for examples.</li>
1064 <li>In addition to instructions, targets can specify arbitrary patterns that
1065 map to one or more instructions using the 'Pat' class. For example,
1066 the PowerPC has no way to load an arbitrary integer immediate into a
1067 register in one instruction. To tell tblgen how to do this, it defines:
1070 <div class="doc_code">
1072 // Arbitrary immediate support. Implement in terms of LIS/ORI.
1073 def : Pat<(i32 imm:$imm),
1074 (ORI (LIS (HI16 imm:$imm)), (LO16 imm:$imm))>;
1078 If none of the single-instruction patterns for loading an immediate into a
1079 register match, this will be used. This rule says "match an arbitrary i32
1080 immediate, turning it into an <tt>ORI</tt> ('or a 16-bit immediate') and an
1081 <tt>LIS</tt> ('load 16-bit immediate, where the immediate is shifted to the
1082 left 16 bits') instruction". To make this work, the
1083 <tt>LO16</tt>/<tt>HI16</tt> node transformations are used to manipulate the
1084 input immediate (in this case, take the high or low 16-bits of the
1086 <li>While the system does automate a lot, it still allows you to write custom
1087 C++ code to match special cases if there is something that is hard to
1091 <p>While it has many strengths, the system currently has some limitations,
1092 primarily because it is a work in progress and is not yet finished:</p>
1095 <li>Overall, there is no way to define or match SelectionDAG nodes that define
1096 multiple values (e.g. <tt>ADD_PARTS</tt>, <tt>LOAD</tt>, <tt>CALL</tt>,
1097 etc). This is the biggest reason that you currently still <em>have to</em>
1098 write custom C++ code for your instruction selector.</li>
1099 <li>There is no great way to support matching complex addressing modes yet. In
1100 the future, we will extend pattern fragments to allow them to define
1101 multiple values (e.g. the four operands of the <a href="#x86_memory">X86
1102 addressing mode</a>). In addition, we'll extend fragments so that a
1103 fragment can match multiple different patterns.</li>
1104 <li>We don't automatically infer flags like isStore/isLoad yet.</li>
1105 <li>We don't automatically generate the set of supported registers and
1106 operations for the <a href="#"selectiondag_legalize>Legalizer</a> yet.</li>
1107 <li>We don't have a way of tying in custom legalized nodes yet.</li>
1110 <p>Despite these limitations, the instruction selector generator is still quite
1111 useful for most of the binary and logical operations in typical instruction
1112 sets. If you run into any problems or can't figure out how to do something,
1113 please let Chris know!</p>
1117 <!-- _______________________________________________________________________ -->
1118 <div class="doc_subsubsection">
1119 <a name="selectiondag_sched">SelectionDAG Scheduling and Formation Phase</a>
1122 <div class="doc_text">
1124 <p>The scheduling phase takes the DAG of target instructions from the selection
1125 phase and assigns an order. The scheduler can pick an order depending on
1126 various constraints of the machines (i.e. order for minimal register pressure or
1127 try to cover instruction latencies). Once an order is established, the DAG is
1128 converted to a list of <tt><a href="#machineinstr">MachineInstr</a></tt>s and
1129 the SelectionDAG is destroyed.</p>
1131 <p>Note that this phase is logically separate from the instruction selection
1132 phase, but is tied to it closely in the code because it operates on
1137 <!-- _______________________________________________________________________ -->
1138 <div class="doc_subsubsection">
1139 <a name="selectiondag_future">Future directions for the SelectionDAG</a>
1142 <div class="doc_text">
1145 <li>Optional function-at-a-time selection.</li>
1146 <li>Auto-generate entire selector from <tt>.td</tt> file.</li>
1152 <!-- ======================================================================= -->
1153 <div class="doc_subsection">
1154 <a name="ssamco">SSA-based Machine Code Optimizations</a>
1156 <div class="doc_text"><p>To Be Written</p></div>
1158 <!-- ======================================================================= -->
1159 <div class="doc_subsection">
1160 <a name="regalloc">Register Allocation</a>
1163 <div class="doc_text">
1165 <p>The <i>Register Allocation problem</i> consists in mapping a
1166 program <i>P<sub>v</sub></i>, that can use an unbounded number of
1167 virtual registers, to a program <i>P<sub>p</sub></i> that contains a
1168 finite (possibly small) number of physical registers. Each target
1169 architecture has a different number of physical registers. If the
1170 number of physical registers is not enough to accommodate all the
1171 virtual registers, some of them will have to be mapped into
1172 memory. These virtuals are called <i>spilled virtuals</i>.</p>
1176 <!-- _______________________________________________________________________ -->
1178 <div class="doc_subsubsection">
1179 <a name="regAlloc_represent">How registers are represented in LLVM</a>
1182 <div class="doc_text">
1184 <p>In LLVM, physical registers are denoted by integer numbers that
1185 normally range from 1 to 1023. To see how this numbering is defined
1186 for a particular architecture, you can read the
1187 <tt>GenRegisterNames.inc</tt> file for that architecture. For
1188 instance, by inspecting
1189 <tt>lib/Target/X86/X86GenRegisterNames.inc</tt> we see that the 32-bit
1190 register <tt>EAX</tt> is denoted by 15, and the MMX register
1191 <tt>MM0</tt> is mapped to 48.</p>
1193 <p>Some architectures contain registers that share the same physical
1194 location. A notable example is the X86 platform. For instance, in the
1195 X86 architecture, the registers <tt>EAX</tt>, <tt>AX</tt> and
1196 <tt>AL</tt> share the first eight bits. These physical registers are
1197 marked as <i>aliased</i> in LLVM. Given a particular architecture, you
1198 can check which registers are aliased by inspecting its
1199 <tt>RegisterInfo.td</tt> file. Moreover, the method
1200 <tt>MRegisterInfo::getAliasSet(p_reg)</tt> returns an array containing
1201 all the physical registers aliased to the register <tt>p_reg</tt>.</p>
1203 <p>Physical registers, in LLVM, are grouped in <i>Register Classes</i>.
1204 Elements in the same register class are functionally equivalent, and can
1205 be interchangeably used. Each virtual register can only be mapped to
1206 physical registers of a particular class. For instance, in the X86
1207 architecture, some virtuals can only be allocated to 8 bit registers.
1208 A register class is described by <tt>TargetRegisterClass</tt> objects.
1209 To discover if a virtual register is compatible with a given physical,
1210 this code can be used:
1213 <div class="doc_code">
1215 bool RegMapping_Fer::compatible_class(MachineFunction &mf,
1218 assert(MRegisterInfo::isPhysicalRegister(p_reg) &&
1219 "Target register must be physical");
1220 const TargetRegisterClass *trc = mf.getSSARegMap()->getRegClass(v_reg);
1221 return trc->contains(p_reg);
1226 <p>Sometimes, mostly for debugging purposes, it is useful to change
1227 the number of physical registers available in the target
1228 architecture. This must be done statically, inside the
1229 <tt>TargetRegsterInfo.td</tt> file. Just <tt>grep</tt> for
1230 <tt>RegisterClass</tt>, the last parameter of which is a list of
1231 registers. Just commenting some out is one simple way to avoid them
1232 being used. A more polite way is to explicitly exclude some registers
1233 from the <i>allocation order</i>. See the definition of the
1234 <tt>GR</tt> register class in
1235 <tt>lib/Target/IA64/IA64RegisterInfo.td</tt> for an example of this
1236 (e.g., <tt>numReservedRegs</tt> registers are hidden.)</p>
1238 <p>Virtual registers are also denoted by integer numbers. Contrary to
1239 physical registers, different virtual registers never share the same
1240 number. The smallest virtual register is normally assigned the number
1241 1024. This may change, so, in order to know which is the first virtual
1242 register, you should access
1243 <tt>MRegisterInfo::FirstVirtualRegister</tt>. Any register whose
1244 number is greater than or equal to
1245 <tt>MRegisterInfo::FirstVirtualRegister</tt> is considered a virtual
1246 register. Whereas physical registers are statically defined in a
1247 <tt>TargetRegisterInfo.td</tt> file and cannot be created by the
1248 application developer, that is not the case with virtual registers.
1249 In order to create new virtual registers, use the method
1250 <tt>SSARegMap::createVirtualRegister()</tt>. This method will return a
1251 virtual register with the highest code.
1254 <p>Before register allocation, the operands of an instruction are
1255 mostly virtual registers, although physical registers may also be
1256 used. In order to check if a given machine operand is a register, use
1257 the boolean function <tt>MachineOperand::isRegister()</tt>. To obtain
1258 the integer code of a register, use
1259 <tt>MachineOperand::getReg()</tt>. An instruction may define or use a
1260 register. For instance, <tt>ADD reg:1026 := reg:1025 reg:1024</tt>
1261 defines the registers 1024, and uses registers 1025 and 1026. Given a
1262 register operand, the method <tt>MachineOperand::isUse()</tt> informs
1263 if that register is being used by the instruction. The method
1264 <tt>MachineOperand::isDef()</tt> informs if that registers is being
1267 <p>We will call physical registers present in the LLVM bytecode before
1268 register allocation <i>pre-colored registers</i>. Pre-colored
1269 registers are used in many different situations, for instance, to pass
1270 parameters of functions calls, and to store results of particular
1271 instructions. There are two types of pre-colored registers: the ones
1272 <i>implicitly</i> defined, and those <i>explicitly</i>
1273 defined. Explicitly defined registers are normal operands, and can be
1274 accessed with <tt>MachineInstr::getOperand(int)::getReg()</tt>. In
1275 order to check which registers are implicitly defined by an
1276 instruction, use the
1277 <tt>TargetInstrInfo::get(opcode)::ImplicitDefs</tt>, where
1278 <tt>opcode</tt> is the opcode of the target instruction. One important
1279 difference between explicit and implicit physical registers is that
1280 the latter are defined statically for each instruction, whereas the
1281 former may vary depending on the program being compiled. For example,
1282 an instruction that represents a function call will always implicitly
1283 define or use the same set of physical registers. To read the
1284 registers implicitly used by an instruction, use
1285 <tt>TargetInstrInfo::get(opcode)::ImplicitUses</tt>. Pre-colored
1286 registers impose constraints on any register allocation algorithm. The
1287 register allocator must make sure that none of them is been
1288 overwritten by the values of virtual registers while still alive.</p>
1292 <!-- _______________________________________________________________________ -->
1294 <div class="doc_subsubsection">
1295 <a name="regAlloc_howTo">Mapping virtual registers to physical registers</a>
1298 <div class="doc_text">
1300 <p>There are two ways to map virtual registers to physical registers (or to
1301 memory slots). The first way, that we will call <i>direct mapping</i>,
1302 is based on the use of methods of the classes <tt>MRegisterInfo</tt>,
1303 and <tt>MachineOperand</tt>. The second way, that we will call
1304 <i>indirect mapping</i>, relies on the <tt>VirtRegMap</tt> class in
1305 order to insert loads and stores sending and getting values to and from
1308 <p>The direct mapping provides more flexibility to the developer of
1309 the register allocator; however, it is more error prone, and demands
1310 more implementation work. Basically, the programmer will have to
1311 specify where load and store instructions should be inserted in the
1312 target function being compiled in order to get and store values in
1313 memory. To assign a physical register to a virtual register present in
1314 a given operand, use <tt>MachineOperand::setReg(p_reg)</tt>. To insert
1315 a store instruction, use
1316 <tt>MRegisterInfo::storeRegToStackSlot(...)</tt>, and to insert a load
1317 instruction, use <tt>MRegisterInfo::loadRegFromStackSlot</tt>.</p>
1319 <p>The indirect mapping shields the application developer from the
1320 complexities of inserting load and store instructions. In order to map
1321 a virtual register to a physical one, use
1322 <tt>VirtRegMap::assignVirt2Phys(vreg, preg)</tt>. In order to map a
1323 certain virtual register to memory, use
1324 <tt>VirtRegMap::assignVirt2StackSlot(vreg)</tt>. This method will
1325 return the stack slot where <tt>vreg</tt>'s value will be located. If
1326 it is necessary to map another virtual register to the same stack
1327 slot, use <tt>VirtRegMap::assignVirt2StackSlot(vreg,
1328 stack_location)</tt>. One important point to consider when using the
1329 indirect mapping, is that even if a virtual register is mapped to
1330 memory, it still needs to be mapped to a physical register. This
1331 physical register is the location where the virtual register is
1332 supposed to be found before being stored or after being reloaded.</p>
1334 <p>If the indirect strategy is used, after all the virtual registers
1335 have been mapped to physical registers or stack slots, it is necessary
1336 to use a spiller object to place load and store instructions in the
1337 code. Every virtual that has been mapped to a stack slot will be
1338 stored to memory after been defined and will be loaded before being
1339 used. The implementation of the spiller tries to recycle load/store
1340 instructions, avoiding unnecessary instructions. For an example of how
1341 to invoke the spiller, see
1342 <tt>RegAllocLinearScan::runOnMachineFunction</tt> in
1343 <tt>lib/CodeGen/RegAllocLinearScan.cpp</tt>.</p>
1347 <!-- _______________________________________________________________________ -->
1348 <div class="doc_subsubsection">
1349 <a name="regAlloc_twoAddr">Handling two address instructions</a>
1352 <div class="doc_text">
1354 <p>With very rare exceptions (e.g., function calls), the LLVM machine
1355 code instructions are three address instructions. That is, each
1356 instruction is expected to define at most one register, and to use at
1357 most two registers. However, some architectures use two address
1358 instructions. In this case, the defined register is also one of the
1359 used register. For instance, an instruction such as <tt>ADD %EAX,
1360 %EBX</tt>, in X86 is actually equivalent to <tt>%EAX = %EAX +
1363 <p>In order to produce correct code, LLVM must convert three address
1364 instructions that represent two address instructions into true two
1365 address instructions. LLVM provides the pass
1366 <tt>TwoAddressInstructionPass</tt> for this specific purpose. It must
1367 be run before register allocation takes place. After its execution,
1368 the resulting code may no longer be in SSA form. This happens, for
1369 instance, in situations where an instruction such as <tt>%a = ADD %b
1370 %c</tt> is converted to two instructions such as:</p>
1372 <div class="doc_code">
1379 <p>Notice that, internally, the second instruction is represented as
1380 <tt>ADD %a[def/use] %b</tt>. I.e., the register operand <tt>%a</tt> is
1381 both used and defined by the instruction.</p>
1385 <!-- _______________________________________________________________________ -->
1386 <div class="doc_subsubsection">
1387 <a name="regAlloc_ssaDecon">The SSA deconstruction phase</a>
1390 <div class="doc_text">
1392 <p>An important transformation that happens during register allocation is called
1393 the <i>SSA Deconstruction Phase</i>. The SSA form simplifies many
1394 analyses that are performed on the control flow graph of
1395 programs. However, traditional instruction sets do not implement
1396 PHI instructions. Thus, in order to generate executable code, compilers
1397 must replace PHI instructions with other instructions that preserve their
1400 <p>There are many ways in which PHI instructions can safely be removed
1401 from the target code. The most traditional PHI deconstruction
1402 algorithm replaces PHI instructions with copy instructions. That is
1403 the strategy adopted by LLVM. The SSA deconstruction algorithm is
1404 implemented in n<tt>lib/CodeGen/>PHIElimination.cpp</tt>. In order to
1405 invoke this pass, the identifier <tt>PHIEliminationID</tt> must be
1406 marked as required in the code of the register allocator.</p>
1410 <!-- _______________________________________________________________________ -->
1411 <div class="doc_subsubsection">
1412 <a name="regAlloc_fold">Instruction folding</a>
1415 <div class="doc_text">
1417 <p><i>Instruction folding</i> is an optimization performed during
1418 register allocation that removes unnecessary copy instructions. For
1419 instance, a sequence of instructions such as:</p>
1421 <div class="doc_code">
1423 %EBX = LOAD %mem_address
1428 <p>can be safely substituted by the single instruction:
1430 <div class="doc_code">
1432 %EAX = LOAD %mem_address
1436 <p>Instructions can be folded with the
1437 <tt>MRegisterInfo::foldMemoryOperand(...)</tt> method. Care must be
1438 taken when folding instructions; a folded instruction can be quite
1439 different from the original instruction. See
1440 <tt>LiveIntervals::addIntervalsForSpills</tt> in
1441 <tt>lib/CodeGen/LiveIntervalAnalysis.cpp</tt> for an example of its use.</p>
1445 <!-- _______________________________________________________________________ -->
1447 <div class="doc_subsubsection">
1448 <a name="regAlloc_builtIn">Built in register allocators</a>
1451 <div class="doc_text">
1453 <p>The LLVM infrastructure provides the application developer with
1454 three different register allocators:</p>
1457 <li><i>Simple</i> - This is a very simple implementation that does
1458 not keep values in registers across instructions. This register
1459 allocator immediately spills every value right after it is
1460 computed, and reloads all used operands from memory to temporary
1461 registers before each instruction.</li>
1462 <li><i>Local</i> - This register allocator is an improvement on the
1463 <i>Simple</i> implementation. It allocates registers on a basic
1464 block level, attempting to keep values in registers and reusing
1465 registers as appropriate.</li>
1466 <li><i>Linear Scan</i> - <i>The default allocator</i>. This is the
1467 well-know linear scan register allocator. Whereas the
1468 <i>Simple</i> and <i>Local</i> algorithms use a direct mapping
1469 implementation technique, the <i>Linear Scan</i> implementation
1470 uses a spiller in order to place load and stores.</li>
1473 <p>The type of register allocator used in <tt>llc</tt> can be chosen with the
1474 command line option <tt>-regalloc=...</tt>:</p>
1476 <div class="doc_code">
1478 $ llc -f -regalloc=simple file.bc -o sp.s;
1479 $ llc -f -regalloc=local file.bc -o lc.s;
1480 $ llc -f -regalloc=linearscan file.bc -o ln.s;
1486 <!-- ======================================================================= -->
1487 <div class="doc_subsection">
1488 <a name="proepicode">Prolog/Epilog Code Insertion</a>
1490 <div class="doc_text"><p>To Be Written</p></div>
1491 <!-- ======================================================================= -->
1492 <div class="doc_subsection">
1493 <a name="latemco">Late Machine Code Optimizations</a>
1495 <div class="doc_text"><p>To Be Written</p></div>
1496 <!-- ======================================================================= -->
1497 <div class="doc_subsection">
1498 <a name="codeemit">Code Emission</a>
1500 <div class="doc_text"><p>To Be Written</p></div>
1501 <!-- _______________________________________________________________________ -->
1502 <div class="doc_subsubsection">
1503 <a name="codeemit_asm">Generating Assembly Code</a>
1505 <div class="doc_text"><p>To Be Written</p></div>
1506 <!-- _______________________________________________________________________ -->
1507 <div class="doc_subsubsection">
1508 <a name="codeemit_bin">Generating Binary Machine Code</a>
1511 <div class="doc_text">
1512 <p>For the JIT or <tt>.o</tt> file writer</p>
1516 <!-- *********************************************************************** -->
1517 <div class="doc_section">
1518 <a name="targetimpls">Target-specific Implementation Notes</a>
1520 <!-- *********************************************************************** -->
1522 <div class="doc_text">
1524 <p>This section of the document explains features or design decisions that
1525 are specific to the code generator for a particular target.</p>
1530 <!-- ======================================================================= -->
1531 <div class="doc_subsection">
1532 <a name="x86">The X86 backend</a>
1535 <div class="doc_text">
1537 <p>The X86 code generator lives in the <tt>lib/Target/X86</tt> directory. This
1538 code generator currently targets a generic P6-like processor. As such, it
1539 produces a few P6-and-above instructions (like conditional moves), but it does
1540 not make use of newer features like MMX or SSE. In the future, the X86 backend
1541 will have sub-target support added for specific processor families and
1542 implementations.</p>
1546 <!-- _______________________________________________________________________ -->
1547 <div class="doc_subsubsection">
1548 <a name="x86_tt">X86 Target Triples Supported</a>
1551 <div class="doc_text">
1553 <p>The following are the known target triples that are supported by the X86
1554 backend. This is not an exhaustive list, and it would be useful to add those
1555 that people test.</p>
1558 <li><b>i686-pc-linux-gnu</b> - Linux</li>
1559 <li><b>i386-unknown-freebsd5.3</b> - FreeBSD 5.3</li>
1560 <li><b>i686-pc-cygwin</b> - Cygwin on Win32</li>
1561 <li><b>i686-pc-mingw32</b> - MingW on Win32</li>
1562 <li><b>i686-apple-darwin*</b> - Apple Darwin on X86</li>
1567 <!-- _______________________________________________________________________ -->
1568 <div class="doc_subsubsection">
1569 <a name="x86_memory">Representing X86 addressing modes in MachineInstrs</a>
1572 <div class="doc_text">
1574 <p>The x86 has a very flexible way of accessing memory. It is capable of
1575 forming memory addresses of the following expression directly in integer
1576 instructions (which use ModR/M addressing):</p>
1578 <div class="doc_code">
1580 Base + [1,2,4,8] * IndexReg + Disp32
1584 <p>In order to represent this, LLVM tracks no less than 4 operands for each
1585 memory operand of this form. This means that the "load" form of '<tt>mov</tt>'
1586 has the following <tt>MachineOperand</tt>s in this order:</p>
1590 Meaning: DestReg, | BaseReg, Scale, IndexReg, Displacement
1591 OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg, SignExtImm
1594 <p>Stores, and all other instructions, treat the four memory operands in the
1595 same way and in the same order.</p>
1599 <!-- _______________________________________________________________________ -->
1600 <div class="doc_subsubsection">
1601 <a name="x86_names">Instruction naming</a>
1604 <div class="doc_text">
1606 <p>An instruction name consists of the base name, a default operand size, and a
1607 a character per operand with an optional special size. For example:</p>
1610 <tt>ADD8rr</tt> -> add, 8-bit register, 8-bit register<br>
1611 <tt>IMUL16rmi</tt> -> imul, 16-bit register, 16-bit memory, 16-bit immediate<br>
1612 <tt>IMUL16rmi8</tt> -> imul, 16-bit register, 16-bit memory, 8-bit immediate<br>
1613 <tt>MOVSX32rm16</tt> -> movsx, 32-bit register, 16-bit memory
1618 <!-- *********************************************************************** -->
1621 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1622 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1623 <a href="http://validator.w3.org/check/referer"><img
1624 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /></a>
1626 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1627 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1628 Last modified: $Date$