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