First draft of the "Live Interval Analysis" section. This is the "Live
[oota-llvm.git] / docs / CodeGenerator.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5   <title>The LLVM Target-Independent Code Generator</title>
6   <link rel="stylesheet" href="llvm.css" type="text/css">
7 </head>
8 <body>
9
10 <div class="doc_title">
11   The LLVM Target-Independent Code Generator
12 </div>
13
14 <ol>
15   <li><a href="#introduction">Introduction</a>
16     <ul>
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
19           generator</a></li>
20       <li><a href="#tablegen">Using TableGen for target description</a></li>
21     </ul>
22   </li>
23   <li><a href="#targetdesc">Target description classes</a>
24     <ul>
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>
33     </ul>
34   </li>
35   <li><a href="#codegendesc">Machine code description classes</a>
36     <ul>
37     <li><a href="#machineinstr">The <tt>MachineInstr</tt> class</a></li>
38     <li><a href="#machinebasicblock">The <tt>MachineBasicBlock</tt>
39                                      class</a></li>
40     <li><a href="#machinefunction">The <tt>MachineFunction</tt> class</a></li>
41     </ul>
42   </li>
43   <li><a href="#codegenalgs">Target-independent code generation algorithms</a>
44     <ul>
45     <li><a href="#instselect">Instruction Selection</a>
46       <ul>
47       <li><a href="#selectiondag_intro">Introduction to SelectionDAGs</a></li>
48       <li><a href="#selectiondag_process">SelectionDAG Code Generation
49                                           Process</a></li>
50       <li><a href="#selectiondag_build">Initial SelectionDAG
51                                         Construction</a></li>
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
57                                         Phase</a></li>
58       <li><a href="#selectiondag_future">Future directions for the
59                                          SelectionDAG</a></li>
60       </ul></li>
61      <li><a href="#liveinterval_analysis">Live Interval Analysis</a>
62        <ul>
63        <li><a href="#livevariable_analysis">Live Variable Analysis</a></li>
64        </ul></li>
65     <li><a href="#regalloc">Register Allocation</a>
66       <ul>
67       <li><a href="#regAlloc_represent">How registers are represented in
68                                         LLVM</a></li>
69       <li><a href="#regAlloc_howTo">Mapping virtual registers to physical
70                                     registers</a></li>
71       <li><a href="#regAlloc_twoAddr">Handling two address instructions</a></li>
72       <li><a href="#regAlloc_ssaDecon">The SSA deconstruction phase</a></li>
73       <li><a href="#regAlloc_fold">Instruction folding</a></li>
74       <li><a href="#regAlloc_builtIn">Built in register allocators</a></li>
75       </ul></li>
76     <li><a href="#codeemit">Code Emission</a>
77         <ul>
78         <li><a href="#codeemit_asm">Generating Assembly Code</a></li>
79         <li><a href="#codeemit_bin">Generating Binary Machine Code</a></li>
80         </ul></li>
81     </ul>
82   </li>
83   <li><a href="#targetimpls">Target-specific Implementation Notes</a>
84     <ul>
85     <li><a href="#x86">The X86 backend</a></li>
86     </ul>
87   </li>
88
89 </ol>
90
91 <div class="doc_author">
92   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>,
93                 <a href="mailto:isanbard@gmail.com">Bill Wendling</a>, and
94                 <a href="mailto:pronesto@gmail.com">Fernando Magno Quintao
95                                                     Pereira</a></p>
96 </div>
97
98 <div class="doc_warning">
99   <p>Warning: This is a work in progress.</p>
100 </div>
101
102 <!-- *********************************************************************** -->
103 <div class="doc_section">
104   <a name="introduction">Introduction</a>
105 </div>
106 <!-- *********************************************************************** -->
107
108 <div class="doc_text">
109
110 <p>The LLVM target-independent code generator is a framework that provides a
111 suite of reusable components for translating the LLVM internal representation to
112 the machine code for a specified target&mdash;either in assembly form (suitable
113 for a static compiler) or in binary machine code format (usable for a JIT
114 compiler). The LLVM target-independent code generator consists of five main
115 components:</p>
116
117 <ol>
118 <li><a href="#targetdesc">Abstract target description</a> interfaces which
119 capture important properties about various aspects of the machine, independently
120 of how they will be used.  These interfaces are defined in
121 <tt>include/llvm/Target/</tt>.</li>
122
123 <li>Classes used to represent the <a href="#codegendesc">machine code</a> being
124 generated for a target.  These classes are intended to be abstract enough to
125 represent the machine code for <i>any</i> target machine.  These classes are
126 defined in <tt>include/llvm/CodeGen/</tt>.</li>
127
128 <li><a href="#codegenalgs">Target-independent algorithms</a> used to implement
129 various phases of native code generation (register allocation, scheduling, stack
130 frame representation, etc).  This code lives in <tt>lib/CodeGen/</tt>.</li>
131
132 <li><a href="#targetimpls">Implementations of the abstract target description
133 interfaces</a> for particular targets.  These machine descriptions make use of
134 the components provided by LLVM, and can optionally provide custom
135 target-specific passes, to build complete code generators for a specific target.
136 Target descriptions live in <tt>lib/Target/</tt>.</li>
137
138 <li><a href="#jit">The target-independent JIT components</a>.  The LLVM JIT is
139 completely target independent (it uses the <tt>TargetJITInfo</tt> structure to
140 interface for target-specific issues.  The code for the target-independent
141 JIT lives in <tt>lib/ExecutionEngine/JIT</tt>.</li>
142
143 </ol>
144
145 <p>
146 Depending on which part of the code generator you are interested in working on,
147 different pieces of this will be useful to you.  In any case, you should be
148 familiar with the <a href="#targetdesc">target description</a> and <a
149 href="#codegendesc">machine code representation</a> classes.  If you want to add
150 a backend for a new target, you will need to <a href="#targetimpls">implement the
151 target description</a> classes for your new target and understand the <a
152 href="LangRef.html">LLVM code representation</a>.  If you are interested in
153 implementing a new <a href="#codegenalgs">code generation algorithm</a>, it
154 should only depend on the target-description and machine code representation
155 classes, ensuring that it is portable.
156 </p>
157
158 </div>
159
160 <!-- ======================================================================= -->
161 <div class="doc_subsection">
162  <a name="required">Required components in the code generator</a>
163 </div>
164
165 <div class="doc_text">
166
167 <p>The two pieces of the LLVM code generator are the high-level interface to the
168 code generator and the set of reusable components that can be used to build
169 target-specific backends.  The two most important interfaces (<a
170 href="#targetmachine"><tt>TargetMachine</tt></a> and <a
171 href="#targetdata"><tt>TargetData</tt></a>) are the only ones that are
172 required to be defined for a backend to fit into the LLVM system, but the others
173 must be defined if the reusable code generator components are going to be
174 used.</p>
175
176 <p>This design has two important implications.  The first is that LLVM can
177 support completely non-traditional code generation targets.  For example, the C
178 backend does not require register allocation, instruction selection, or any of
179 the other standard components provided by the system.  As such, it only
180 implements these two interfaces, and does its own thing.  Another example of a
181 code generator like this is a (purely hypothetical) backend that converts LLVM
182 to the GCC RTL form and uses GCC to emit machine code for a target.</p>
183
184 <p>This design also implies that it is possible to design and
185 implement radically different code generators in the LLVM system that do not
186 make use of any of the built-in components.  Doing so is not recommended at all,
187 but could be required for radically different targets that do not fit into the
188 LLVM machine description model: FPGAs for example.</p>
189
190 </div>
191
192 <!-- ======================================================================= -->
193 <div class="doc_subsection">
194  <a name="high-level-design">The high-level design of the code generator</a>
195 </div>
196
197 <div class="doc_text">
198
199 <p>The LLVM target-independent code generator is designed to support efficient and
200 quality code generation for standard register-based microprocessors.  Code
201 generation in this model is divided into the following stages:</p>
202
203 <ol>
204 <li><b><a href="#instselect">Instruction Selection</a></b> - This phase
205 determines an efficient way to express the input LLVM code in the target
206 instruction set.
207 This stage produces the initial code for the program in the target instruction
208 set, then makes use of virtual registers in SSA form and physical registers that
209 represent any required register assignments due to target constraints or calling
210 conventions.  This step turns the LLVM code into a DAG of target
211 instructions.</li>
212
213 <li><b><a href="#selectiondag_sched">Scheduling and Formation</a></b> - This
214 phase takes the DAG of target instructions produced by the instruction selection
215 phase, determines an ordering of the instructions, then emits the instructions
216 as <tt><a href="#machineinstr">MachineInstr</a></tt>s with that ordering.  Note
217 that we describe this in the <a href="#instselect">instruction selection
218 section</a> because it operates on a <a
219 href="#selectiondag_intro">SelectionDAG</a>.
220 </li>
221
222 <li><b><a href="#ssamco">SSA-based Machine Code Optimizations</a></b> - This 
223 optional stage consists of a series of machine-code optimizations that 
224 operate on the SSA-form produced by the instruction selector.  Optimizations 
225 like modulo-scheduling or peephole optimization work here.
226 </li>
227
228 <li><b><a href="#regalloc">Register Allocation</a></b> - The
229 target code is transformed from an infinite virtual register file in SSA form 
230 to the concrete register file used by the target.  This phase introduces spill 
231 code and eliminates all virtual register references from the program.</li>
232
233 <li><b><a href="#proepicode">Prolog/Epilog Code Insertion</a></b> - Once the 
234 machine code has been generated for the function and the amount of stack space 
235 required is known (used for LLVM alloca's and spill slots), the prolog and 
236 epilog code for the function can be inserted and "abstract stack location 
237 references" can be eliminated.  This stage is responsible for implementing 
238 optimizations like frame-pointer elimination and stack packing.</li>
239
240 <li><b><a href="#latemco">Late Machine Code Optimizations</a></b> - Optimizations
241 that operate on "final" machine code can go here, such as spill code scheduling
242 and peephole optimizations.</li>
243
244 <li><b><a href="#codeemit">Code Emission</a></b> - The final stage actually 
245 puts out the code for the current function, either in the target assembler 
246 format or in machine code.</li>
247
248 </ol>
249
250 <p>The code generator is based on the assumption that the instruction selector
251 will use an optimal pattern matching selector to create high-quality sequences of
252 native instructions.  Alternative code generator designs based on pattern 
253 expansion and aggressive iterative peephole optimization are much slower.  This
254 design permits efficient compilation (important for JIT environments) and
255 aggressive optimization (used when generating code offline) by allowing 
256 components of varying levels of sophistication to be used for any step of 
257 compilation.</p>
258
259 <p>In addition to these stages, target implementations can insert arbitrary
260 target-specific passes into the flow.  For example, the X86 target uses a
261 special pass to handle the 80x87 floating point stack architecture.  Other
262 targets with unusual requirements can be supported with custom passes as
263 needed.</p>
264
265 </div>
266
267
268 <!-- ======================================================================= -->
269 <div class="doc_subsection">
270  <a name="tablegen">Using TableGen for target description</a>
271 </div>
272
273 <div class="doc_text">
274
275 <p>The target description classes require a detailed description of the target
276 architecture.  These target descriptions often have a large amount of common
277 information (e.g., an <tt>add</tt> instruction is almost identical to a 
278 <tt>sub</tt> instruction).
279 In order to allow the maximum amount of commonality to be factored out, the LLVM
280 code generator uses the <a href="TableGenFundamentals.html">TableGen</a> tool to
281 describe big chunks of the target machine, which allows the use of
282 domain-specific and target-specific abstractions to reduce the amount of 
283 repetition.</p>
284
285 <p>As LLVM continues to be developed and refined, we plan to move more and more
286 of the target description to the <tt>.td</tt> form.  Doing so gives us a
287 number of advantages.  The most important is that it makes it easier to port
288 LLVM because it reduces the amount of C++ code that has to be written, and the
289 surface area of the code generator that needs to be understood before someone
290 can get something working.  Second, it makes it easier to change things. In
291 particular, if tables and other things are all emitted by <tt>tblgen</tt>, we
292 only need a change in one place (<tt>tblgen</tt>) to update all of the targets
293 to a new interface.</p>
294
295 </div>
296
297 <!-- *********************************************************************** -->
298 <div class="doc_section">
299   <a name="targetdesc">Target description classes</a>
300 </div>
301 <!-- *********************************************************************** -->
302
303 <div class="doc_text">
304
305 <p>The LLVM target description classes (located in the
306 <tt>include/llvm/Target</tt> directory) provide an abstract description of the
307 target machine independent of any particular client.  These classes are
308 designed to capture the <i>abstract</i> properties of the target (such as the
309 instructions and registers it has), and do not incorporate any particular pieces
310 of code generation algorithms.</p>
311
312 <p>All of the target description classes (except the <tt><a
313 href="#targetdata">TargetData</a></tt> class) are designed to be subclassed by
314 the concrete target implementation, and have virtual methods implemented.  To
315 get to these implementations, the <tt><a
316 href="#targetmachine">TargetMachine</a></tt> class provides accessors that
317 should be implemented by the target.</p>
318
319 </div>
320
321 <!-- ======================================================================= -->
322 <div class="doc_subsection">
323   <a name="targetmachine">The <tt>TargetMachine</tt> class</a>
324 </div>
325
326 <div class="doc_text">
327
328 <p>The <tt>TargetMachine</tt> class provides virtual methods that are used to
329 access the target-specific implementations of the various target description
330 classes via the <tt>get*Info</tt> methods (<tt>getInstrInfo</tt>,
331 <tt>getRegisterInfo</tt>, <tt>getFrameInfo</tt>, etc.).  This class is 
332 designed to be specialized by
333 a concrete target implementation (e.g., <tt>X86TargetMachine</tt>) which
334 implements the various virtual methods.  The only required target description
335 class is the <a href="#targetdata"><tt>TargetData</tt></a> class, but if the
336 code generator components are to be used, the other interfaces should be
337 implemented as well.</p>
338
339 </div>
340
341
342 <!-- ======================================================================= -->
343 <div class="doc_subsection">
344   <a name="targetdata">The <tt>TargetData</tt> class</a>
345 </div>
346
347 <div class="doc_text">
348
349 <p>The <tt>TargetData</tt> class is the only required target description class,
350 and it is the only class that is not extensible (you cannot derived  a new 
351 class from it).  <tt>TargetData</tt> specifies information about how the target 
352 lays out memory for structures, the alignment requirements for various data 
353 types, the size of pointers in the target, and whether the target is 
354 little-endian or big-endian.</p>
355
356 </div>
357
358 <!-- ======================================================================= -->
359 <div class="doc_subsection">
360   <a name="targetlowering">The <tt>TargetLowering</tt> class</a>
361 </div>
362
363 <div class="doc_text">
364
365 <p>The <tt>TargetLowering</tt> class is used by SelectionDAG based instruction
366 selectors primarily to describe how LLVM code should be lowered to SelectionDAG
367 operations.  Among other things, this class indicates:</p>
368
369 <ul>
370   <li>an initial register class to use for various <tt>ValueType</tt>s</li>
371   <li>which operations are natively supported by the target machine</li>
372   <li>the return type of <tt>setcc</tt> operations</li>
373   <li>the type to use for shift amounts</li>
374   <li>various high-level characteristics, like whether it is profitable to turn
375       division by a constant into a multiplication sequence</li>
376 </ol>
377
378 </div>
379
380 <!-- ======================================================================= -->
381 <div class="doc_subsection">
382   <a name="mregisterinfo">The <tt>MRegisterInfo</tt> class</a>
383 </div>
384
385 <div class="doc_text">
386
387 <p>The <tt>MRegisterInfo</tt> class (which will eventually be renamed to
388 <tt>TargetRegisterInfo</tt>) is used to describe the register file of the
389 target and any interactions between the registers.</p>
390
391 <p>Registers in the code generator are represented in the code generator by
392 unsigned integers.  Physical registers (those that actually exist in the target
393 description) are unique small numbers, and virtual registers are generally
394 large.  Note that register #0 is reserved as a flag value.</p>
395
396 <p>Each register in the processor description has an associated
397 <tt>TargetRegisterDesc</tt> entry, which provides a textual name for the
398 register (used for assembly output and debugging dumps) and a set of aliases
399 (used to indicate whether one register overlaps with another).
400 </p>
401
402 <p>In addition to the per-register description, the <tt>MRegisterInfo</tt> class
403 exposes a set of processor specific register classes (instances of the
404 <tt>TargetRegisterClass</tt> class).  Each register class contains sets of
405 registers that have the same properties (for example, they are all 32-bit
406 integer registers).  Each SSA virtual register created by the instruction
407 selector has an associated register class.  When the register allocator runs, it
408 replaces virtual registers with a physical register in the set.</p>
409
410 <p>
411 The target-specific implementations of these classes is auto-generated from a <a
412 href="TableGenFundamentals.html">TableGen</a> description of the register file.
413 </p>
414
415 </div>
416
417 <!-- ======================================================================= -->
418 <div class="doc_subsection">
419   <a name="targetinstrinfo">The <tt>TargetInstrInfo</tt> class</a>
420 </div>
421
422 <div class="doc_text">
423   <p>The <tt>TargetInstrInfo</tt> class is used to describe the machine 
424   instructions supported by the target. It is essentially an array of 
425   <tt>TargetInstrDescriptor</tt> objects, each of which describes one
426   instruction the target supports. Descriptors define things like the mnemonic
427   for the opcode, the number of operands, the list of implicit register uses
428   and defs, whether the instruction has certain target-independent properties 
429   (accesses memory, is commutable, etc), and holds any target-specific
430   flags.</p>
431 </div>
432
433 <!-- ======================================================================= -->
434 <div class="doc_subsection">
435   <a name="targetframeinfo">The <tt>TargetFrameInfo</tt> class</a>
436 </div>
437
438 <div class="doc_text">
439   <p>The <tt>TargetFrameInfo</tt> class is used to provide information about the
440   stack frame layout of the target. It holds the direction of stack growth, 
441   the known stack alignment on entry to each function, and the offset to the 
442   local area.  The offset to the local area is the offset from the stack 
443   pointer on function entry to the first location where function data (local 
444   variables, spill locations) can be stored.</p>
445 </div>
446
447 <!-- ======================================================================= -->
448 <div class="doc_subsection">
449   <a name="targetsubtarget">The <tt>TargetSubtarget</tt> class</a>
450 </div>
451
452 <div class="doc_text">
453   <p>The <tt>TargetSubtarget</tt> class is used to provide information about the
454   specific chip set being targeted.  A sub-target informs code generation of 
455   which instructions are supported, instruction latencies and instruction 
456   execution itinerary; i.e., which processing units are used, in what order, and
457   for how long.</p>
458 </div>
459
460
461 <!-- ======================================================================= -->
462 <div class="doc_subsection">
463   <a name="targetjitinfo">The <tt>TargetJITInfo</tt> class</a>
464 </div>
465
466 <div class="doc_text">
467   <p>The <tt>TargetJITInfo</tt> class exposes an abstract interface used by the
468   Just-In-Time code generator to perform target-specific activities, such as
469   emitting stubs.  If a <tt>TargetMachine</tt> supports JIT code generation, it
470   should provide one of these objects through the <tt>getJITInfo</tt>
471   method.</p>
472 </div>
473
474 <!-- *********************************************************************** -->
475 <div class="doc_section">
476   <a name="codegendesc">Machine code description classes</a>
477 </div>
478 <!-- *********************************************************************** -->
479
480 <div class="doc_text">
481
482 <p>At the high-level, LLVM code is translated to a machine specific
483 representation formed out of
484 <a href="#machinefunction"><tt>MachineFunction</tt></a>,
485 <a href="#machinebasicblock"><tt>MachineBasicBlock</tt></a>, and <a 
486 href="#machineinstr"><tt>MachineInstr</tt></a> instances
487 (defined in <tt>include/llvm/CodeGen</tt>).  This representation is completely
488 target agnostic, representing instructions in their most abstract form: an
489 opcode and a series of operands.  This representation is designed to support
490 both an SSA representation for machine code, as well as a register allocated,
491 non-SSA form.</p>
492
493 </div>
494
495 <!-- ======================================================================= -->
496 <div class="doc_subsection">
497   <a name="machineinstr">The <tt>MachineInstr</tt> class</a>
498 </div>
499
500 <div class="doc_text">
501
502 <p>Target machine instructions are represented as instances of the
503 <tt>MachineInstr</tt> class.  This class is an extremely abstract way of
504 representing machine instructions.  In particular, it only keeps track of 
505 an opcode number and a set of operands.</p>
506
507 <p>The opcode number is a simple unsigned integer that only has meaning to a 
508 specific backend.  All of the instructions for a target should be defined in 
509 the <tt>*InstrInfo.td</tt> file for the target. The opcode enum values
510 are auto-generated from this description.  The <tt>MachineInstr</tt> class does
511 not have any information about how to interpret the instruction (i.e., what the 
512 semantics of the instruction are); for that you must refer to the 
513 <tt><a href="#targetinstrinfo">TargetInstrInfo</a></tt> class.</p> 
514
515 <p>The operands of a machine instruction can be of several different types:
516 a register reference, a constant integer, a basic block reference, etc.  In
517 addition, a machine operand should be marked as a def or a use of the value
518 (though only registers are allowed to be defs).</p>
519
520 <p>By convention, the LLVM code generator orders instruction operands so that
521 all register definitions come before the register uses, even on architectures
522 that are normally printed in other orders.  For example, the SPARC add 
523 instruction: "<tt>add %i1, %i2, %i3</tt>" adds the "%i1", and "%i2" registers
524 and stores the result into the "%i3" register.  In the LLVM code generator,
525 the operands should be stored as "<tt>%i3, %i1, %i2</tt>": with the destination
526 first.</p>
527
528 <p>Keeping destination (definition) operands at the beginning of the operand 
529 list has several advantages.  In particular, the debugging printer will print 
530 the instruction like this:</p>
531
532 <div class="doc_code">
533 <pre>
534 %r3 = add %i1, %i2
535 </pre>
536 </div>
537
538 <p>Also if the first operand is a def, it is easier to <a 
539 href="#buildmi">create instructions</a> whose only def is the first 
540 operand.</p>
541
542 </div>
543
544 <!-- _______________________________________________________________________ -->
545 <div class="doc_subsubsection">
546   <a name="buildmi">Using the <tt>MachineInstrBuilder.h</tt> functions</a>
547 </div>
548
549 <div class="doc_text">
550
551 <p>Machine instructions are created by using the <tt>BuildMI</tt> functions,
552 located in the <tt>include/llvm/CodeGen/MachineInstrBuilder.h</tt> file.  The
553 <tt>BuildMI</tt> functions make it easy to build arbitrary machine 
554 instructions.  Usage of the <tt>BuildMI</tt> functions look like this:</p>
555
556 <div class="doc_code">
557 <pre>
558 // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
559 // instruction.  The '1' specifies how many operands will be added.
560 MachineInstr *MI = BuildMI(X86::MOV32ri, 1, DestReg).addImm(42);
561
562 // Create the same instr, but insert it at the end of a basic block.
563 MachineBasicBlock &amp;MBB = ...
564 BuildMI(MBB, X86::MOV32ri, 1, DestReg).addImm(42);
565
566 // Create the same instr, but insert it before a specified iterator point.
567 MachineBasicBlock::iterator MBBI = ...
568 BuildMI(MBB, MBBI, X86::MOV32ri, 1, DestReg).addImm(42);
569
570 // Create a 'cmp Reg, 0' instruction, no destination reg.
571 MI = BuildMI(X86::CMP32ri, 2).addReg(Reg).addImm(0);
572 // Create an 'sahf' instruction which takes no operands and stores nothing.
573 MI = BuildMI(X86::SAHF, 0);
574
575 // Create a self looping branch instruction.
576 BuildMI(MBB, X86::JNE, 1).addMBB(&amp;MBB);
577 </pre>
578 </div>
579
580 <p>The key thing to remember with the <tt>BuildMI</tt> functions is that you
581 have to specify the number of operands that the machine instruction will take.
582 This allows for efficient memory allocation.  You also need to specify if
583 operands default to be uses of values, not definitions.  If you need to add a
584 definition operand (other than the optional destination register), you must
585 explicitly mark it as such:</p>
586
587 <div class="doc_code">
588 <pre>
589 MI.addReg(Reg, MachineOperand::Def);
590 </pre>
591 </div>
592
593 </div>
594
595 <!-- _______________________________________________________________________ -->
596 <div class="doc_subsubsection">
597   <a name="fixedregs">Fixed (preassigned) registers</a>
598 </div>
599
600 <div class="doc_text">
601
602 <p>One important issue that the code generator needs to be aware of is the
603 presence of fixed registers.  In particular, there are often places in the 
604 instruction stream where the register allocator <em>must</em> arrange for a
605 particular value to be in a particular register.  This can occur due to 
606 limitations of the instruction set (e.g., the X86 can only do a 32-bit divide 
607 with the <tt>EAX</tt>/<tt>EDX</tt> registers), or external factors like calling
608 conventions.  In any case, the instruction selector should emit code that 
609 copies a virtual register into or out of a physical register when needed.</p>
610
611 <p>For example, consider this simple LLVM example:</p>
612
613 <div class="doc_code">
614 <pre>
615 int %test(int %X, int %Y) {
616   %Z = div int %X, %Y
617   ret int %Z
618 }
619 </pre>
620 </div>
621
622 <p>The X86 instruction selector produces this machine code for the <tt>div</tt>
623 and <tt>ret</tt> (use 
624 "<tt>llc X.bc -march=x86 -print-machineinstrs</tt>" to get this):</p>
625
626 <div class="doc_code">
627 <pre>
628 ;; Start of div
629 %EAX = mov %reg1024           ;; Copy X (in reg1024) into EAX
630 %reg1027 = sar %reg1024, 31
631 %EDX = mov %reg1027           ;; Sign extend X into EDX
632 idiv %reg1025                 ;; Divide by Y (in reg1025)
633 %reg1026 = mov %EAX           ;; Read the result (Z) out of EAX
634
635 ;; Start of ret
636 %EAX = mov %reg1026           ;; 32-bit return value goes in EAX
637 ret
638 </pre>
639 </div>
640
641 <p>By the end of code generation, the register allocator has coalesced
642 the registers and deleted the resultant identity moves producing the
643 following code:</p>
644
645 <div class="doc_code">
646 <pre>
647 ;; X is in EAX, Y is in ECX
648 mov %EAX, %EDX
649 sar %EDX, 31
650 idiv %ECX
651 ret 
652 </pre>
653 </div>
654
655 <p>This approach is extremely general (if it can handle the X86 architecture, 
656 it can handle anything!) and allows all of the target specific
657 knowledge about the instruction stream to be isolated in the instruction 
658 selector.  Note that physical registers should have a short lifetime for good 
659 code generation, and all physical registers are assumed dead on entry to and
660 exit from basic blocks (before register allocation).  Thus, if you need a value
661 to be live across basic block boundaries, it <em>must</em> live in a virtual 
662 register.</p>
663
664 </div>
665
666 <!-- _______________________________________________________________________ -->
667 <div class="doc_subsubsection">
668   <a name="ssa">Machine code in SSA form</a>
669 </div>
670
671 <div class="doc_text">
672
673 <p><tt>MachineInstr</tt>'s are initially selected in SSA-form, and
674 are maintained in SSA-form until register allocation happens.  For the most 
675 part, this is trivially simple since LLVM is already in SSA form; LLVM PHI nodes
676 become machine code PHI nodes, and virtual registers are only allowed to have a
677 single definition.</p>
678
679 <p>After register allocation, machine code is no longer in SSA-form because there 
680 are no virtual registers left in the code.</p>
681
682 </div>
683
684 <!-- ======================================================================= -->
685 <div class="doc_subsection">
686   <a name="machinebasicblock">The <tt>MachineBasicBlock</tt> class</a>
687 </div>
688
689 <div class="doc_text">
690
691 <p>The <tt>MachineBasicBlock</tt> class contains a list of machine instructions
692 (<tt><a href="#machineinstr">MachineInstr</a></tt> instances).  It roughly
693 corresponds to the LLVM code input to the instruction selector, but there can be
694 a one-to-many mapping (i.e. one LLVM basic block can map to multiple machine
695 basic blocks). The <tt>MachineBasicBlock</tt> class has a
696 "<tt>getBasicBlock</tt>" method, which returns the LLVM basic block that it
697 comes from.</p>
698
699 </div>
700
701 <!-- ======================================================================= -->
702 <div class="doc_subsection">
703   <a name="machinefunction">The <tt>MachineFunction</tt> class</a>
704 </div>
705
706 <div class="doc_text">
707
708 <p>The <tt>MachineFunction</tt> class contains a list of machine basic blocks
709 (<tt><a href="#machinebasicblock">MachineBasicBlock</a></tt> instances).  It
710 corresponds one-to-one with the LLVM function input to the instruction selector.
711 In addition to a list of basic blocks, the <tt>MachineFunction</tt> contains a
712 a <tt>MachineConstantPool</tt>, a <tt>MachineFrameInfo</tt>, a
713 <tt>MachineFunctionInfo</tt>, a <tt>SSARegMap</tt>, and a set of live in and
714 live out registers for the function.  See
715 <tt>include/llvm/CodeGen/MachineFunction.h</tt> for more information.</p>
716
717 </div>
718
719 <!-- *********************************************************************** -->
720 <div class="doc_section">
721   <a name="codegenalgs">Target-independent code generation algorithms</a>
722 </div>
723 <!-- *********************************************************************** -->
724
725 <div class="doc_text">
726
727 <p>This section documents the phases described in the <a
728 href="#high-level-design">high-level design of the code generator</a>.  It
729 explains how they work and some of the rationale behind their design.</p>
730
731 </div>
732
733 <!-- ======================================================================= -->
734 <div class="doc_subsection">
735   <a name="instselect">Instruction Selection</a>
736 </div>
737
738 <div class="doc_text">
739 <p>
740 Instruction Selection is the process of translating LLVM code presented to the
741 code generator into target-specific machine instructions.  There are several
742 well-known ways to do this in the literature.  In LLVM there are two main forms:
743 the SelectionDAG based instruction selector framework and an old-style 'simple'
744 instruction selector, which effectively peephole selects each LLVM instruction
745 into a series of machine instructions.  We recommend that all targets use the
746 SelectionDAG infrastructure.
747 </p>
748
749 <p>Portions of the DAG instruction selector are generated from the target 
750 description (<tt>*.td</tt>) files.  Our goal is for the entire instruction
751 selector to be generated from these <tt>.td</tt> files.</p>
752 </div>
753
754 <!-- _______________________________________________________________________ -->
755 <div class="doc_subsubsection">
756   <a name="selectiondag_intro">Introduction to SelectionDAGs</a>
757 </div>
758
759 <div class="doc_text">
760
761 <p>The SelectionDAG provides an abstraction for code representation in a way
762 that is amenable to instruction selection using automatic techniques
763 (e.g. dynamic-programming based optimal pattern matching selectors). It is also
764 well-suited to other phases of code generation; in particular,
765 instruction scheduling (SelectionDAG's are very close to scheduling DAGs
766 post-selection).  Additionally, the SelectionDAG provides a host representation
767 where a large variety of very-low-level (but target-independent) 
768 <a href="#selectiondag_optimize">optimizations</a> may be
769 performed; ones which require extensive information about the instructions
770 efficiently supported by the target.</p>
771
772 <p>The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the
773 <tt>SDNode</tt> class.  The primary payload of the <tt>SDNode</tt> is its 
774 operation code (Opcode) that indicates what operation the node performs and
775 the operands to the operation.
776 The various operation node types are described at the top of the
777 <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt> file.</p>
778
779 <p>Although most operations define a single value, each node in the graph may 
780 define multiple values.  For example, a combined div/rem operation will define
781 both the dividend and the remainder. Many other situations require multiple
782 values as well.  Each node also has some number of operands, which are edges 
783 to the node defining the used value.  Because nodes may define multiple values,
784 edges are represented by instances of the <tt>SDOperand</tt> class, which is 
785 a <tt>&lt;SDNode, unsigned&gt;</tt> pair, indicating the node and result
786 value being used, respectively.  Each value produced by an <tt>SDNode</tt> has
787 an associated <tt>MVT::ValueType</tt> indicating what type the value is.</p>
788
789 <p>SelectionDAGs contain two different kinds of values: those that represent
790 data flow and those that represent control flow dependencies.  Data values are
791 simple edges with an integer or floating point value type.  Control edges are
792 represented as "chain" edges which are of type <tt>MVT::Other</tt>.  These edges
793 provide an ordering between nodes that have side effects (such as
794 loads, stores, calls, returns, etc).  All nodes that have side effects should
795 take a token chain as input and produce a new one as output.  By convention,
796 token chain inputs are always operand #0, and chain results are always the last
797 value produced by an operation.</p>
798
799 <p>A SelectionDAG has designated "Entry" and "Root" nodes.  The Entry node is
800 always a marker node with an Opcode of <tt>ISD::EntryToken</tt>.  The Root node
801 is the final side-effecting node in the token chain. For example, in a single
802 basic block function it would be the return node.</p>
803
804 <p>One important concept for SelectionDAGs is the notion of a "legal" vs.
805 "illegal" DAG.  A legal DAG for a target is one that only uses supported
806 operations and supported types.  On a 32-bit PowerPC, for example, a DAG with
807 a value of type i1, i8, i16, or i64 would be illegal, as would a DAG that uses a
808 SREM or UREM operation.  The
809 <a href="#selectiondag_legalize">legalize</a> phase is responsible for turning
810 an illegal DAG into a legal DAG.</p>
811
812 </div>
813
814 <!-- _______________________________________________________________________ -->
815 <div class="doc_subsubsection">
816   <a name="selectiondag_process">SelectionDAG Instruction Selection Process</a>
817 </div>
818
819 <div class="doc_text">
820
821 <p>SelectionDAG-based instruction selection consists of the following steps:</p>
822
823 <ol>
824 <li><a href="#selectiondag_build">Build initial DAG</a> - This stage
825     performs a simple translation from the input LLVM code to an illegal
826     SelectionDAG.</li>
827 <li><a href="#selectiondag_optimize">Optimize SelectionDAG</a> - This stage
828     performs simple optimizations on the SelectionDAG to simplify it, and
829     recognize meta instructions (like rotates and <tt>div</tt>/<tt>rem</tt>
830     pairs) for targets that support these meta operations.  This makes the
831     resultant code more efficient and the <a href="#selectiondag_select">select
832     instructions from DAG</a> phase (below) simpler.</li>
833 <li><a href="#selectiondag_legalize">Legalize SelectionDAG</a> - This stage
834     converts the illegal SelectionDAG to a legal SelectionDAG by eliminating
835     unsupported operations and data types.</li>
836 <li><a href="#selectiondag_optimize">Optimize SelectionDAG (#2)</a> - This
837     second run of the SelectionDAG optimizes the newly legalized DAG to
838     eliminate inefficiencies introduced by legalization.</li>
839 <li><a href="#selectiondag_select">Select instructions from DAG</a> - Finally,
840     the target instruction selector matches the DAG operations to target
841     instructions.  This process translates the target-independent input DAG into
842     another DAG of target instructions.</li>
843 <li><a href="#selectiondag_sched">SelectionDAG Scheduling and Formation</a>
844     - The last phase assigns a linear order to the instructions in the 
845     target-instruction DAG and emits them into the MachineFunction being
846     compiled.  This step uses traditional prepass scheduling techniques.</li>
847 </ol>
848
849 <p>After all of these steps are complete, the SelectionDAG is destroyed and the
850 rest of the code generation passes are run.</p>
851
852 <p>One great way to visualize what is going on here is to take advantage of a 
853 few LLC command line options.  In particular, the <tt>-view-isel-dags</tt>
854 option pops up a window with the SelectionDAG input to the Select phase for all
855 of the code compiled (if you only get errors printed to the console while using
856 this, you probably <a href="ProgrammersManual.html#ViewGraph">need to configure
857 your system</a> to add support for it).  The <tt>-view-sched-dags</tt> option
858 views the SelectionDAG output from the Select phase and input to the Scheduler
859 phase.</p>
860
861 </div>
862
863 <!-- _______________________________________________________________________ -->
864 <div class="doc_subsubsection">
865   <a name="selectiondag_build">Initial SelectionDAG Construction</a>
866 </div>
867
868 <div class="doc_text">
869
870 <p>The initial SelectionDAG is na&iuml;vely peephole expanded from the LLVM
871 input by the <tt>SelectionDAGLowering</tt> class in the
872 <tt>lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp</tt> file.  The intent of this
873 pass is to expose as much low-level, target-specific details to the SelectionDAG
874 as possible.  This pass is mostly hard-coded (e.g. an LLVM <tt>add</tt> turns
875 into an <tt>SDNode add</tt> while a <tt>geteelementptr</tt> is expanded into the
876 obvious arithmetic). This pass requires target-specific hooks to lower calls,
877 returns, varargs, etc.  For these features, the
878 <tt><a href="#targetlowering">TargetLowering</a></tt> interface is used.</p>
879
880 </div>
881
882 <!-- _______________________________________________________________________ -->
883 <div class="doc_subsubsection">
884   <a name="selectiondag_legalize">SelectionDAG Legalize Phase</a>
885 </div>
886
887 <div class="doc_text">
888
889 <p>The Legalize phase is in charge of converting a DAG to only use the types and
890 operations that are natively supported by the target.  This involves two major
891 tasks:</p>
892
893 <ol>
894 <li><p>Convert values of unsupported types to values of supported types.</p>
895     <p>There are two main ways of doing this: converting small types to 
896        larger types ("promoting"), and breaking up large integer types
897        into smaller ones ("expanding").  For example, a target might require
898        that all f32 values are promoted to f64 and that all i1/i8/i16 values
899        are promoted to i32.  The same target might require that all i64 values
900        be expanded into i32 values.  These changes can insert sign and zero
901        extensions as needed to make sure that the final code has the same
902        behavior as the input.</p>
903     <p>A target implementation tells the legalizer which types are supported
904        (and which register class to use for them) by calling the
905        <tt>addRegisterClass</tt> method in its TargetLowering constructor.</p>
906 </li>
907
908 <li><p>Eliminate operations that are not supported by the target.</p>
909     <p>Targets often have weird constraints, such as not supporting every
910        operation on every supported datatype (e.g. X86 does not support byte
911        conditional moves and PowerPC does not support sign-extending loads from
912        a 16-bit memory location).  Legalize takes care of this by open-coding
913        another sequence of operations to emulate the operation ("expansion"), by
914        promoting one type to a larger type that supports the operation
915        ("promotion"), or by using a target-specific hook to implement the
916        legalization ("custom").</p>
917     <p>A target implementation tells the legalizer which operations are not
918        supported (and which of the above three actions to take) by calling the
919        <tt>setOperationAction</tt> method in its <tt>TargetLowering</tt>
920        constructor.</p>
921 </li>
922 </ol>
923
924 <p>Prior to the existance of the Legalize pass, we required that every target
925 <a href="#selectiondag_optimize">selector</a> supported and handled every
926 operator and type even if they are not natively supported.  The introduction of
927 the Legalize phase allows all of the cannonicalization patterns to be shared
928 across targets, and makes it very easy to optimize the cannonicalized code
929 because it is still in the form of a DAG.</p>
930
931 </div>
932
933 <!-- _______________________________________________________________________ -->
934 <div class="doc_subsubsection">
935   <a name="selectiondag_optimize">SelectionDAG Optimization Phase: the DAG
936   Combiner</a>
937 </div>
938
939 <div class="doc_text">
940
941 <p>The SelectionDAG optimization phase is run twice for code generation: once
942 immediately after the DAG is built and once after legalization.  The first run
943 of the pass allows the initial code to be cleaned up (e.g. performing 
944 optimizations that depend on knowing that the operators have restricted type 
945 inputs).  The second run of the pass cleans up the messy code generated by the 
946 Legalize pass, which allows Legalize to be very simple (it can focus on making
947 code legal instead of focusing on generating <em>good</em> and legal code).</p>
948
949 <p>One important class of optimizations performed is optimizing inserted sign
950 and zero extension instructions.  We currently use ad-hoc techniques, but could
951 move to more rigorous techniques in the future.  Here are some good papers on
952 the subject:</p>
953
954 <p>
955  "<a href="http://www.eecs.harvard.edu/~nr/pubs/widen-abstract.html">Widening
956  integer arithmetic</a>"<br>
957  Kevin Redwine and Norman Ramsey<br>
958  International Conference on Compiler Construction (CC) 2004
959 </p>
960
961
962 <p>
963  "<a href="http://portal.acm.org/citation.cfm?doid=512529.512552">Effective
964  sign extension elimination</a>"<br>
965  Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani<br>
966  Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design
967  and Implementation.
968 </p>
969
970 </div>
971
972 <!-- _______________________________________________________________________ -->
973 <div class="doc_subsubsection">
974   <a name="selectiondag_select">SelectionDAG Select Phase</a>
975 </div>
976
977 <div class="doc_text">
978
979 <p>The Select phase is the bulk of the target-specific code for instruction
980 selection.  This phase takes a legal SelectionDAG as input, pattern matches the
981 instructions supported by the target to this DAG, and produces a new DAG of
982 target code.  For example, consider the following LLVM fragment:</p>
983
984 <div class="doc_code">
985 <pre>
986 %t1 = add float %W, %X
987 %t2 = mul float %t1, %Y
988 %t3 = add float %t2, %Z
989 </pre>
990 </div>
991
992 <p>This LLVM code corresponds to a SelectionDAG that looks basically like
993 this:</p>
994
995 <div class="doc_code">
996 <pre>
997 (fadd:f32 (fmul:f32 (fadd:f32 W, X), Y), Z)
998 </pre>
999 </div>
1000
1001 <p>If a target supports floating point multiply-and-add (FMA) operations, one
1002 of the adds can be merged with the multiply.  On the PowerPC, for example, the
1003 output of the instruction selector might look like this DAG:</p>
1004
1005 <div class="doc_code">
1006 <pre>
1007 (FMADDS (FADDS W, X), Y, Z)
1008 </pre>
1009 </div>
1010
1011 <p>The <tt>FMADDS</tt> instruction is a ternary instruction that multiplies its
1012 first two operands and adds the third (as single-precision floating-point
1013 numbers).  The <tt>FADDS</tt> instruction is a simple binary single-precision
1014 add instruction.  To perform this pattern match, the PowerPC backend includes
1015 the following instruction definitions:</p>
1016
1017 <div class="doc_code">
1018 <pre>
1019 def FMADDS : AForm_1&lt;59, 29,
1020                     (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRC, F4RC:$FRB),
1021                     "fmadds $FRT, $FRA, $FRC, $FRB",
1022                     [<b>(set F4RC:$FRT, (fadd (fmul F4RC:$FRA, F4RC:$FRC),
1023                                            F4RC:$FRB))</b>]&gt;;
1024 def FADDS : AForm_2&lt;59, 21,
1025                     (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRB),
1026                     "fadds $FRT, $FRA, $FRB",
1027                     [<b>(set F4RC:$FRT, (fadd F4RC:$FRA, F4RC:$FRB))</b>]&gt;;
1028 </pre>
1029 </div>
1030
1031 <p>The portion of the instruction definition in bold indicates the pattern used
1032 to match the instruction.  The DAG operators (like <tt>fmul</tt>/<tt>fadd</tt>)
1033 are defined in the <tt>lib/Target/TargetSelectionDAG.td</tt> file.  
1034 "<tt>F4RC</tt>" is the register class of the input and result values.<p>
1035
1036 <p>The TableGen DAG instruction selector generator reads the instruction 
1037 patterns in the <tt>.td</tt> file and automatically builds parts of the pattern
1038 matching code for your target.  It has the following strengths:</p>
1039
1040 <ul>
1041 <li>At compiler-compiler time, it analyzes your instruction patterns and tells
1042     you if your patterns make sense or not.</li>
1043 <li>It can handle arbitrary constraints on operands for the pattern match.  In
1044     particular, it is straight-forward to say things like "match any immediate
1045     that is a 13-bit sign-extended value".  For examples, see the 
1046     <tt>immSExt16</tt> and related <tt>tblgen</tt> classes in the PowerPC
1047     backend.</li>
1048 <li>It knows several important identities for the patterns defined.  For
1049     example, it knows that addition is commutative, so it allows the 
1050     <tt>FMADDS</tt> pattern above to match "<tt>(fadd X, (fmul Y, Z))</tt>" as
1051     well as "<tt>(fadd (fmul X, Y), Z)</tt>", without the target author having
1052     to specially handle this case.</li>
1053 <li>It has a full-featured type-inferencing system.  In particular, you should
1054     rarely have to explicitly tell the system what type parts of your patterns
1055     are.  In the <tt>FMADDS</tt> case above, we didn't have to tell
1056     <tt>tblgen</tt> that all of the nodes in the pattern are of type 'f32'.  It
1057     was able to infer and propagate this knowledge from the fact that
1058     <tt>F4RC</tt> has type 'f32'.</li>
1059 <li>Targets can define their own (and rely on built-in) "pattern fragments".
1060     Pattern fragments are chunks of reusable patterns that get inlined into your
1061     patterns during compiler-compiler time.  For example, the integer
1062     "<tt>(not x)</tt>" operation is actually defined as a pattern fragment that
1063     expands as "<tt>(xor x, -1)</tt>", since the SelectionDAG does not have a
1064     native '<tt>not</tt>' operation.  Targets can define their own short-hand
1065     fragments as they see fit.  See the definition of '<tt>not</tt>' and
1066     '<tt>ineg</tt>' for examples.</li>
1067 <li>In addition to instructions, targets can specify arbitrary patterns that
1068     map to one or more instructions using the 'Pat' class.  For example,
1069     the PowerPC has no way to load an arbitrary integer immediate into a
1070     register in one instruction. To tell tblgen how to do this, it defines:
1071     <br>
1072     <br>
1073     <div class="doc_code">
1074     <pre>
1075 // Arbitrary immediate support.  Implement in terms of LIS/ORI.
1076 def : Pat&lt;(i32 imm:$imm),
1077           (ORI (LIS (HI16 imm:$imm)), (LO16 imm:$imm))&gt;;
1078     </pre>
1079     </div>
1080     <br>    
1081     If none of the single-instruction patterns for loading an immediate into a
1082     register match, this will be used.  This rule says "match an arbitrary i32
1083     immediate, turning it into an <tt>ORI</tt> ('or a 16-bit immediate') and an
1084     <tt>LIS</tt> ('load 16-bit immediate, where the immediate is shifted to the
1085     left 16 bits') instruction".  To make this work, the
1086     <tt>LO16</tt>/<tt>HI16</tt> node transformations are used to manipulate the
1087     input immediate (in this case, take the high or low 16-bits of the
1088     immediate).</li>
1089 <li>While the system does automate a lot, it still allows you to write custom
1090     C++ code to match special cases if there is something that is hard to
1091     express.</li>
1092 </ul>
1093
1094 <p>While it has many strengths, the system currently has some limitations,
1095 primarily because it is a work in progress and is not yet finished:</p>
1096
1097 <ul>
1098 <li>Overall, there is no way to define or match SelectionDAG nodes that define
1099     multiple values (e.g. <tt>ADD_PARTS</tt>, <tt>LOAD</tt>, <tt>CALL</tt>,
1100     etc).  This is the biggest reason that you currently still <em>have to</em>
1101     write custom C++ code for your instruction selector.</li>
1102 <li>There is no great way to support matching complex addressing modes yet.  In
1103     the future, we will extend pattern fragments to allow them to define
1104     multiple values (e.g. the four operands of the <a href="#x86_memory">X86
1105     addressing mode</a>).  In addition, we'll extend fragments so that a
1106     fragment can match multiple different patterns.</li>
1107 <li>We don't automatically infer flags like isStore/isLoad yet.</li>
1108 <li>We don't automatically generate the set of supported registers and
1109     operations for the <a href="#"selectiondag_legalize>Legalizer</a> yet.</li>
1110 <li>We don't have a way of tying in custom legalized nodes yet.</li>
1111 </ul>
1112
1113 <p>Despite these limitations, the instruction selector generator is still quite
1114 useful for most of the binary and logical operations in typical instruction
1115 sets.  If you run into any problems or can't figure out how to do something, 
1116 please let Chris know!</p>
1117
1118 </div>
1119
1120 <!-- _______________________________________________________________________ -->
1121 <div class="doc_subsubsection">
1122   <a name="selectiondag_sched">SelectionDAG Scheduling and Formation Phase</a>
1123 </div>
1124
1125 <div class="doc_text">
1126
1127 <p>The scheduling phase takes the DAG of target instructions from the selection
1128 phase and assigns an order.  The scheduler can pick an order depending on
1129 various constraints of the machines (i.e. order for minimal register pressure or
1130 try to cover instruction latencies).  Once an order is established, the DAG is
1131 converted to a list of <tt><a href="#machineinstr">MachineInstr</a></tt>s and
1132 the SelectionDAG is destroyed.</p>
1133
1134 <p>Note that this phase is logically separate from the instruction selection
1135 phase, but is tied to it closely in the code because it operates on
1136 SelectionDAGs.</p>
1137
1138 </div>
1139
1140 <!-- _______________________________________________________________________ -->
1141 <div class="doc_subsubsection">
1142   <a name="selectiondag_future">Future directions for the SelectionDAG</a>
1143 </div>
1144
1145 <div class="doc_text">
1146
1147 <ol>
1148 <li>Optional function-at-a-time selection.</li>
1149 <li>Auto-generate entire selector from <tt>.td</tt> file.</li>
1150 </li>
1151 </ol>
1152
1153 </div>
1154  
1155 <!-- ======================================================================= -->
1156 <div class="doc_subsection">
1157   <a name="ssamco">SSA-based Machine Code Optimizations</a>
1158 </div>
1159 <div class="doc_text"><p>To Be Written</p></div>
1160
1161 <!-- ======================================================================= -->
1162 <div class="doc_subsection">
1163   <a name="liveinterval_analysis">Live Interval Analysis</a>
1164 </div>
1165
1166 <div class="doc_text">
1167
1168 <p>Live Interval Analysis identifies the ranges where a variable is <i>live</i>.
1169 It's used by the <a href="#regalloc">register allocator pass</a> to determine
1170 if two or more virtual registers which require the same register are live at
1171 the same point in the program (conflict). When this situation occurs, one
1172 virtual register must be <i>spilt</i>.</p>
1173
1174 </div>
1175
1176 <!-- _______________________________________________________________________ -->
1177 <div class="doc_subsubsection">
1178   <a name="livevariable_analysis">Live Variable Analysis</a>
1179 </div>
1180
1181 <div class="doc_text">
1182
1183 <p>The first step to determining the live intervals of variables is to
1184 calculate the set of registers that are immediately dead after the
1185 instruction (i.e., the instruction calculates the value, but it is never
1186 used) and the set of registers that are used by the instruction, but are
1187 never used after the instruction (i.e., they are killed). Live variable
1188 information is computed for each <i>virtual</i> and <i>register
1189 allocatable</i> physical register in the function.  LLVM assumes that
1190 physical registers are only live within a single basic block.  This allows
1191 it to do a single, local analysis to resolve physical register lifetimes in
1192 each basic block. If a physical register is not register allocatable (e.g.,
1193 a stack pointer or condition codes), it is not tracked.</p>
1194
1195 <p>Physical registers may be live in to or out of a function. Live in values
1196 are typically arguments in register. Live out values are typically return
1197 values in registers. Live in values are marked as such, and are given a dummy
1198 "defining" instruction during live interval analysis. If the last basic block
1199 of a function is a <tt>return</tt>, then it's marked as using all live-out
1200 values in the function.</p>
1201
1202 <p><tt>PHI</tt> nodes need to be handled specially, because the calculation
1203 of the live variable information from a depth first traversal of the CFG of
1204 the function won't guarantee that a virtual register is defined before it's
1205 used. When a <tt>PHI</tt> node is encounted, only the definition is
1206 handled, because the uses will be handled in other basic blocks.</p>
1207
1208 <p>For each <tt>PHI</tt> node of the current basic block, we simulate an
1209 assignment at the end of the current basic block and traverse the successor
1210 basic blocks. If a successor basic block has a <tt>PHI</tt> node and one of
1211 the <tt>PHI</tt> node's operands is coming from the current basic block,
1212 then the variable is marked as <i>alive</i> within the current basic block
1213 and all of its predecessor basic blocks, until the basic block with the
1214 defining instruction is encountered.</p>
1215
1216 </div>
1217
1218 <!-- FIXME:
1219
1220 A. General Overview
1221 B. Describe Default RA (Linear Scan)
1222    1. LiveVariable Analysis
1223       a. All physical register references presumed dead across BBs
1224       b. Mark live-in regs as live-in
1225       c. Calculate LV info in DFS order
1226          1) We'll see def of vreg before its uses
1227          2) PHI nodes are treated specially
1228             a) Only handle its def
1229             b) Uses handled in other BBs
1230          3) Handle all uses and defs
1231             a) Handle implicit preg uses
1232                (1) "TargetInstrDescriptor" from "TargetInstructionInfo"
1233             b) Handle explicit preg and vreg uses
1234             c) Handle implicit preg defs
1235                (1) "TargetInstrDescriptor" from "TargetInstructionInfo"
1236             d) Handle explicit preg and vreg defs
1237          4) Use of vreg marks it killed (last use in BB)
1238             a) Updates (expands) live range
1239             b) Marks vreg as alive in dominating blocks
1240          5) Use of preg updates info and used tables
1241          6) Def of vreg defaults to "dead"
1242             a) Expanded later (see B.1.c.4)
1243          7) Def of preg updates info, used, RegsKilled, and RegsDead tables.
1244          8) Handle virt assigns from PHI nodes at the bottom of the BB
1245             a) If successor block has PHI nodes
1246                (1) Simulate an assignment at the end of current BB
1247                    (i.e., mark it as alive in current BB)
1248          9) If last block is a "return"
1249             a) Mark it as using all live-out values
1250          10) Kill all pregs available at the end of the BB
1251       d. Update "RegistersDead" and "RegistersKilled"
1252          1) RegistersDead - This map keeps track of all of the registers that
1253             are dead immediately after an instruction executes, which are not
1254             dead after the operands are evaluated.  In practice, this only
1255             contains registers which are defined by an instruction, but never
1256             used.
1257          2) RegistersKilled - This map keeps track of all of the registers that
1258             are dead immediately after an instruction reads its operands.  If an
1259             instruction does not have an entry in this map, it kills no
1260             registers.
1261    2. LiveInterval Analysis
1262       a. Use LV pass to conservatively compute live intervals for vregs and pregs
1263       b. For some ordering of the machine instrs [1,N], a live interval is an
1264          interval [i,j) where 1 <= i <= j < N for which a variable is live
1265       c. Function has live ins
1266          1) Insert dummy instr at beginning
1267          2) Pretend dummy instr "defines" values
1268       d. Number each machine instruction -- depth-first order
1269          1) An interval [i, j) == Live interval for reg v if there is no
1270             instr with num j' > j s.t. v is live at j' and there is no instr
1271             with number i' < i s.t. v is live at i'
1272          2) Intervals can have holes: [1,20), [50,65), [1000,1001)
1273       e. Handle line-in values
1274       f. Compute live intervals
1275          1) Each live range is assigned a value num within the live interval
1276          2) vreg
1277             a) May be defined multiple times (due to phi and 2-addr elimination)
1278             b) Live only within defining BB
1279                (1) Single kill after def in BB
1280             c) Lives to end of defining BB, potentially across some BBs
1281                (1) Add range that goes from def to end of defining BB
1282                (2) Iterate over all BBs that the var is completely live in
1283                    (a) add [instrIndex(begin), InstrIndex(end)+4) to LI
1284                (3) Vreg is live from start of any killing block to 'use'
1285             d) If seeing vreg again (because of phi or 2-addr elimination)
1286                (1) If 2-addr elim, then vreg is 1st op and a def-and-use
1287                    (a) Didn't realize there are 2 values in LI
1288                    (b) Need to take LR that defs vreg and split it into 2 vals
1289                        (1) Delete initial value (from first def to redef)
1290                        (2) Get new value num (#1)
1291                        (3) Value#0 is now defined by the 2-addr instr
1292                        (4) Add new LR which replaces the range for input copy
1293                (2) Else phi-elimination
1294                    (a) If first redef of vreg, change LR in PHI block to be
1295                        a different Value Number
1296                    (b) Each variable def is only live until the end of the BB
1297          3) preg
1298             a) Cannot be live across BB
1299             b) Lifetime must end somewhere in its defining BB
1300             c) Dead at def instr, if not used after def
1301                (1) Interval: [defSlot(def), defSlot(def) + 1)
1302             d) Killed by subsequent instr, if not dead on def
1303                (1) Interval: [defSlot(def), useSlot(kill) + 1)
1304             e) If neither, then it's live-in to func and never used
1305                (1) Interval: [start, start + 1)
1306       e. Join intervals
1307       f. Compute spill weights
1308       g. Coalesce vregs
1309       h. Remove identity moves
1310    3. Linear Scan RA
1311       a. 
1312
1313
1314   /// VarInfo - This represents the regions where a virtual register is live in
1315   /// the program.  We represent this with three different pieces of
1316   /// information: the instruction that uniquely defines the value, the set of
1317   /// blocks the instruction is live into and live out of, and the set of 
1318   /// non-phi instructions that are the last users of the value.
1319   ///
1320   /// In the common case where a value is defined and killed in the same block,
1321   /// DefInst is the defining inst, there is one killing instruction, and 
1322   /// AliveBlocks is empty.
1323   ///
1324   /// Otherwise, the value is live out of the block.  If the value is live
1325   /// across any blocks, these blocks are listed in AliveBlocks.  Blocks where
1326   /// the liveness range ends are not included in AliveBlocks, instead being
1327   /// captured by the Kills set.  In these blocks, the value is live into the
1328   /// block (unless the value is defined and killed in the same block) and lives
1329   /// until the specified instruction.  Note that there cannot ever be a value
1330   /// whose Kills set contains two instructions from the same basic block.
1331   ///
1332   /// PHI nodes complicate things a bit.  If a PHI node is the last user of a
1333   /// value in one of its predecessor blocks, it is not listed in the kills set,
1334   /// but does include the predecessor block in the AliveBlocks set (unless that
1335   /// block also defines the value).  This leads to the (perfectly sensical)
1336   /// situation where a value is defined in a block, and the last use is a phi
1337   /// node in the successor.  In this case, DefInst will be the defining
1338   /// instruction, AliveBlocks is empty (the value is not live across any 
1339   /// blocks) and Kills is empty (phi nodes are not included).  This is sensical
1340   /// because the value must be live to the end of the block, but is not live in
1341   /// any successor blocks.
1342
1343  -->
1344
1345 <!-- ======================================================================= -->
1346 <div class="doc_subsection">
1347   <a name="regalloc">Register Allocation</a>
1348 </div>
1349
1350 <div class="doc_text">
1351
1352 <p>The <i>Register Allocation problem</i> consists in mapping a
1353 program <i>P<sub>v</sub></i>, that can use an unbounded number of
1354 virtual registers, to a program <i>P<sub>p</sub></i> that contains a
1355 finite (possibly small) number of physical registers. Each target
1356 architecture has a different number of physical registers. If the
1357 number of physical registers is not enough to accommodate all the
1358 virtual registers, some of them will have to be mapped into
1359 memory. These virtuals are called <i>spilled virtuals</i>.</p>
1360
1361 </div>
1362
1363 <!-- _______________________________________________________________________ -->
1364
1365 <div class="doc_subsubsection">
1366   <a name="regAlloc_represent">How registers are represented in LLVM</a>
1367 </div>
1368
1369 <div class="doc_text">
1370
1371 <p>In LLVM, physical registers are denoted by integer numbers that
1372 normally range from 1 to 1023. To see how this numbering is defined
1373 for a particular architecture, you can read the
1374 <tt>GenRegisterNames.inc</tt> file for that architecture. For
1375 instance, by inspecting
1376 <tt>lib/Target/X86/X86GenRegisterNames.inc</tt> we see that the 32-bit
1377 register <tt>EAX</tt> is denoted by 15, and the MMX register
1378 <tt>MM0</tt> is mapped to 48.</p>
1379
1380 <p>Some architectures contain registers that share the same physical
1381 location. A notable example is the X86 platform. For instance, in the
1382 X86 architecture, the registers <tt>EAX</tt>, <tt>AX</tt> and
1383 <tt>AL</tt> share the first eight bits. These physical registers are
1384 marked as <i>aliased</i> in LLVM. Given a particular architecture, you
1385 can check which registers are aliased by inspecting its
1386 <tt>RegisterInfo.td</tt> file. Moreover, the method
1387 <tt>MRegisterInfo::getAliasSet(p_reg)</tt> returns an array containing
1388 all the physical registers aliased to the register <tt>p_reg</tt>.</p>
1389
1390 <p>Physical registers, in LLVM, are grouped in <i>Register Classes</i>.
1391 Elements in the same register class are functionally equivalent, and can
1392 be interchangeably used. Each virtual register can only be mapped to
1393 physical registers of a particular class. For instance, in the X86
1394 architecture, some virtuals can only be allocated to 8 bit registers.
1395 A register class is described by <tt>TargetRegisterClass</tt> objects.
1396 To discover if a virtual register is compatible with a given physical,
1397 this code can be used:
1398 </p>
1399
1400 <div class="doc_code">
1401 <pre>
1402 bool RegMapping_Fer::compatible_class(MachineFunction &mf,
1403                                       unsigned v_reg,
1404                                       unsigned p_reg) {
1405   assert(MRegisterInfo::isPhysicalRegister(p_reg) &&
1406          "Target register must be physical");
1407   const TargetRegisterClass *trc = mf.getSSARegMap()->getRegClass(v_reg);
1408   return trc->contains(p_reg);
1409 }
1410 </pre>
1411 </div>
1412
1413 <p>Sometimes, mostly for debugging purposes, it is useful to change
1414 the number of physical registers available in the target
1415 architecture. This must be done statically, inside the
1416 <tt>TargetRegsterInfo.td</tt> file. Just <tt>grep</tt> for
1417 <tt>RegisterClass</tt>, the last parameter of which is a list of
1418 registers. Just commenting some out is one simple way to avoid them
1419 being used. A more polite way is to explicitly exclude some registers
1420 from the <i>allocation order</i>. See the definition of the
1421 <tt>GR</tt> register class in
1422 <tt>lib/Target/IA64/IA64RegisterInfo.td</tt> for an example of this
1423 (e.g., <tt>numReservedRegs</tt> registers are hidden.)</p>
1424
1425 <p>Virtual registers are also denoted by integer numbers. Contrary to
1426 physical registers, different virtual registers never share the same
1427 number. The smallest virtual register is normally assigned the number
1428 1024. This may change, so, in order to know which is the first virtual
1429 register, you should access
1430 <tt>MRegisterInfo::FirstVirtualRegister</tt>. Any register whose
1431 number is greater than or equal to
1432 <tt>MRegisterInfo::FirstVirtualRegister</tt> is considered a virtual
1433 register. Whereas physical registers are statically defined in a
1434 <tt>TargetRegisterInfo.td</tt> file and cannot be created by the
1435 application developer, that is not the case with virtual registers.
1436 In order to create new virtual registers, use the method
1437 <tt>SSARegMap::createVirtualRegister()</tt>. This method will return a
1438 virtual register with the highest code.
1439 </p>
1440
1441 <p>Before register allocation, the operands of an instruction are
1442 mostly virtual registers, although physical registers may also be
1443 used. In order to check if a given machine operand is a register, use
1444 the boolean function <tt>MachineOperand::isRegister()</tt>. To obtain
1445 the integer code of a register, use
1446 <tt>MachineOperand::getReg()</tt>. An instruction may define or use a
1447 register. For instance, <tt>ADD reg:1026 := reg:1025 reg:1024</tt>
1448 defines the registers 1024, and uses registers 1025 and 1026. Given a
1449 register operand, the method <tt>MachineOperand::isUse()</tt> informs
1450 if that register is being used by the instruction. The method
1451 <tt>MachineOperand::isDef()</tt> informs if that registers is being
1452 defined.</p>
1453
1454 <p>We will call physical registers present in the LLVM bytecode before
1455 register allocation <i>pre-colored registers</i>. Pre-colored
1456 registers are used in many different situations, for instance, to pass
1457 parameters of functions calls, and to store results of particular
1458 instructions. There are two types of pre-colored registers: the ones
1459 <i>implicitly</i> defined, and those <i>explicitly</i>
1460 defined. Explicitly defined registers are normal operands, and can be
1461 accessed with <tt>MachineInstr::getOperand(int)::getReg()</tt>.  In
1462 order to check which registers are implicitly defined by an
1463 instruction, use the
1464 <tt>TargetInstrInfo::get(opcode)::ImplicitDefs</tt>, where
1465 <tt>opcode</tt> is the opcode of the target instruction. One important
1466 difference between explicit and implicit physical registers is that
1467 the latter are defined statically for each instruction, whereas the
1468 former may vary depending on the program being compiled. For example,
1469 an instruction that represents a function call will always implicitly
1470 define or use the same set of physical registers. To read the
1471 registers implicitly used by an instruction, use
1472 <tt>TargetInstrInfo::get(opcode)::ImplicitUses</tt>. Pre-colored
1473 registers impose constraints on any register allocation algorithm. The
1474 register allocator must make sure that none of them is been
1475 overwritten by the values of virtual registers while still alive.</p>
1476
1477 </div>
1478
1479 <!-- _______________________________________________________________________ -->
1480
1481 <div class="doc_subsubsection">
1482   <a name="regAlloc_howTo">Mapping virtual registers to physical registers</a>
1483 </div>
1484
1485 <div class="doc_text">
1486
1487 <p>There are two ways to map virtual registers to physical registers (or to
1488 memory slots). The first way, that we will call <i>direct mapping</i>,
1489 is based on the use of methods of the classes <tt>MRegisterInfo</tt>,
1490 and <tt>MachineOperand</tt>. The second way, that we will call
1491 <i>indirect mapping</i>, relies on the <tt>VirtRegMap</tt> class in
1492 order to insert loads and stores sending and getting values to and from
1493 memory.</p>
1494
1495 <p>The direct mapping provides more flexibility to the developer of
1496 the register allocator; however, it is more error prone, and demands
1497 more implementation work.  Basically, the programmer will have to
1498 specify where load and store instructions should be inserted in the
1499 target function being compiled in order to get and store values in
1500 memory. To assign a physical register to a virtual register present in
1501 a given operand, use <tt>MachineOperand::setReg(p_reg)</tt>. To insert
1502 a store instruction, use
1503 <tt>MRegisterInfo::storeRegToStackSlot(...)</tt>, and to insert a load
1504 instruction, use <tt>MRegisterInfo::loadRegFromStackSlot</tt>.</p>
1505
1506 <p>The indirect mapping shields the application developer from the
1507 complexities of inserting load and store instructions. In order to map
1508 a virtual register to a physical one, use
1509 <tt>VirtRegMap::assignVirt2Phys(vreg, preg)</tt>.  In order to map a
1510 certain virtual register to memory, use
1511 <tt>VirtRegMap::assignVirt2StackSlot(vreg)</tt>. This method will
1512 return the stack slot where <tt>vreg</tt>'s value will be located.  If
1513 it is necessary to map another virtual register to the same stack
1514 slot, use <tt>VirtRegMap::assignVirt2StackSlot(vreg,
1515 stack_location)</tt>. One important point to consider when using the
1516 indirect mapping, is that even if a virtual register is mapped to
1517 memory, it still needs to be mapped to a physical register. This
1518 physical register is the location where the virtual register is
1519 supposed to be found before being stored or after being reloaded.</p>
1520
1521 <p>If the indirect strategy is used, after all the virtual registers
1522 have been mapped to physical registers or stack slots, it is necessary
1523 to use a spiller object to place load and store instructions in the
1524 code. Every virtual that has been mapped to a stack slot will be
1525 stored to memory after been defined and will be loaded before being
1526 used. The implementation of the spiller tries to recycle load/store
1527 instructions, avoiding unnecessary instructions. For an example of how
1528 to invoke the spiller, see
1529 <tt>RegAllocLinearScan::runOnMachineFunction</tt> in
1530 <tt>lib/CodeGen/RegAllocLinearScan.cpp</tt>.</p>
1531
1532 </div>
1533
1534 <!-- _______________________________________________________________________ -->
1535 <div class="doc_subsubsection">
1536   <a name="regAlloc_twoAddr">Handling two address instructions</a>
1537 </div>
1538
1539 <div class="doc_text">
1540
1541 <p>With very rare exceptions (e.g., function calls), the LLVM machine
1542 code instructions are three address instructions. That is, each
1543 instruction is expected to define at most one register, and to use at
1544 most two registers.  However, some architectures use two address
1545 instructions. In this case, the defined register is also one of the
1546 used register. For instance, an instruction such as <tt>ADD %EAX,
1547 %EBX</tt>, in X86 is actually equivalent to <tt>%EAX = %EAX +
1548 %EBX</tt>.</p>
1549
1550 <p>In order to produce correct code, LLVM must convert three address
1551 instructions that represent two address instructions into true two
1552 address instructions. LLVM provides the pass
1553 <tt>TwoAddressInstructionPass</tt> for this specific purpose. It must
1554 be run before register allocation takes place. After its execution,
1555 the resulting code may no longer be in SSA form. This happens, for
1556 instance, in situations where an instruction such as <tt>%a = ADD %b
1557 %c</tt> is converted to two instructions such as:</p>
1558
1559 <div class="doc_code">
1560 <pre>
1561 %a = MOVE %b
1562 %a = ADD %a %b
1563 </pre>
1564 </div>
1565
1566 <p>Notice that, internally, the second instruction is represented as
1567 <tt>ADD %a[def/use] %b</tt>. I.e., the register operand <tt>%a</tt> is
1568 both used and defined by the instruction.</p>
1569
1570 </div>
1571
1572 <!-- _______________________________________________________________________ -->
1573 <div class="doc_subsubsection">
1574   <a name="regAlloc_ssaDecon">The SSA deconstruction phase</a>
1575 </div>
1576
1577 <div class="doc_text">
1578
1579 <p>An important transformation that happens during register allocation is called
1580 the <i>SSA Deconstruction Phase</i>. The SSA form simplifies many
1581 analyses that are performed on the control flow graph of
1582 programs. However, traditional instruction sets do not implement
1583 PHI instructions. Thus, in order to generate executable code, compilers
1584 must replace PHI instructions with other instructions that preserve their
1585 semantics.</p>
1586
1587 <p>There are many ways in which PHI instructions can safely be removed
1588 from the target code. The most traditional PHI deconstruction
1589 algorithm replaces PHI instructions with copy instructions. That is
1590 the strategy adopted by LLVM. The SSA deconstruction algorithm is
1591 implemented in n<tt>lib/CodeGen/>PHIElimination.cpp</tt>. In order to
1592 invoke this pass, the identifier <tt>PHIEliminationID</tt> must be
1593 marked as required in the code of the register allocator.</p>
1594
1595 </div>
1596
1597 <!-- _______________________________________________________________________ -->
1598 <div class="doc_subsubsection">
1599   <a name="regAlloc_fold">Instruction folding</a>
1600 </div>
1601
1602 <div class="doc_text">
1603
1604 <p><i>Instruction folding</i> is an optimization performed during
1605 register allocation that removes unnecessary copy instructions. For
1606 instance, a sequence of instructions such as:</p>
1607
1608 <div class="doc_code">
1609 <pre>
1610 %EBX = LOAD %mem_address
1611 %EAX = COPY %EBX
1612 </pre>
1613 </div>
1614
1615 <p>can be safely substituted by the single instruction:
1616
1617 <div class="doc_code">
1618 <pre>
1619 %EAX = LOAD %mem_address
1620 </pre>
1621 </div>
1622
1623 <p>Instructions can be folded with the
1624 <tt>MRegisterInfo::foldMemoryOperand(...)</tt> method. Care must be
1625 taken when folding instructions; a folded instruction can be quite
1626 different from the original instruction. See
1627 <tt>LiveIntervals::addIntervalsForSpills</tt> in
1628 <tt>lib/CodeGen/LiveIntervalAnalysis.cpp</tt> for an example of its use.</p>
1629
1630 </div>
1631
1632 <!-- _______________________________________________________________________ -->
1633
1634 <div class="doc_subsubsection">
1635   <a name="regAlloc_builtIn">Built in register allocators</a>
1636 </div>
1637
1638 <div class="doc_text">
1639
1640 <p>The LLVM infrastructure provides the application developer with
1641 three different register allocators:</p>
1642
1643 <ul>
1644   <li><i>Simple</i> - This is a very simple implementation that does
1645       not keep values in registers across instructions. This register
1646       allocator immediately spills every value right after it is
1647       computed, and reloads all used operands from memory to temporary
1648       registers before each instruction.</li>
1649   <li><i>Local</i> - This register allocator is an improvement on the
1650       <i>Simple</i> implementation. It allocates registers on a basic
1651       block level, attempting to keep values in registers and reusing
1652       registers as appropriate.</li>
1653   <li><i>Linear Scan</i> - <i>The default allocator</i>. This is the
1654       well-know linear scan register allocator. Whereas the
1655       <i>Simple</i> and <i>Local</i> algorithms use a direct mapping
1656       implementation technique, the <i>Linear Scan</i> implementation
1657       uses a spiller in order to place load and stores.</li>
1658 </ul>
1659
1660 <p>The type of register allocator used in <tt>llc</tt> can be chosen with the
1661 command line option <tt>-regalloc=...</tt>:</p>
1662
1663 <div class="doc_code">
1664 <pre>
1665 $ llc -f -regalloc=simple file.bc -o sp.s;
1666 $ llc -f -regalloc=local file.bc -o lc.s;
1667 $ llc -f -regalloc=linearscan file.bc -o ln.s;
1668 </pre>
1669 </div>
1670
1671 </div>
1672
1673 <!-- ======================================================================= -->
1674 <div class="doc_subsection">
1675   <a name="proepicode">Prolog/Epilog Code Insertion</a>
1676 </div>
1677 <div class="doc_text"><p>To Be Written</p></div>
1678 <!-- ======================================================================= -->
1679 <div class="doc_subsection">
1680   <a name="latemco">Late Machine Code Optimizations</a>
1681 </div>
1682 <div class="doc_text"><p>To Be Written</p></div>
1683 <!-- ======================================================================= -->
1684 <div class="doc_subsection">
1685   <a name="codeemit">Code Emission</a>
1686 </div>
1687 <div class="doc_text"><p>To Be Written</p></div>
1688 <!-- _______________________________________________________________________ -->
1689 <div class="doc_subsubsection">
1690   <a name="codeemit_asm">Generating Assembly Code</a>
1691 </div>
1692 <div class="doc_text"><p>To Be Written</p></div>
1693 <!-- _______________________________________________________________________ -->
1694 <div class="doc_subsubsection">
1695   <a name="codeemit_bin">Generating Binary Machine Code</a>
1696 </div>
1697
1698 <div class="doc_text">
1699    <p>For the JIT or <tt>.o</tt> file writer</p>
1700 </div>
1701
1702
1703 <!-- *********************************************************************** -->
1704 <div class="doc_section">
1705   <a name="targetimpls">Target-specific Implementation Notes</a>
1706 </div>
1707 <!-- *********************************************************************** -->
1708
1709 <div class="doc_text">
1710
1711 <p>This section of the document explains features or design decisions that
1712 are specific to the code generator for a particular target.</p>
1713
1714 </div>
1715
1716
1717 <!-- ======================================================================= -->
1718 <div class="doc_subsection">
1719   <a name="x86">The X86 backend</a>
1720 </div>
1721
1722 <div class="doc_text">
1723
1724 <p>The X86 code generator lives in the <tt>lib/Target/X86</tt> directory.  This
1725 code generator currently targets a generic P6-like processor.  As such, it
1726 produces a few P6-and-above instructions (like conditional moves), but it does
1727 not make use of newer features like MMX or SSE.  In the future, the X86 backend
1728 will have sub-target support added for specific processor families and 
1729 implementations.</p>
1730
1731 </div>
1732
1733 <!-- _______________________________________________________________________ -->
1734 <div class="doc_subsubsection">
1735   <a name="x86_tt">X86 Target Triples Supported</a>
1736 </div>
1737
1738 <div class="doc_text">
1739
1740 <p>The following are the known target triples that are supported by the X86 
1741 backend.  This is not an exhaustive list, and it would be useful to add those
1742 that people test.</p>
1743
1744 <ul>
1745 <li><b>i686-pc-linux-gnu</b> - Linux</li>
1746 <li><b>i386-unknown-freebsd5.3</b> - FreeBSD 5.3</li>
1747 <li><b>i686-pc-cygwin</b> - Cygwin on Win32</li>
1748 <li><b>i686-pc-mingw32</b> - MingW on Win32</li>
1749 <li><b>i686-apple-darwin*</b> - Apple Darwin on X86</li>
1750 </ul>
1751
1752 </div>
1753
1754 <!-- _______________________________________________________________________ -->
1755 <div class="doc_subsubsection">
1756   <a name="x86_memory">Representing X86 addressing modes in MachineInstrs</a>
1757 </div>
1758
1759 <div class="doc_text">
1760
1761 <p>The x86 has a very flexible way of accessing memory.  It is capable of
1762 forming memory addresses of the following expression directly in integer
1763 instructions (which use ModR/M addressing):</p>
1764
1765 <div class="doc_code">
1766 <pre>
1767 Base + [1,2,4,8] * IndexReg + Disp32
1768 </pre>
1769 </div>
1770
1771 <p>In order to represent this, LLVM tracks no less than 4 operands for each
1772 memory operand of this form.  This means that the "load" form of '<tt>mov</tt>'
1773 has the following <tt>MachineOperand</tt>s in this order:</p>
1774
1775 <pre>
1776 Index:        0     |    1        2       3           4
1777 Meaning:   DestReg, | BaseReg,  Scale, IndexReg, Displacement
1778 OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg,   SignExtImm
1779 </pre>
1780
1781 <p>Stores, and all other instructions, treat the four memory operands in the 
1782 same way and in the same order.</p>
1783
1784 </div>
1785
1786 <!-- _______________________________________________________________________ -->
1787 <div class="doc_subsubsection">
1788   <a name="x86_names">Instruction naming</a>
1789 </div>
1790
1791 <div class="doc_text">
1792
1793 <p>An instruction name consists of the base name, a default operand size, and a
1794 a character per operand with an optional special size. For example:</p>
1795
1796 <p>
1797 <tt>ADD8rr</tt> -&gt; add, 8-bit register, 8-bit register<br>
1798 <tt>IMUL16rmi</tt> -&gt; imul, 16-bit register, 16-bit memory, 16-bit immediate<br>
1799 <tt>IMUL16rmi8</tt> -&gt; imul, 16-bit register, 16-bit memory, 8-bit immediate<br>
1800 <tt>MOVSX32rm16</tt> -&gt; movsx, 32-bit register, 16-bit memory
1801 </p>
1802
1803 </div>
1804
1805 <!-- *********************************************************************** -->
1806 <hr>
1807 <address>
1808   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1809   src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1810   <a href="http://validator.w3.org/check/referer"><img
1811   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /></a>
1812
1813   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1814   <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1815   Last modified: $Date$
1816 </address>
1817
1818 </body>
1819 </html>