Added MVT::v2f16
[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   <meta http-equiv="content-type" content="text/html; charset=utf-8">
6   <title>The LLVM Target-Independent Code Generator</title>
7   <link rel="stylesheet" href="llvm.css" type="text/css">
8
9   <style type="text/css">
10     .unknown { background-color: #C0C0C0; text-align: center; }
11     .unknown:before { content: "?" }
12     .no { background-color: #C11B17 }
13     .no:before { content: "N" }
14     .partial { background-color: #F88017 }
15     .yes { background-color: #0F0; }
16     .yes:before { content: "Y" }
17   </style>
18
19 </head>
20 <body>
21
22 <h1>
23   The LLVM Target-Independent Code Generator
24 </h1>
25
26 <ol>
27   <li><a href="#introduction">Introduction</a>
28     <ul>
29       <li><a href="#required">Required components in the code generator</a></li>
30       <li><a href="#high-level-design">The high-level design of the code
31           generator</a></li>
32       <li><a href="#tablegen">Using TableGen for target description</a></li>
33     </ul>
34   </li>
35   <li><a href="#targetdesc">Target description classes</a>
36     <ul>
37       <li><a href="#targetmachine">The <tt>TargetMachine</tt> class</a></li>
38       <li><a href="#targetdata">The <tt>TargetData</tt> class</a></li>
39       <li><a href="#targetlowering">The <tt>TargetLowering</tt> class</a></li>
40       <li><a href="#targetregisterinfo">The <tt>TargetRegisterInfo</tt> class</a></li>
41       <li><a href="#targetinstrinfo">The <tt>TargetInstrInfo</tt> class</a></li>
42       <li><a href="#targetframeinfo">The <tt>TargetFrameInfo</tt> class</a></li>
43       <li><a href="#targetsubtarget">The <tt>TargetSubtarget</tt> class</a></li>
44       <li><a href="#targetjitinfo">The <tt>TargetJITInfo</tt> class</a></li>
45     </ul>
46   </li>
47   <li><a href="#codegendesc">The "Machine" Code Generator classes</a>
48     <ul>
49     <li><a href="#machineinstr">The <tt>MachineInstr</tt> class</a></li>
50     <li><a href="#machinebasicblock">The <tt>MachineBasicBlock</tt>
51                                      class</a></li>
52     <li><a href="#machinefunction">The <tt>MachineFunction</tt> class</a></li>
53     <li><a href="#machineinstrbundle"><tt>MachineInstr Bundles</tt></a></li>
54     </ul>
55   </li>
56   <li><a href="#mc">The "MC" Layer</a>
57     <ul>
58     <li><a href="#mcstreamer">The <tt>MCStreamer</tt> API</a></li>
59     <li><a href="#mccontext">The <tt>MCContext</tt> class</a>
60     <li><a href="#mcsymbol">The <tt>MCSymbol</tt> class</a></li>
61     <li><a href="#mcsection">The <tt>MCSection</tt> class</a></li>
62     <li><a href="#mcinst">The <tt>MCInst</tt> class</a></li>
63     </ul>
64   </li>
65   <li><a href="#codegenalgs">Target-independent code generation algorithms</a>
66     <ul>
67     <li><a href="#instselect">Instruction Selection</a>
68       <ul>
69       <li><a href="#selectiondag_intro">Introduction to SelectionDAGs</a></li>
70       <li><a href="#selectiondag_process">SelectionDAG Code Generation
71                                           Process</a></li>
72       <li><a href="#selectiondag_build">Initial SelectionDAG
73                                         Construction</a></li>
74       <li><a href="#selectiondag_legalize_types">SelectionDAG LegalizeTypes Phase</a></li>
75       <li><a href="#selectiondag_legalize">SelectionDAG Legalize Phase</a></li>
76       <li><a href="#selectiondag_optimize">SelectionDAG Optimization
77                                            Phase: the DAG Combiner</a></li>
78       <li><a href="#selectiondag_select">SelectionDAG Select Phase</a></li>
79       <li><a href="#selectiondag_sched">SelectionDAG Scheduling and Formation
80                                         Phase</a></li>
81       <li><a href="#selectiondag_future">Future directions for the
82                                          SelectionDAG</a></li>
83       </ul></li>
84      <li><a href="#liveintervals">Live Intervals</a>
85        <ul>
86        <li><a href="#livevariable_analysis">Live Variable Analysis</a></li>
87        <li><a href="#liveintervals_analysis">Live Intervals Analysis</a></li>
88        </ul></li>
89     <li><a href="#regalloc">Register Allocation</a>
90       <ul>
91       <li><a href="#regAlloc_represent">How registers are represented in
92                                         LLVM</a></li>
93       <li><a href="#regAlloc_howTo">Mapping virtual registers to physical
94                                     registers</a></li>
95       <li><a href="#regAlloc_twoAddr">Handling two address instructions</a></li>
96       <li><a href="#regAlloc_ssaDecon">The SSA deconstruction phase</a></li>
97       <li><a href="#regAlloc_fold">Instruction folding</a></li>
98       <li><a href="#regAlloc_builtIn">Built in register allocators</a></li>
99       </ul></li>
100     <li><a href="#codeemit">Code Emission</a></li>
101     <li><a href="#vliw_packetizer">VLIW Packetizer</a>
102       <ul>
103       <li><a href="#vliw_mapping">Mapping from instructions to functional
104                  units</a></li>
105       <li><a href="#vliw_repr">How the packetization tables are
106                              generated and used</a></li>
107       </ul>
108     </li>
109     </ul>
110   </li>
111   <li><a href="#nativeassembler">Implementing a Native Assembler</a></li>
112   
113   <li><a href="#targetimpls">Target-specific Implementation Notes</a>
114     <ul>
115     <li><a href="#targetfeatures">Target Feature Matrix</a></li>
116     <li><a href="#tailcallopt">Tail call optimization</a></li>
117     <li><a href="#sibcallopt">Sibling call optimization</a></li>
118     <li><a href="#x86">The X86 backend</a></li>
119     <li><a href="#ppc">The PowerPC backend</a>
120       <ul>
121       <li><a href="#ppc_abi">LLVM PowerPC ABI</a></li>
122       <li><a href="#ppc_frame">Frame Layout</a></li>
123       <li><a href="#ppc_prolog">Prolog/Epilog</a></li>
124       <li><a href="#ppc_dynamic">Dynamic Allocation</a></li>
125       </ul></li>
126     <li><a href="#ptx">The PTX backend</a></li>
127     </ul></li>
128
129 </ol>
130
131 <div class="doc_author">
132   <p>Written by the LLVM Team.</p>
133 </div>
134
135 <div class="doc_warning">
136   <p>Warning: This is a work in progress.</p>
137 </div>
138
139 <!-- *********************************************************************** -->
140 <h2>
141   <a name="introduction">Introduction</a>
142 </h2>
143 <!-- *********************************************************************** -->
144
145 <div>
146
147 <p>The LLVM target-independent code generator is a framework that provides a
148    suite of reusable components for translating the LLVM internal representation
149    to the machine code for a specified target&mdash;either in assembly form
150    (suitable for a static compiler) or in binary machine code format (usable for
151    a JIT compiler). The LLVM target-independent code generator consists of six
152    main components:</p>
153
154 <ol>
155   <li><a href="#targetdesc">Abstract target description</a> interfaces which
156       capture important properties about various aspects of the machine,
157       independently of how they will be used.  These interfaces are defined in
158       <tt>include/llvm/Target/</tt>.</li>
159
160   <li>Classes used to represent the <a href="#codegendesc">code being
161       generated</a> for a target.  These classes are intended to be abstract
162       enough to represent the machine code for <i>any</i> target machine.  These
163       classes are defined in <tt>include/llvm/CodeGen/</tt>. At this level,
164       concepts like "constant pool entries" and "jump tables" are explicitly
165       exposed.</li>
166
167   <li>Classes and algorithms used to represent code as the object file level,
168       the <a href="#mc">MC Layer</a>.  These classes represent assembly level
169       constructs like labels, sections, and instructions.  At this level,
170       concepts like "constant pool entries" and "jump tables" don't exist.</li>
171
172   <li><a href="#codegenalgs">Target-independent algorithms</a> used to implement
173       various phases of native code generation (register allocation, scheduling,
174       stack frame representation, etc).  This code lives
175       in <tt>lib/CodeGen/</tt>.</li>
176
177   <li><a href="#targetimpls">Implementations of the abstract target description
178       interfaces</a> for particular targets.  These machine descriptions make
179       use of the components provided by LLVM, and can optionally provide custom
180       target-specific passes, to build complete code generators for a specific
181       target.  Target descriptions live in <tt>lib/Target/</tt>.</li>
182
183   <li><a href="#jit">The target-independent JIT components</a>.  The LLVM JIT is
184       completely target independent (it uses the <tt>TargetJITInfo</tt>
185       structure to interface for target-specific issues.  The code for the
186       target-independent JIT lives in <tt>lib/ExecutionEngine/JIT</tt>.</li>
187 </ol>
188
189 <p>Depending on which part of the code generator you are interested in working
190    on, different pieces of this will be useful to you.  In any case, you should
191    be familiar with the <a href="#targetdesc">target description</a>
192    and <a href="#codegendesc">machine code representation</a> classes.  If you
193    want to add a backend for a new target, you will need
194    to <a href="#targetimpls">implement the target description</a> classes for
195    your new target and understand the <a href="LangRef.html">LLVM code
196    representation</a>.  If you are interested in implementing a
197    new <a href="#codegenalgs">code generation algorithm</a>, it should only
198    depend on the target-description and machine code representation classes,
199    ensuring that it is portable.</p>
200
201 <!-- ======================================================================= -->
202 <h3>
203  <a name="required">Required components in the code generator</a>
204 </h3>
205
206 <div>
207
208 <p>The two pieces of the LLVM code generator are the high-level interface to the
209    code generator and the set of reusable components that can be used to build
210    target-specific backends.  The two most important interfaces
211    (<a href="#targetmachine"><tt>TargetMachine</tt></a>
212    and <a href="#targetdata"><tt>TargetData</tt></a>) are the only ones that are
213    required to be defined for a backend to fit into the LLVM system, but the
214    others must be defined if the reusable code generator components are going to
215    be used.</p>
216
217 <p>This design has two important implications.  The first is that LLVM can
218    support completely non-traditional code generation targets.  For example, the
219    C backend does not require register allocation, instruction selection, or any
220    of the other standard components provided by the system.  As such, it only
221    implements these two interfaces, and does its own thing.  Another example of
222    a code generator like this is a (purely hypothetical) backend that converts
223    LLVM to the GCC RTL form and uses GCC to emit machine code for a target.</p>
224
225 <p>This design also implies that it is possible to design and implement
226    radically different code generators in the LLVM system that do not make use
227    of any of the built-in components.  Doing so is not recommended at all, but
228    could be required for radically different targets that do not fit into the
229    LLVM machine description model: FPGAs for example.</p>
230
231 </div>
232
233 <!-- ======================================================================= -->
234 <h3>
235  <a name="high-level-design">The high-level design of the code generator</a>
236 </h3>
237
238 <div>
239
240 <p>The LLVM target-independent code generator is designed to support efficient
241    and quality code generation for standard register-based microprocessors.
242    Code generation in this model is divided into the following stages:</p>
243
244 <ol>
245   <li><b><a href="#instselect">Instruction Selection</a></b> &mdash; This phase
246       determines an efficient way to express the input LLVM code in the target
247       instruction set.  This stage produces the initial code for the program in
248       the target instruction set, then makes use of virtual registers in SSA
249       form and physical registers that represent any required register
250       assignments due to target constraints or calling conventions.  This step
251       turns the LLVM code into a DAG of target instructions.</li>
252
253   <li><b><a href="#selectiondag_sched">Scheduling and Formation</a></b> &mdash;
254       This phase takes the DAG of target instructions produced by the
255       instruction selection phase, determines an ordering of the instructions,
256       then emits the instructions
257       as <tt><a href="#machineinstr">MachineInstr</a></tt>s with that ordering.
258       Note that we describe this in the <a href="#instselect">instruction
259       selection section</a> because it operates on
260       a <a href="#selectiondag_intro">SelectionDAG</a>.</li>
261
262   <li><b><a href="#ssamco">SSA-based Machine Code Optimizations</a></b> &mdash;
263       This optional stage consists of a series of machine-code optimizations
264       that operate on the SSA-form produced by the instruction selector.
265       Optimizations like modulo-scheduling or peephole optimization work
266       here.</li>
267
268   <li><b><a href="#regalloc">Register Allocation</a></b> &mdash; The target code
269       is transformed from an infinite virtual register file in SSA form to the
270       concrete register file used by the target.  This phase introduces spill
271       code and eliminates all virtual register references from the program.</li>
272
273   <li><b><a href="#proepicode">Prolog/Epilog Code Insertion</a></b> &mdash; Once
274       the machine code has been generated for the function and the amount of
275       stack space required is known (used for LLVM alloca's and spill slots),
276       the prolog and epilog code for the function can be inserted and "abstract
277       stack location references" can be eliminated.  This stage is responsible
278       for implementing optimizations like frame-pointer elimination and stack
279       packing.</li>
280
281   <li><b><a href="#latemco">Late Machine Code Optimizations</a></b> &mdash;
282       Optimizations that operate on "final" machine code can go here, such as
283       spill code scheduling and peephole optimizations.</li>
284
285   <li><b><a href="#codeemit">Code Emission</a></b> &mdash; The final stage
286       actually puts out the code for the current function, either in the target
287       assembler format or in machine code.</li>
288 </ol>
289
290 <p>The code generator is based on the assumption that the instruction selector
291    will use an optimal pattern matching selector to create high-quality
292    sequences of native instructions.  Alternative code generator designs based
293    on pattern expansion and aggressive iterative peephole optimization are much
294    slower.  This design permits efficient compilation (important for JIT
295    environments) and aggressive optimization (used when generating code offline)
296    by allowing components of varying levels of sophistication to be used for any
297    step of compilation.</p>
298
299 <p>In addition to these stages, target implementations can insert arbitrary
300    target-specific passes into the flow.  For example, the X86 target uses a
301    special pass to handle the 80x87 floating point stack architecture.  Other
302    targets with unusual requirements can be supported with custom passes as
303    needed.</p>
304
305 </div>
306
307 <!-- ======================================================================= -->
308 <h3>
309  <a name="tablegen">Using TableGen for target description</a>
310 </h3>
311
312 <div>
313
314 <p>The target description classes require a detailed description of the target
315    architecture.  These target descriptions often have a large amount of common
316    information (e.g., an <tt>add</tt> instruction is almost identical to a
317    <tt>sub</tt> instruction).  In order to allow the maximum amount of
318    commonality to be factored out, the LLVM code generator uses
319    the <a href="TableGenFundamentals.html">TableGen</a> tool to describe big
320    chunks of the target machine, which allows the use of domain-specific and
321    target-specific abstractions to reduce the amount of repetition.</p>
322
323 <p>As LLVM continues to be developed and refined, we plan to move more and more
324    of the target description to the <tt>.td</tt> form.  Doing so gives us a
325    number of advantages.  The most important is that it makes it easier to port
326    LLVM because it reduces the amount of C++ code that has to be written, and
327    the surface area of the code generator that needs to be understood before
328    someone can get something working.  Second, it makes it easier to change
329    things. In particular, if tables and other things are all emitted
330    by <tt>tblgen</tt>, we only need a change in one place (<tt>tblgen</tt>) to
331    update all of the targets to a new interface.</p>
332
333 </div>
334
335 </div>
336
337 <!-- *********************************************************************** -->
338 <h2>
339   <a name="targetdesc">Target description classes</a>
340 </h2>
341 <!-- *********************************************************************** -->
342
343 <div>
344
345 <p>The LLVM target description classes (located in the
346    <tt>include/llvm/Target</tt> directory) provide an abstract description of
347    the target machine independent of any particular client.  These classes are
348    designed to capture the <i>abstract</i> properties of the target (such as the
349    instructions and registers it has), and do not incorporate any particular
350    pieces of code generation algorithms.</p>
351
352 <p>All of the target description classes (except the
353    <tt><a href="#targetdata">TargetData</a></tt> class) are designed to be
354    subclassed by the concrete target implementation, and have virtual methods
355    implemented.  To get to these implementations, the
356    <tt><a href="#targetmachine">TargetMachine</a></tt> class provides accessors
357    that should be implemented by the target.</p>
358
359 <!-- ======================================================================= -->
360 <h3>
361   <a name="targetmachine">The <tt>TargetMachine</tt> class</a>
362 </h3>
363
364 <div>
365
366 <p>The <tt>TargetMachine</tt> class provides virtual methods that are used to
367    access the target-specific implementations of the various target description
368    classes via the <tt>get*Info</tt> methods (<tt>getInstrInfo</tt>,
369    <tt>getRegisterInfo</tt>, <tt>getFrameInfo</tt>, etc.).  This class is
370    designed to be specialized by a concrete target implementation
371    (e.g., <tt>X86TargetMachine</tt>) which implements the various virtual
372    methods.  The only required target description class is
373    the <a href="#targetdata"><tt>TargetData</tt></a> class, but if the code
374    generator components are to be used, the other interfaces should be
375    implemented as well.</p>
376
377 </div>
378
379 <!-- ======================================================================= -->
380 <h3>
381   <a name="targetdata">The <tt>TargetData</tt> class</a>
382 </h3>
383
384 <div>
385
386 <p>The <tt>TargetData</tt> class is the only required target description class,
387    and it is the only class that is not extensible (you cannot derived a new
388    class from it).  <tt>TargetData</tt> specifies information about how the
389    target lays out memory for structures, the alignment requirements for various
390    data types, the size of pointers in the target, and whether the target is
391    little-endian or big-endian.</p>
392
393 </div>
394
395 <!-- ======================================================================= -->
396 <h3>
397   <a name="targetlowering">The <tt>TargetLowering</tt> class</a>
398 </h3>
399
400 <div>
401
402 <p>The <tt>TargetLowering</tt> class is used by SelectionDAG based instruction
403    selectors primarily to describe how LLVM code should be lowered to
404    SelectionDAG operations.  Among other things, this class indicates:</p>
405
406 <ul>
407   <li>an initial register class to use for various <tt>ValueType</tt>s,</li>
408
409   <li>which operations are natively supported by the target machine,</li>
410
411   <li>the return type of <tt>setcc</tt> operations,</li>
412
413   <li>the type to use for shift amounts, and</li>
414
415   <li>various high-level characteristics, like whether it is profitable to turn
416       division by a constant into a multiplication sequence</li>
417 </ul>
418
419 </div>
420
421 <!-- ======================================================================= -->
422 <h3>
423   <a name="targetregisterinfo">The <tt>TargetRegisterInfo</tt> class</a>
424 </h3>
425
426 <div>
427
428 <p>The <tt>TargetRegisterInfo</tt> class is used to describe the register file
429    of the target and any interactions between the registers.</p>
430
431 <p>Registers in the code generator are represented in the code generator by
432    unsigned integers.  Physical registers (those that actually exist in the
433    target description) are unique small numbers, and virtual registers are
434    generally large.  Note that register #0 is reserved as a flag value.</p>
435
436 <p>Each register in the processor description has an associated
437    <tt>TargetRegisterDesc</tt> entry, which provides a textual name for the
438    register (used for assembly output and debugging dumps) and a set of aliases
439    (used to indicate whether one register overlaps with another).</p>
440
441 <p>In addition to the per-register description, the <tt>TargetRegisterInfo</tt>
442    class exposes a set of processor specific register classes (instances of the
443    <tt>TargetRegisterClass</tt> class).  Each register class contains sets of
444    registers that have the same properties (for example, they are all 32-bit
445    integer registers).  Each SSA virtual register created by the instruction
446    selector has an associated register class.  When the register allocator runs,
447    it replaces virtual registers with a physical register in the set.</p>
448
449 <p>The target-specific implementations of these classes is auto-generated from
450    a <a href="TableGenFundamentals.html">TableGen</a> description of the
451    register file.</p>
452
453 </div>
454
455 <!-- ======================================================================= -->
456 <h3>
457   <a name="targetinstrinfo">The <tt>TargetInstrInfo</tt> class</a>
458 </h3>
459
460 <div>
461
462 <p>The <tt>TargetInstrInfo</tt> class is used to describe the machine
463    instructions supported by the target. It is essentially an array of
464    <tt>TargetInstrDescriptor</tt> objects, each of which describes one
465    instruction the target supports. Descriptors define things like the mnemonic
466    for the opcode, the number of operands, the list of implicit register uses
467    and defs, whether the instruction has certain target-independent properties
468    (accesses memory, is commutable, etc), and holds any target-specific
469    flags.</p>
470
471 </div>
472
473 <!-- ======================================================================= -->
474 <h3>
475   <a name="targetframeinfo">The <tt>TargetFrameInfo</tt> class</a>
476 </h3>
477
478 <div>
479
480 <p>The <tt>TargetFrameInfo</tt> class is used to provide information about the
481    stack frame layout of the target. It holds the direction of stack growth, the
482    known stack alignment on entry to each function, and the offset to the local
483    area.  The offset to the local area is the offset from the stack pointer on
484    function entry to the first location where function data (local variables,
485    spill locations) can be stored.</p>
486
487 </div>
488
489 <!-- ======================================================================= -->
490 <h3>
491   <a name="targetsubtarget">The <tt>TargetSubtarget</tt> class</a>
492 </h3>
493
494 <div>
495
496 <p>The <tt>TargetSubtarget</tt> class is used to provide information about the
497    specific chip set being targeted.  A sub-target informs code generation of
498    which instructions are supported, instruction latencies and instruction
499    execution itinerary; i.e., which processing units are used, in what order,
500    and for how long.</p>
501
502 </div>
503
504
505 <!-- ======================================================================= -->
506 <h3>
507   <a name="targetjitinfo">The <tt>TargetJITInfo</tt> class</a>
508 </h3>
509
510 <div>
511
512 <p>The <tt>TargetJITInfo</tt> class exposes an abstract interface used by the
513    Just-In-Time code generator to perform target-specific activities, such as
514    emitting stubs.  If a <tt>TargetMachine</tt> supports JIT code generation, it
515    should provide one of these objects through the <tt>getJITInfo</tt>
516    method.</p>
517
518 </div>
519
520 </div>
521
522 <!-- *********************************************************************** -->
523 <h2>
524   <a name="codegendesc">Machine code description classes</a>
525 </h2>
526 <!-- *********************************************************************** -->
527
528 <div>
529
530 <p>At the high-level, LLVM code is translated to a machine specific
531    representation formed out of
532    <a href="#machinefunction"><tt>MachineFunction</tt></a>,
533    <a href="#machinebasicblock"><tt>MachineBasicBlock</tt></a>,
534    and <a href="#machineinstr"><tt>MachineInstr</tt></a> instances (defined
535    in <tt>include/llvm/CodeGen</tt>).  This representation is completely target
536    agnostic, representing instructions in their most abstract form: an opcode
537    and a series of operands.  This representation is designed to support both an
538    SSA representation for machine code, as well as a register allocated, non-SSA
539    form.</p>
540
541 <!-- ======================================================================= -->
542 <h3>
543   <a name="machineinstr">The <tt>MachineInstr</tt> class</a>
544 </h3>
545
546 <div>
547
548 <p>Target machine instructions are represented as instances of the
549    <tt>MachineInstr</tt> class.  This class is an extremely abstract way of
550    representing machine instructions.  In particular, it only keeps track of an
551    opcode number and a set of operands.</p>
552
553 <p>The opcode number is a simple unsigned integer that only has meaning to a
554    specific backend.  All of the instructions for a target should be defined in
555    the <tt>*InstrInfo.td</tt> file for the target. The opcode enum values are
556    auto-generated from this description.  The <tt>MachineInstr</tt> class does
557    not have any information about how to interpret the instruction (i.e., what
558    the semantics of the instruction are); for that you must refer to the
559    <tt><a href="#targetinstrinfo">TargetInstrInfo</a></tt> class.</p> 
560
561 <p>The operands of a machine instruction can be of several different types: a
562    register reference, a constant integer, a basic block reference, etc.  In
563    addition, a machine operand should be marked as a def or a use of the value
564    (though only registers are allowed to be defs).</p>
565
566 <p>By convention, the LLVM code generator orders instruction operands so that
567    all register definitions come before the register uses, even on architectures
568    that are normally printed in other orders.  For example, the SPARC add
569    instruction: "<tt>add %i1, %i2, %i3</tt>" adds the "%i1", and "%i2" registers
570    and stores the result into the "%i3" register.  In the LLVM code generator,
571    the operands should be stored as "<tt>%i3, %i1, %i2</tt>": with the
572    destination first.</p>
573
574 <p>Keeping destination (definition) operands at the beginning of the operand
575    list has several advantages.  In particular, the debugging printer will print
576    the instruction like this:</p>
577
578 <div class="doc_code">
579 <pre>
580 %r3 = add %i1, %i2
581 </pre>
582 </div>
583
584 <p>Also if the first operand is a def, it is easier to <a href="#buildmi">create
585    instructions</a> whose only def is the first operand.</p>
586
587 <!-- _______________________________________________________________________ -->
588 <h4>
589   <a name="buildmi">Using the <tt>MachineInstrBuilder.h</tt> functions</a>
590 </h4>
591
592 <div>
593
594 <p>Machine instructions are created by using the <tt>BuildMI</tt> functions,
595    located in the <tt>include/llvm/CodeGen/MachineInstrBuilder.h</tt> file.  The
596    <tt>BuildMI</tt> functions make it easy to build arbitrary machine
597    instructions.  Usage of the <tt>BuildMI</tt> functions look like this:</p>
598
599 <div class="doc_code">
600 <pre>
601 // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
602 // instruction.  The '1' specifies how many operands will be added.
603 MachineInstr *MI = BuildMI(X86::MOV32ri, 1, DestReg).addImm(42);
604
605 // Create the same instr, but insert it at the end of a basic block.
606 MachineBasicBlock &amp;MBB = ...
607 BuildMI(MBB, X86::MOV32ri, 1, DestReg).addImm(42);
608
609 // Create the same instr, but insert it before a specified iterator point.
610 MachineBasicBlock::iterator MBBI = ...
611 BuildMI(MBB, MBBI, X86::MOV32ri, 1, DestReg).addImm(42);
612
613 // Create a 'cmp Reg, 0' instruction, no destination reg.
614 MI = BuildMI(X86::CMP32ri, 2).addReg(Reg).addImm(0);
615 // Create an 'sahf' instruction which takes no operands and stores nothing.
616 MI = BuildMI(X86::SAHF, 0);
617
618 // Create a self looping branch instruction.
619 BuildMI(MBB, X86::JNE, 1).addMBB(&amp;MBB);
620 </pre>
621 </div>
622
623 <p>The key thing to remember with the <tt>BuildMI</tt> functions is that you
624    have to specify the number of operands that the machine instruction will
625    take.  This allows for efficient memory allocation.  You also need to specify
626    if operands default to be uses of values, not definitions.  If you need to
627    add a definition operand (other than the optional destination register), you
628    must explicitly mark it as such:</p>
629
630 <div class="doc_code">
631 <pre>
632 MI.addReg(Reg, RegState::Define);
633 </pre>
634 </div>
635
636 </div>
637
638 <!-- _______________________________________________________________________ -->
639 <h4>
640   <a name="fixedregs">Fixed (preassigned) registers</a>
641 </h4>
642
643 <div>
644
645 <p>One important issue that the code generator needs to be aware of is the
646    presence of fixed registers.  In particular, there are often places in the
647    instruction stream where the register allocator <em>must</em> arrange for a
648    particular value to be in a particular register.  This can occur due to
649    limitations of the instruction set (e.g., the X86 can only do a 32-bit divide
650    with the <tt>EAX</tt>/<tt>EDX</tt> registers), or external factors like
651    calling conventions.  In any case, the instruction selector should emit code
652    that copies a virtual register into or out of a physical register when
653    needed.</p>
654
655 <p>For example, consider this simple LLVM example:</p>
656
657 <div class="doc_code">
658 <pre>
659 define i32 @test(i32 %X, i32 %Y) {
660   %Z = udiv i32 %X, %Y
661   ret i32 %Z
662 }
663 </pre>
664 </div>
665
666 <p>The X86 instruction selector produces this machine code for the <tt>div</tt>
667    and <tt>ret</tt> (use "<tt>llc X.bc -march=x86 -print-machineinstrs</tt>" to
668    get this):</p>
669
670 <div class="doc_code">
671 <pre>
672 ;; Start of div
673 %EAX = mov %reg1024           ;; Copy X (in reg1024) into EAX
674 %reg1027 = sar %reg1024, 31
675 %EDX = mov %reg1027           ;; Sign extend X into EDX
676 idiv %reg1025                 ;; Divide by Y (in reg1025)
677 %reg1026 = mov %EAX           ;; Read the result (Z) out of EAX
678
679 ;; Start of ret
680 %EAX = mov %reg1026           ;; 32-bit return value goes in EAX
681 ret
682 </pre>
683 </div>
684
685 <p>By the end of code generation, the register allocator has coalesced the
686    registers and deleted the resultant identity moves producing the following
687    code:</p>
688
689 <div class="doc_code">
690 <pre>
691 ;; X is in EAX, Y is in ECX
692 mov %EAX, %EDX
693 sar %EDX, 31
694 idiv %ECX
695 ret 
696 </pre>
697 </div>
698
699 <p>This approach is extremely general (if it can handle the X86 architecture, it
700    can handle anything!) and allows all of the target specific knowledge about
701    the instruction stream to be isolated in the instruction selector.  Note that
702    physical registers should have a short lifetime for good code generation, and
703    all physical registers are assumed dead on entry to and exit from basic
704    blocks (before register allocation).  Thus, if you need a value to be live
705    across basic block boundaries, it <em>must</em> live in a virtual
706    register.</p>
707
708 </div>
709
710 <!-- _______________________________________________________________________ -->
711 <h4>
712   <a name="ssa">Machine code in SSA form</a>
713 </h4>
714
715 <div>
716
717 <p><tt>MachineInstr</tt>'s are initially selected in SSA-form, and are
718    maintained in SSA-form until register allocation happens.  For the most part,
719    this is trivially simple since LLVM is already in SSA form; LLVM PHI nodes
720    become machine code PHI nodes, and virtual registers are only allowed to have
721    a single definition.</p>
722
723 <p>After register allocation, machine code is no longer in SSA-form because
724    there are no virtual registers left in the code.</p>
725
726 </div>
727
728 </div>
729
730 <!-- ======================================================================= -->
731 <h3>
732   <a name="machinebasicblock">The <tt>MachineBasicBlock</tt> class</a>
733 </h3>
734
735 <div>
736
737 <p>The <tt>MachineBasicBlock</tt> class contains a list of machine instructions
738    (<tt><a href="#machineinstr">MachineInstr</a></tt> instances).  It roughly
739    corresponds to the LLVM code input to the instruction selector, but there can
740    be a one-to-many mapping (i.e. one LLVM basic block can map to multiple
741    machine basic blocks). The <tt>MachineBasicBlock</tt> class has a
742    "<tt>getBasicBlock</tt>" method, which returns the LLVM basic block that it
743    comes from.</p>
744
745 </div>
746
747 <!-- ======================================================================= -->
748 <h3>
749   <a name="machinefunction">The <tt>MachineFunction</tt> class</a>
750 </h3>
751
752 <div>
753
754 <p>The <tt>MachineFunction</tt> class contains a list of machine basic blocks
755    (<tt><a href="#machinebasicblock">MachineBasicBlock</a></tt> instances).  It
756    corresponds one-to-one with the LLVM function input to the instruction
757    selector.  In addition to a list of basic blocks,
758    the <tt>MachineFunction</tt> contains a a <tt>MachineConstantPool</tt>,
759    a <tt>MachineFrameInfo</tt>, a <tt>MachineFunctionInfo</tt>, and a
760    <tt>MachineRegisterInfo</tt>.  See
761    <tt>include/llvm/CodeGen/MachineFunction.h</tt> for more information.</p>
762
763 </div>
764
765 <!-- ======================================================================= -->
766 <h3>
767   <a name="machineinstrbundle"><tt>MachineInstr Bundles</tt></a>
768 </h3>
769
770 <div>
771
772 <p>LLVM code generator can model sequences of instructions as MachineInstr
773    bundles. A MI bundle can model a VLIW group / pack which contains an
774    arbitrary number of parallel instructions. It can also be used to model
775    a sequential list of instructions (potentially with data dependencies) that
776    cannot be legally separated (e.g. ARM Thumb2 IT blocks).</p>
777
778 <p>Conceptually a MI bundle is a MI with a number of other MIs nested within:
779 </p>
780
781 <div class="doc_code">
782 <pre>
783 --------------
784 |   Bundle   | ---------
785 --------------          \
786        |           ----------------
787        |           |      MI      |
788        |           ----------------
789        |                   |
790        |           ----------------
791        |           |      MI      |
792        |           ----------------
793        |                   |
794        |           ----------------
795        |           |      MI      |
796        |           ----------------
797        |
798 --------------
799 |   Bundle   | --------
800 --------------         \
801        |           ----------------
802        |           |      MI      |
803        |           ----------------
804        |                   |
805        |           ----------------
806        |           |      MI      |
807        |           ----------------
808        |                   |
809        |                  ...
810        |
811 --------------
812 |   Bundle   | --------
813 --------------         \
814        |
815       ...
816 </pre>
817 </div>
818
819 <p> MI bundle support does not change the physical representations of
820     MachineBasicBlock and MachineInstr. All the MIs (including top level and
821     nested ones) are stored as sequential list of MIs. The "bundled" MIs are
822     marked with the 'InsideBundle' flag. A top level MI with the special BUNDLE
823     opcode is used to represent the start of a bundle. It's legal to mix BUNDLE
824     MIs with indiviual MIs that are not inside bundles nor represent bundles.
825 </p>
826
827 <p> MachineInstr passes should operate on a MI bundle as a single unit. Member
828     methods have been taught to correctly handle bundles and MIs inside bundles.
829     The MachineBasicBlock iterator has been modified to skip over bundled MIs to
830     enforce the bundle-as-a-single-unit concept. An alternative iterator
831     instr_iterator has been added to MachineBasicBlock to allow passes to
832     iterate over all of the MIs in a MachineBasicBlock, including those which
833     are nested inside bundles. The top level BUNDLE instruction must have the
834     correct set of register MachineOperand's that represent the cumulative
835     inputs and outputs of the bundled MIs.</p>
836
837 <p> Packing / bundling of MachineInstr's should be done as part of the register
838     allocation super-pass. More specifically, the pass which determines what
839     MIs should be bundled together must be done after code generator exits SSA
840     form (i.e. after two-address pass, PHI elimination, and copy coalescing).
841     Bundles should only be finalized (i.e. adding BUNDLE MIs and input and
842     output register MachineOperands) after virtual registers have been
843     rewritten into physical registers. This requirement eliminates the need to
844     add virtual register operands to BUNDLE instructions which would effectively
845     double the virtual register def and use lists.</p>
846
847 </div>
848
849 <!-- *********************************************************************** -->
850 <h2>
851   <a name="mc">The "MC" Layer</a>
852 </h2>
853 <!-- *********************************************************************** -->
854
855 <div>
856
857 <p>
858 The MC Layer is used to represent and process code at the raw machine code
859 level, devoid of "high level" information like "constant pools", "jump tables",
860 "global variables" or anything like that.  At this level, LLVM handles things
861 like label names, machine instructions, and sections in the object file.  The
862 code in this layer is used for a number of important purposes: the tail end of
863 the code generator uses it to write a .s or .o file, and it is also used by the
864 llvm-mc tool to implement standalone machine code assemblers and disassemblers.
865 </p>
866
867 <p>
868 This section describes some of the important classes.  There are also a number
869 of important subsystems that interact at this layer, they are described later
870 in this manual.
871 </p>
872
873 <!-- ======================================================================= -->
874 <h3>
875   <a name="mcstreamer">The <tt>MCStreamer</tt> API</a>
876 </h3>
877
878 <div>
879
880 <p>
881 MCStreamer is best thought of as an assembler API.  It is an abstract API which
882 is <em>implemented</em> in different ways (e.g. to output a .s file, output an
883 ELF .o file, etc) but whose API correspond directly to what you see in a .s
884 file.  MCStreamer has one method per directive, such as EmitLabel,
885 EmitSymbolAttribute, SwitchSection, EmitValue (for .byte, .word), etc, which
886 directly correspond to assembly level directives.  It also has an
887 EmitInstruction method, which is used to output an MCInst to the streamer.
888 </p>
889
890 <p>
891 This API is most important for two clients: the llvm-mc stand-alone assembler is
892 effectively a parser that parses a line, then invokes a method on MCStreamer. In
893 the code generator, the <a href="#codeemit">Code Emission</a> phase of the code
894 generator lowers higher level LLVM IR and Machine* constructs down to the MC
895 layer, emitting directives through MCStreamer.</p>
896
897 <p>
898 On the implementation side of MCStreamer, there are two major implementations:
899 one for writing out a .s file (MCAsmStreamer), and one for writing out a .o
900 file (MCObjectStreamer).  MCAsmStreamer is a straight-forward implementation
901 that prints out a directive for each method (e.g. EmitValue -&gt; .byte), but
902 MCObjectStreamer implements a full assembler.
903 </p>
904
905 </div>
906
907 <!-- ======================================================================= -->
908 <h3>
909   <a name="mccontext">The <tt>MCContext</tt> class</a>
910 </h3>
911
912 <div>
913
914 <p>
915 The MCContext class is the owner of a variety of uniqued data structures at the
916 MC layer, including symbols, sections, etc.  As such, this is the class that you
917 interact with to create symbols and sections.  This class can not be subclassed.
918 </p>
919
920 </div>
921
922 <!-- ======================================================================= -->
923 <h3>
924   <a name="mcsymbol">The <tt>MCSymbol</tt> class</a>
925 </h3>
926
927 <div>
928
929 <p>
930 The MCSymbol class represents a symbol (aka label) in the assembly file.  There
931 are two interesting kinds of symbols: assembler temporary symbols, and normal
932 symbols.  Assembler temporary symbols are used and processed by the assembler
933 but are discarded when the object file is produced.  The distinction is usually
934 represented by adding a prefix to the label, for example "L" labels are
935 assembler temporary labels in MachO.
936 </p>
937
938 <p>MCSymbols are created by MCContext and uniqued there.  This means that
939 MCSymbols can be compared for pointer equivalence to find out if they are the
940 same symbol.  Note that pointer inequality does not guarantee the labels will
941 end up at different addresses though.  It's perfectly legal to output something
942 like this to the .s file:<p>
943
944 <pre>
945   foo:
946   bar:
947     .byte 4
948 </pre>
949
950 <p>In this case, both the foo and bar symbols will have the same address.</p>
951
952 </div>
953
954 <!-- ======================================================================= -->
955 <h3>
956   <a name="mcsection">The <tt>MCSection</tt> class</a>
957 </h3>
958
959 <div>
960
961 <p>
962 The MCSection class represents an object-file specific section. It is subclassed
963 by object file specific implementations (e.g. <tt>MCSectionMachO</tt>, 
964 <tt>MCSectionCOFF</tt>, <tt>MCSectionELF</tt>) and these are created and uniqued
965 by MCContext.  The MCStreamer has a notion of the current section, which can be
966 changed with the SwitchToSection method (which corresponds to a ".section"
967 directive in a .s file).
968 </p>
969
970 </div>
971
972 <!-- ======================================================================= -->
973 <h3>
974   <a name="mcinst">The <tt>MCInst</tt> class</a>
975 </h3>
976
977 <div>
978
979 <p>
980 The MCInst class is a target-independent representation of an instruction.  It
981 is a simple class (much more so than <a href="#machineinstr">MachineInstr</a>)
982 that holds a target-specific opcode and a vector of MCOperands.  MCOperand, in
983 turn, is a simple discriminated union of three cases: 1) a simple immediate, 
984 2) a target register ID, 3) a symbolic expression (e.g. "Lfoo-Lbar+42") as an
985 MCExpr.
986 </p>
987
988 <p>MCInst is the common currency used to represent machine instructions at the
989 MC layer.  It is the type used by the instruction encoder, the instruction
990 printer, and the type generated by the assembly parser and disassembler.
991 </p>
992
993 </div>
994
995 </div>
996
997 <!-- *********************************************************************** -->
998 <h2>
999   <a name="codegenalgs">Target-independent code generation algorithms</a>
1000 </h2>
1001 <!-- *********************************************************************** -->
1002
1003 <div>
1004
1005 <p>This section documents the phases described in the
1006    <a href="#high-level-design">high-level design of the code generator</a>.
1007    It explains how they work and some of the rationale behind their design.</p>
1008
1009 <!-- ======================================================================= -->
1010 <h3>
1011   <a name="instselect">Instruction Selection</a>
1012 </h3>
1013
1014 <div>
1015
1016 <p>Instruction Selection is the process of translating LLVM code presented to
1017    the code generator into target-specific machine instructions.  There are
1018    several well-known ways to do this in the literature.  LLVM uses a
1019    SelectionDAG based instruction selector.</p>
1020
1021 <p>Portions of the DAG instruction selector are generated from the target
1022    description (<tt>*.td</tt>) files.  Our goal is for the entire instruction
1023    selector to be generated from these <tt>.td</tt> files, though currently
1024    there are still things that require custom C++ code.</p>
1025
1026 <!-- _______________________________________________________________________ -->
1027 <h4>
1028   <a name="selectiondag_intro">Introduction to SelectionDAGs</a>
1029 </h4>
1030
1031 <div>
1032
1033 <p>The SelectionDAG provides an abstraction for code representation in a way
1034    that is amenable to instruction selection using automatic techniques
1035    (e.g. dynamic-programming based optimal pattern matching selectors). It is
1036    also well-suited to other phases of code generation; in particular,
1037    instruction scheduling (SelectionDAG's are very close to scheduling DAGs
1038    post-selection).  Additionally, the SelectionDAG provides a host
1039    representation where a large variety of very-low-level (but
1040    target-independent) <a href="#selectiondag_optimize">optimizations</a> may be
1041    performed; ones which require extensive information about the instructions
1042    efficiently supported by the target.</p>
1043
1044 <p>The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the
1045    <tt>SDNode</tt> class.  The primary payload of the <tt>SDNode</tt> is its
1046    operation code (Opcode) that indicates what operation the node performs and
1047    the operands to the operation.  The various operation node types are
1048    described at the top of the <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>
1049    file.</p>
1050
1051 <p>Although most operations define a single value, each node in the graph may
1052    define multiple values.  For example, a combined div/rem operation will
1053    define both the dividend and the remainder. Many other situations require
1054    multiple values as well.  Each node also has some number of operands, which
1055    are edges to the node defining the used value.  Because nodes may define
1056    multiple values, edges are represented by instances of the <tt>SDValue</tt>
1057    class, which is a <tt>&lt;SDNode, unsigned&gt;</tt> pair, indicating the node
1058    and result value being used, respectively.  Each value produced by
1059    an <tt>SDNode</tt> has an associated <tt>MVT</tt> (Machine Value Type)
1060    indicating what the type of the value is.</p>
1061
1062 <p>SelectionDAGs contain two different kinds of values: those that represent
1063    data flow and those that represent control flow dependencies.  Data values
1064    are simple edges with an integer or floating point value type.  Control edges
1065    are represented as "chain" edges which are of type <tt>MVT::Other</tt>.
1066    These edges provide an ordering between nodes that have side effects (such as
1067    loads, stores, calls, returns, etc).  All nodes that have side effects should
1068    take a token chain as input and produce a new one as output.  By convention,
1069    token chain inputs are always operand #0, and chain results are always the
1070    last value produced by an operation.</p>
1071
1072 <p>A SelectionDAG has designated "Entry" and "Root" nodes.  The Entry node is
1073    always a marker node with an Opcode of <tt>ISD::EntryToken</tt>.  The Root
1074    node is the final side-effecting node in the token chain. For example, in a
1075    single basic block function it would be the return node.</p>
1076
1077 <p>One important concept for SelectionDAGs is the notion of a "legal" vs.
1078    "illegal" DAG.  A legal DAG for a target is one that only uses supported
1079    operations and supported types.  On a 32-bit PowerPC, for example, a DAG with
1080    a value of type i1, i8, i16, or i64 would be illegal, as would a DAG that
1081    uses a SREM or UREM operation.  The
1082    <a href="#selectinodag_legalize_types">legalize types</a> and
1083    <a href="#selectiondag_legalize">legalize operations</a> phases are
1084    responsible for turning an illegal DAG into a legal DAG.</p>
1085
1086 </div>
1087
1088 <!-- _______________________________________________________________________ -->
1089 <h4>
1090   <a name="selectiondag_process">SelectionDAG Instruction Selection Process</a>
1091 </h4>
1092
1093 <div>
1094
1095 <p>SelectionDAG-based instruction selection consists of the following steps:</p>
1096
1097 <ol>
1098   <li><a href="#selectiondag_build">Build initial DAG</a> &mdash; This stage
1099       performs a simple translation from the input LLVM code to an illegal
1100       SelectionDAG.</li>
1101
1102   <li><a href="#selectiondag_optimize">Optimize SelectionDAG</a> &mdash; This
1103       stage performs simple optimizations on the SelectionDAG to simplify it,
1104       and recognize meta instructions (like rotates
1105       and <tt>div</tt>/<tt>rem</tt> pairs) for targets that support these meta
1106       operations.  This makes the resultant code more efficient and
1107       the <a href="#selectiondag_select">select instructions from DAG</a> phase
1108       (below) simpler.</li>
1109
1110   <li><a href="#selectiondag_legalize_types">Legalize SelectionDAG Types</a>
1111       &mdash; This stage transforms SelectionDAG nodes to eliminate any types
1112       that are unsupported on the target.</li>
1113
1114   <li><a href="#selectiondag_optimize">Optimize SelectionDAG</a> &mdash; The
1115       SelectionDAG optimizer is run to clean up redundancies exposed by type
1116       legalization.</li>
1117
1118   <li><a href="#selectiondag_legalize">Legalize SelectionDAG Ops</a> &mdash;
1119       This stage transforms SelectionDAG nodes to eliminate any operations 
1120       that are unsupported on the target.</li>
1121
1122   <li><a href="#selectiondag_optimize">Optimize SelectionDAG</a> &mdash; The
1123       SelectionDAG optimizer is run to eliminate inefficiencies introduced by
1124       operation legalization.</li>
1125
1126   <li><a href="#selectiondag_select">Select instructions from DAG</a> &mdash;
1127       Finally, the target instruction selector matches the DAG operations to
1128       target instructions.  This process translates the target-independent input
1129       DAG into another DAG of target instructions.</li>
1130
1131   <li><a href="#selectiondag_sched">SelectionDAG Scheduling and Formation</a>
1132       &mdash; The last phase assigns a linear order to the instructions in the
1133       target-instruction DAG and emits them into the MachineFunction being
1134       compiled.  This step uses traditional prepass scheduling techniques.</li>
1135 </ol>
1136
1137 <p>After all of these steps are complete, the SelectionDAG is destroyed and the
1138    rest of the code generation passes are run.</p>
1139
1140 <p>One great way to visualize what is going on here is to take advantage of a
1141    few LLC command line options.  The following options pop up a window
1142    displaying the SelectionDAG at specific times (if you only get errors printed
1143    to the console while using this, you probably
1144    <a href="ProgrammersManual.html#ViewGraph">need to configure your system</a>
1145    to add support for it).</p>
1146
1147 <ul>
1148   <li><tt>-view-dag-combine1-dags</tt> displays the DAG after being built,
1149       before the first optimization pass.</li>
1150
1151   <li><tt>-view-legalize-dags</tt> displays the DAG before Legalization.</li>
1152
1153   <li><tt>-view-dag-combine2-dags</tt> displays the DAG before the second
1154       optimization pass.</li>
1155
1156   <li><tt>-view-isel-dags</tt> displays the DAG before the Select phase.</li>
1157
1158   <li><tt>-view-sched-dags</tt> displays the DAG before Scheduling.</li>
1159 </ul>
1160
1161 <p>The <tt>-view-sunit-dags</tt> displays the Scheduler's dependency graph.
1162    This graph is based on the final SelectionDAG, with nodes that must be
1163    scheduled together bundled into a single scheduling-unit node, and with
1164    immediate operands and other nodes that aren't relevant for scheduling
1165    omitted.</p>
1166
1167 </div>
1168
1169 <!-- _______________________________________________________________________ -->
1170 <h4>
1171   <a name="selectiondag_build">Initial SelectionDAG Construction</a>
1172 </h4>
1173
1174 <div>
1175
1176 <p>The initial SelectionDAG is na&iuml;vely peephole expanded from the LLVM
1177    input by the <tt>SelectionDAGLowering</tt> class in the
1178    <tt>lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp</tt> file.  The intent of
1179    this pass is to expose as much low-level, target-specific details to the
1180    SelectionDAG as possible.  This pass is mostly hard-coded (e.g. an
1181    LLVM <tt>add</tt> turns into an <tt>SDNode add</tt> while a
1182    <tt>getelementptr</tt> is expanded into the obvious arithmetic). This pass
1183    requires target-specific hooks to lower calls, returns, varargs, etc.  For
1184    these features, the <tt><a href="#targetlowering">TargetLowering</a></tt>
1185    interface is used.</p>
1186
1187 </div>
1188
1189 <!-- _______________________________________________________________________ -->
1190 <h4>
1191   <a name="selectiondag_legalize_types">SelectionDAG LegalizeTypes Phase</a>
1192 </h4>
1193
1194 <div>
1195
1196 <p>The Legalize phase is in charge of converting a DAG to only use the types
1197    that are natively supported by the target.</p>
1198
1199 <p>There are two main ways of converting values of unsupported scalar types to
1200    values of supported types: converting small types to larger types
1201    ("promoting"), and breaking up large integer types into smaller ones
1202    ("expanding").  For example, a target might require that all f32 values are
1203    promoted to f64 and that all i1/i8/i16 values are promoted to i32.  The same
1204    target might require that all i64 values be expanded into pairs of i32
1205    values.  These changes can insert sign and zero extensions as needed to make
1206    sure that the final code has the same behavior as the input.</p>
1207
1208 <p>There are two main ways of converting values of unsupported vector types to
1209    value of supported types: splitting vector types, multiple times if
1210    necessary, until a legal type is found, and extending vector types by adding
1211    elements to the end to round them out to legal types ("widening").  If a
1212    vector gets split all the way down to single-element parts with no supported
1213    vector type being found, the elements are converted to scalars
1214    ("scalarizing").</p>
1215
1216 <p>A target implementation tells the legalizer which types are supported (and
1217    which register class to use for them) by calling the
1218    <tt>addRegisterClass</tt> method in its TargetLowering constructor.</p>
1219
1220 </div>
1221
1222 <!-- _______________________________________________________________________ -->
1223 <h4>
1224   <a name="selectiondag_legalize">SelectionDAG Legalize Phase</a>
1225 </h4>
1226
1227 <div>
1228
1229 <p>The Legalize phase is in charge of converting a DAG to only use the
1230    operations that are natively supported by the target.</p>
1231
1232 <p>Targets often have weird constraints, such as not supporting every operation
1233    on every supported datatype (e.g. X86 does not support byte conditional moves
1234    and PowerPC does not support sign-extending loads from a 16-bit memory
1235    location).  Legalize takes care of this by open-coding another sequence of
1236    operations to emulate the operation ("expansion"), by promoting one type to a
1237    larger type that supports the operation ("promotion"), or by using a
1238    target-specific hook to implement the legalization ("custom").</p>
1239
1240 <p>A target implementation tells the legalizer which operations are not
1241    supported (and which of the above three actions to take) by calling the
1242    <tt>setOperationAction</tt> method in its <tt>TargetLowering</tt>
1243    constructor.</p>
1244
1245 <p>Prior to the existence of the Legalize passes, we required that every target
1246    <a href="#selectiondag_optimize">selector</a> supported and handled every
1247    operator and type even if they are not natively supported.  The introduction
1248    of the Legalize phases allows all of the canonicalization patterns to be
1249    shared across targets, and makes it very easy to optimize the canonicalized
1250    code because it is still in the form of a DAG.</p>
1251
1252 </div>
1253
1254 <!-- _______________________________________________________________________ -->
1255 <h4>
1256   <a name="selectiondag_optimize">
1257     SelectionDAG Optimization Phase: the DAG Combiner
1258   </a>
1259 </h4>
1260
1261 <div>
1262
1263 <p>The SelectionDAG optimization phase is run multiple times for code
1264    generation, immediately after the DAG is built and once after each
1265    legalization.  The first run of the pass allows the initial code to be
1266    cleaned up (e.g. performing optimizations that depend on knowing that the
1267    operators have restricted type inputs).  Subsequent runs of the pass clean up
1268    the messy code generated by the Legalize passes, which allows Legalize to be
1269    very simple (it can focus on making code legal instead of focusing on
1270    generating <em>good</em> and legal code).</p>
1271
1272 <p>One important class of optimizations performed is optimizing inserted sign
1273    and zero extension instructions.  We currently use ad-hoc techniques, but
1274    could move to more rigorous techniques in the future.  Here are some good
1275    papers on the subject:</p>
1276
1277 <p>"<a href="http://www.eecs.harvard.edu/~nr/pubs/widen-abstract.html">Widening
1278    integer arithmetic</a>"<br>
1279    Kevin Redwine and Norman Ramsey<br>
1280    International Conference on Compiler Construction (CC) 2004</p>
1281
1282 <p>"<a href="http://portal.acm.org/citation.cfm?doid=512529.512552">Effective
1283    sign extension elimination</a>"<br>
1284    Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani<br>
1285    Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design
1286    and Implementation.</p>
1287
1288 </div>
1289
1290 <!-- _______________________________________________________________________ -->
1291 <h4>
1292   <a name="selectiondag_select">SelectionDAG Select Phase</a>
1293 </h4>
1294
1295 <div>
1296
1297 <p>The Select phase is the bulk of the target-specific code for instruction
1298    selection.  This phase takes a legal SelectionDAG as input, pattern matches
1299    the instructions supported by the target to this DAG, and produces a new DAG
1300    of target code.  For example, consider the following LLVM fragment:</p>
1301
1302 <div class="doc_code">
1303 <pre>
1304 %t1 = fadd float %W, %X
1305 %t2 = fmul float %t1, %Y
1306 %t3 = fadd float %t2, %Z
1307 </pre>
1308 </div>
1309
1310 <p>This LLVM code corresponds to a SelectionDAG that looks basically like
1311    this:</p>
1312
1313 <div class="doc_code">
1314 <pre>
1315 (fadd:f32 (fmul:f32 (fadd:f32 W, X), Y), Z)
1316 </pre>
1317 </div>
1318
1319 <p>If a target supports floating point multiply-and-add (FMA) operations, one of
1320    the adds can be merged with the multiply.  On the PowerPC, for example, the
1321    output of the instruction selector might look like this DAG:</p>
1322
1323 <div class="doc_code">
1324 <pre>
1325 (FMADDS (FADDS W, X), Y, Z)
1326 </pre>
1327 </div>
1328
1329 <p>The <tt>FMADDS</tt> instruction is a ternary instruction that multiplies its
1330 first two operands and adds the third (as single-precision floating-point
1331 numbers).  The <tt>FADDS</tt> instruction is a simple binary single-precision
1332 add instruction.  To perform this pattern match, the PowerPC backend includes
1333 the following instruction definitions:</p>
1334
1335 <div class="doc_code">
1336 <pre>
1337 def FMADDS : AForm_1&lt;59, 29,
1338                     (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRC, F4RC:$FRB),
1339                     "fmadds $FRT, $FRA, $FRC, $FRB",
1340                     [<b>(set F4RC:$FRT, (fadd (fmul F4RC:$FRA, F4RC:$FRC),
1341                                            F4RC:$FRB))</b>]&gt;;
1342 def FADDS : AForm_2&lt;59, 21,
1343                     (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRB),
1344                     "fadds $FRT, $FRA, $FRB",
1345                     [<b>(set F4RC:$FRT, (fadd F4RC:$FRA, F4RC:$FRB))</b>]&gt;;
1346 </pre>
1347 </div>
1348
1349 <p>The portion of the instruction definition in bold indicates the pattern used
1350    to match the instruction.  The DAG operators
1351    (like <tt>fmul</tt>/<tt>fadd</tt>) are defined in
1352    the <tt>include/llvm/Target/TargetSelectionDAG.td</tt> file.  "
1353    <tt>F4RC</tt>" is the register class of the input and result values.</p>
1354
1355 <p>The TableGen DAG instruction selector generator reads the instruction
1356    patterns in the <tt>.td</tt> file and automatically builds parts of the
1357    pattern matching code for your target.  It has the following strengths:</p>
1358
1359 <ul>
1360   <li>At compiler-compiler time, it analyzes your instruction patterns and tells
1361       you if your patterns make sense or not.</li>
1362
1363   <li>It can handle arbitrary constraints on operands for the pattern match.  In
1364       particular, it is straight-forward to say things like "match any immediate
1365       that is a 13-bit sign-extended value".  For examples, see the
1366       <tt>immSExt16</tt> and related <tt>tblgen</tt> classes in the PowerPC
1367       backend.</li>
1368
1369   <li>It knows several important identities for the patterns defined.  For
1370       example, it knows that addition is commutative, so it allows the
1371       <tt>FMADDS</tt> pattern above to match "<tt>(fadd X, (fmul Y, Z))</tt>" as
1372       well as "<tt>(fadd (fmul X, Y), Z)</tt>", without the target author having
1373       to specially handle this case.</li>
1374
1375   <li>It has a full-featured type-inferencing system.  In particular, you should
1376       rarely have to explicitly tell the system what type parts of your patterns
1377       are.  In the <tt>FMADDS</tt> case above, we didn't have to tell
1378       <tt>tblgen</tt> that all of the nodes in the pattern are of type 'f32'.
1379       It was able to infer and propagate this knowledge from the fact that
1380       <tt>F4RC</tt> has type 'f32'.</li>
1381
1382   <li>Targets can define their own (and rely on built-in) "pattern fragments".
1383       Pattern fragments are chunks of reusable patterns that get inlined into
1384       your patterns during compiler-compiler time.  For example, the integer
1385       "<tt>(not x)</tt>" operation is actually defined as a pattern fragment
1386       that expands as "<tt>(xor x, -1)</tt>", since the SelectionDAG does not
1387       have a native '<tt>not</tt>' operation.  Targets can define their own
1388       short-hand fragments as they see fit.  See the definition of
1389       '<tt>not</tt>' and '<tt>ineg</tt>' for examples.</li>
1390
1391   <li>In addition to instructions, targets can specify arbitrary patterns that
1392       map to one or more instructions using the 'Pat' class.  For example, the
1393       PowerPC has no way to load an arbitrary integer immediate into a register
1394       in one instruction. To tell tblgen how to do this, it defines:
1395       <br>
1396       <br>
1397 <div class="doc_code">
1398 <pre>
1399 // Arbitrary immediate support.  Implement in terms of LIS/ORI.
1400 def : Pat&lt;(i32 imm:$imm),
1401           (ORI (LIS (HI16 imm:$imm)), (LO16 imm:$imm))&gt;;
1402 </pre>
1403 </div>
1404       <br>
1405       If none of the single-instruction patterns for loading an immediate into a
1406       register match, this will be used.  This rule says "match an arbitrary i32
1407       immediate, turning it into an <tt>ORI</tt> ('or a 16-bit immediate') and
1408       an <tt>LIS</tt> ('load 16-bit immediate, where the immediate is shifted to
1409       the left 16 bits') instruction".  To make this work, the
1410       <tt>LO16</tt>/<tt>HI16</tt> node transformations are used to manipulate
1411       the input immediate (in this case, take the high or low 16-bits of the
1412       immediate).</li>
1413
1414   <li>While the system does automate a lot, it still allows you to write custom
1415       C++ code to match special cases if there is something that is hard to
1416       express.</li>
1417 </ul>
1418
1419 <p>While it has many strengths, the system currently has some limitations,
1420    primarily because it is a work in progress and is not yet finished:</p>
1421
1422 <ul>
1423   <li>Overall, there is no way to define or match SelectionDAG nodes that define
1424       multiple values (e.g. <tt>SMUL_LOHI</tt>, <tt>LOAD</tt>, <tt>CALL</tt>,
1425       etc).  This is the biggest reason that you currently still <em>have
1426       to</em> write custom C++ code for your instruction selector.</li>
1427
1428   <li>There is no great way to support matching complex addressing modes yet.
1429       In the future, we will extend pattern fragments to allow them to define
1430       multiple values (e.g. the four operands of the <a href="#x86_memory">X86
1431       addressing mode</a>, which are currently matched with custom C++ code).
1432       In addition, we'll extend fragments so that a fragment can match multiple
1433       different patterns.</li>
1434
1435   <li>We don't automatically infer flags like isStore/isLoad yet.</li>
1436
1437   <li>We don't automatically generate the set of supported registers and
1438       operations for the <a href="#selectiondag_legalize">Legalizer</a>
1439       yet.</li>
1440
1441   <li>We don't have a way of tying in custom legalized nodes yet.</li>
1442 </ul>
1443
1444 <p>Despite these limitations, the instruction selector generator is still quite
1445    useful for most of the binary and logical operations in typical instruction
1446    sets.  If you run into any problems or can't figure out how to do something,
1447    please let Chris know!</p>
1448
1449 </div>
1450
1451 <!-- _______________________________________________________________________ -->
1452 <h4>
1453   <a name="selectiondag_sched">SelectionDAG Scheduling and Formation Phase</a>
1454 </h4>
1455
1456 <div>
1457
1458 <p>The scheduling phase takes the DAG of target instructions from the selection
1459    phase and assigns an order.  The scheduler can pick an order depending on
1460    various constraints of the machines (i.e. order for minimal register pressure
1461    or try to cover instruction latencies).  Once an order is established, the
1462    DAG is converted to a list
1463    of <tt><a href="#machineinstr">MachineInstr</a></tt>s and the SelectionDAG is
1464    destroyed.</p>
1465
1466 <p>Note that this phase is logically separate from the instruction selection
1467    phase, but is tied to it closely in the code because it operates on
1468    SelectionDAGs.</p>
1469
1470 </div>
1471
1472 <!-- _______________________________________________________________________ -->
1473 <h4>
1474   <a name="selectiondag_future">Future directions for the SelectionDAG</a>
1475 </h4>
1476
1477 <div>
1478
1479 <ol>
1480   <li>Optional function-at-a-time selection.</li>
1481
1482   <li>Auto-generate entire selector from <tt>.td</tt> file.</li>
1483 </ol>
1484
1485 </div>
1486  
1487 </div>
1488
1489 <!-- ======================================================================= -->
1490 <h3>
1491   <a name="ssamco">SSA-based Machine Code Optimizations</a>
1492 </h3>
1493 <div><p>To Be Written</p></div>
1494
1495 <!-- ======================================================================= -->
1496 <h3>
1497   <a name="liveintervals">Live Intervals</a>
1498 </h3>
1499
1500 <div>
1501
1502 <p>Live Intervals are the ranges (intervals) where a variable is <i>live</i>.
1503    They are used by some <a href="#regalloc">register allocator</a> passes to
1504    determine if two or more virtual registers which require the same physical
1505    register are live at the same point in the program (i.e., they conflict).
1506    When this situation occurs, one virtual register must be <i>spilled</i>.</p>
1507
1508 <!-- _______________________________________________________________________ -->
1509 <h4>
1510   <a name="livevariable_analysis">Live Variable Analysis</a>
1511 </h4>
1512
1513 <div>
1514
1515 <p>The first step in determining the live intervals of variables is to calculate
1516    the set of registers that are immediately dead after the instruction (i.e.,
1517    the instruction calculates the value, but it is never used) and the set of
1518    registers that are used by the instruction, but are never used after the
1519    instruction (i.e., they are killed). Live variable information is computed
1520    for each <i>virtual</i> register and <i>register allocatable</i> physical
1521    register in the function.  This is done in a very efficient manner because it
1522    uses SSA to sparsely compute lifetime information for virtual registers
1523    (which are in SSA form) and only has to track physical registers within a
1524    block.  Before register allocation, LLVM can assume that physical registers
1525    are only live within a single basic block.  This allows it to do a single,
1526    local analysis to resolve physical register lifetimes within each basic
1527    block. If a physical register is not register allocatable (e.g., a stack
1528    pointer or condition codes), it is not tracked.</p>
1529
1530 <p>Physical registers may be live in to or out of a function. Live in values are
1531    typically arguments in registers. Live out values are typically return values
1532    in registers. Live in values are marked as such, and are given a dummy
1533    "defining" instruction during live intervals analysis. If the last basic
1534    block of a function is a <tt>return</tt>, then it's marked as using all live
1535    out values in the function.</p>
1536
1537 <p><tt>PHI</tt> nodes need to be handled specially, because the calculation of
1538    the live variable information from a depth first traversal of the CFG of the
1539    function won't guarantee that a virtual register used by the <tt>PHI</tt>
1540    node is defined before it's used. When a <tt>PHI</tt> node is encountered,
1541    only the definition is handled, because the uses will be handled in other
1542    basic blocks.</p>
1543
1544 <p>For each <tt>PHI</tt> node of the current basic block, we simulate an
1545    assignment at the end of the current basic block and traverse the successor
1546    basic blocks. If a successor basic block has a <tt>PHI</tt> node and one of
1547    the <tt>PHI</tt> node's operands is coming from the current basic block, then
1548    the variable is marked as <i>alive</i> within the current basic block and all
1549    of its predecessor basic blocks, until the basic block with the defining
1550    instruction is encountered.</p>
1551
1552 </div>
1553
1554 <!-- _______________________________________________________________________ -->
1555 <h4>
1556   <a name="liveintervals_analysis">Live Intervals Analysis</a>
1557 </h4>
1558
1559 <div>
1560
1561 <p>We now have the information available to perform the live intervals analysis
1562    and build the live intervals themselves.  We start off by numbering the basic
1563    blocks and machine instructions.  We then handle the "live-in" values.  These
1564    are in physical registers, so the physical register is assumed to be killed
1565    by the end of the basic block.  Live intervals for virtual registers are
1566    computed for some ordering of the machine instructions <tt>[1, N]</tt>.  A
1567    live interval is an interval <tt>[i, j)</tt>, where <tt>1 &lt;= i &lt;= j
1568    &lt; N</tt>, for which a variable is live.</p>
1569
1570 <p><i><b>More to come...</b></i></p>
1571
1572 </div>
1573
1574 </div>
1575
1576 <!-- ======================================================================= -->
1577 <h3>
1578   <a name="regalloc">Register Allocation</a>
1579 </h3>
1580
1581 <div>
1582
1583 <p>The <i>Register Allocation problem</i> consists in mapping a program
1584    <i>P<sub>v</sub></i>, that can use an unbounded number of virtual registers,
1585    to a program <i>P<sub>p</sub></i> that contains a finite (possibly small)
1586    number of physical registers. Each target architecture has a different number
1587    of physical registers. If the number of physical registers is not enough to
1588    accommodate all the virtual registers, some of them will have to be mapped
1589    into memory. These virtuals are called <i>spilled virtuals</i>.</p>
1590
1591 <!-- _______________________________________________________________________ -->
1592
1593 <h4>
1594   <a name="regAlloc_represent">How registers are represented in LLVM</a>
1595 </h4>
1596
1597 <div>
1598
1599 <p>In LLVM, physical registers are denoted by integer numbers that normally
1600    range from 1 to 1023. To see how this numbering is defined for a particular
1601    architecture, you can read the <tt>GenRegisterNames.inc</tt> file for that
1602    architecture. For instance, by
1603    inspecting <tt>lib/Target/X86/X86GenRegisterNames.inc</tt> we see that the
1604    32-bit register <tt>EAX</tt> is denoted by 15, and the MMX register
1605    <tt>MM0</tt> is mapped to 48.</p>
1606
1607 <p>Some architectures contain registers that share the same physical location. A
1608    notable example is the X86 platform. For instance, in the X86 architecture,
1609    the registers <tt>EAX</tt>, <tt>AX</tt> and <tt>AL</tt> share the first eight
1610    bits. These physical registers are marked as <i>aliased</i> in LLVM. Given a
1611    particular architecture, you can check which registers are aliased by
1612    inspecting its <tt>RegisterInfo.td</tt> file. Moreover, the method
1613    <tt>TargetRegisterInfo::getAliasSet(p_reg)</tt> returns an array containing
1614    all the physical registers aliased to the register <tt>p_reg</tt>.</p>
1615
1616 <p>Physical registers, in LLVM, are grouped in <i>Register Classes</i>.
1617    Elements in the same register class are functionally equivalent, and can be
1618    interchangeably used. Each virtual register can only be mapped to physical
1619    registers of a particular class. For instance, in the X86 architecture, some
1620    virtuals can only be allocated to 8 bit registers.  A register class is
1621    described by <tt>TargetRegisterClass</tt> objects.  To discover if a virtual
1622    register is compatible with a given physical, this code can be used:</p>
1623
1624 <div class="doc_code">
1625 <pre>
1626 bool RegMapping_Fer::compatible_class(MachineFunction &amp;mf,
1627                                       unsigned v_reg,
1628                                       unsigned p_reg) {
1629   assert(TargetRegisterInfo::isPhysicalRegister(p_reg) &amp;&amp;
1630          "Target register must be physical");
1631   const TargetRegisterClass *trc = mf.getRegInfo().getRegClass(v_reg);
1632   return trc-&gt;contains(p_reg);
1633 }
1634 </pre>
1635 </div>
1636
1637 <p>Sometimes, mostly for debugging purposes, it is useful to change the number
1638    of physical registers available in the target architecture. This must be done
1639    statically, inside the <tt>TargetRegsterInfo.td</tt> file. Just <tt>grep</tt>
1640    for <tt>RegisterClass</tt>, the last parameter of which is a list of
1641    registers. Just commenting some out is one simple way to avoid them being
1642    used. A more polite way is to explicitly exclude some registers from
1643    the <i>allocation order</i>. See the definition of the <tt>GR8</tt> register
1644    class in <tt>lib/Target/X86/X86RegisterInfo.td</tt> for an example of this.
1645    </p>
1646
1647 <p>Virtual registers are also denoted by integer numbers. Contrary to physical
1648    registers, different virtual registers never share the same number. Whereas
1649    physical registers are statically defined in a <tt>TargetRegisterInfo.td</tt>
1650    file and cannot be created by the application developer, that is not the case
1651    with virtual registers. In order to create new virtual registers, use the
1652    method <tt>MachineRegisterInfo::createVirtualRegister()</tt>. This method
1653    will return a new virtual register. Use an <tt>IndexedMap&lt;Foo,
1654    VirtReg2IndexFunctor&gt;</tt> to hold information per virtual register. If you
1655    need to enumerate all virtual registers, use the function
1656    <tt>TargetRegisterInfo::index2VirtReg()</tt> to find the virtual register
1657    numbers:</p>
1658
1659 <div class="doc_code">
1660 <pre>
1661   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1662     unsigned VirtReg = TargetRegisterInfo::index2VirtReg(i);
1663     stuff(VirtReg);
1664   }
1665 </pre>
1666 </div>
1667
1668 <p>Before register allocation, the operands of an instruction are mostly virtual
1669    registers, although physical registers may also be used. In order to check if
1670    a given machine operand is a register, use the boolean
1671    function <tt>MachineOperand::isRegister()</tt>. To obtain the integer code of
1672    a register, use <tt>MachineOperand::getReg()</tt>. An instruction may define
1673    or use a register. For instance, <tt>ADD reg:1026 := reg:1025 reg:1024</tt>
1674    defines the registers 1024, and uses registers 1025 and 1026. Given a
1675    register operand, the method <tt>MachineOperand::isUse()</tt> informs if that
1676    register is being used by the instruction. The
1677    method <tt>MachineOperand::isDef()</tt> informs if that registers is being
1678    defined.</p>
1679
1680 <p>We will call physical registers present in the LLVM bitcode before register
1681    allocation <i>pre-colored registers</i>. Pre-colored registers are used in
1682    many different situations, for instance, to pass parameters of functions
1683    calls, and to store results of particular instructions. There are two types
1684    of pre-colored registers: the ones <i>implicitly</i> defined, and
1685    those <i>explicitly</i> defined. Explicitly defined registers are normal
1686    operands, and can be accessed
1687    with <tt>MachineInstr::getOperand(int)::getReg()</tt>.  In order to check
1688    which registers are implicitly defined by an instruction, use
1689    the <tt>TargetInstrInfo::get(opcode)::ImplicitDefs</tt>,
1690    where <tt>opcode</tt> is the opcode of the target instruction. One important
1691    difference between explicit and implicit physical registers is that the
1692    latter are defined statically for each instruction, whereas the former may
1693    vary depending on the program being compiled. For example, an instruction
1694    that represents a function call will always implicitly define or use the same
1695    set of physical registers. To read the registers implicitly used by an
1696    instruction,
1697    use <tt>TargetInstrInfo::get(opcode)::ImplicitUses</tt>. Pre-colored
1698    registers impose constraints on any register allocation algorithm. The
1699    register allocator must make sure that none of them are overwritten by
1700    the values of virtual registers while still alive.</p>
1701
1702 </div>
1703
1704 <!-- _______________________________________________________________________ -->
1705
1706 <h4>
1707   <a name="regAlloc_howTo">Mapping virtual registers to physical registers</a>
1708 </h4>
1709
1710 <div>
1711
1712 <p>There are two ways to map virtual registers to physical registers (or to
1713    memory slots). The first way, that we will call <i>direct mapping</i>, is
1714    based on the use of methods of the classes <tt>TargetRegisterInfo</tt>,
1715    and <tt>MachineOperand</tt>. The second way, that we will call <i>indirect
1716    mapping</i>, relies on the <tt>VirtRegMap</tt> class in order to insert loads
1717    and stores sending and getting values to and from memory.</p>
1718
1719 <p>The direct mapping provides more flexibility to the developer of the register
1720    allocator; however, it is more error prone, and demands more implementation
1721    work.  Basically, the programmer will have to specify where load and store
1722    instructions should be inserted in the target function being compiled in
1723    order to get and store values in memory. To assign a physical register to a
1724    virtual register present in a given operand,
1725    use <tt>MachineOperand::setReg(p_reg)</tt>. To insert a store instruction,
1726    use <tt>TargetInstrInfo::storeRegToStackSlot(...)</tt>, and to insert a
1727    load instruction, use <tt>TargetInstrInfo::loadRegFromStackSlot</tt>.</p>
1728
1729 <p>The indirect mapping shields the application developer from the complexities
1730    of inserting load and store instructions. In order to map a virtual register
1731    to a physical one, use <tt>VirtRegMap::assignVirt2Phys(vreg, preg)</tt>.  In
1732    order to map a certain virtual register to memory,
1733    use <tt>VirtRegMap::assignVirt2StackSlot(vreg)</tt>. This method will return
1734    the stack slot where <tt>vreg</tt>'s value will be located.  If it is
1735    necessary to map another virtual register to the same stack slot,
1736    use <tt>VirtRegMap::assignVirt2StackSlot(vreg, stack_location)</tt>. One
1737    important point to consider when using the indirect mapping, is that even if
1738    a virtual register is mapped to memory, it still needs to be mapped to a
1739    physical register. This physical register is the location where the virtual
1740    register is supposed to be found before being stored or after being
1741    reloaded.</p>
1742
1743 <p>If the indirect strategy is used, after all the virtual registers have been
1744    mapped to physical registers or stack slots, it is necessary to use a spiller
1745    object to place load and store instructions in the code. Every virtual that
1746    has been mapped to a stack slot will be stored to memory after been defined
1747    and will be loaded before being used. The implementation of the spiller tries
1748    to recycle load/store instructions, avoiding unnecessary instructions. For an
1749    example of how to invoke the spiller,
1750    see <tt>RegAllocLinearScan::runOnMachineFunction</tt>
1751    in <tt>lib/CodeGen/RegAllocLinearScan.cpp</tt>.</p>
1752
1753 </div>
1754
1755 <!-- _______________________________________________________________________ -->
1756 <h4>
1757   <a name="regAlloc_twoAddr">Handling two address instructions</a>
1758 </h4>
1759
1760 <div>
1761
1762 <p>With very rare exceptions (e.g., function calls), the LLVM machine code
1763    instructions are three address instructions. That is, each instruction is
1764    expected to define at most one register, and to use at most two registers.
1765    However, some architectures use two address instructions. In this case, the
1766    defined register is also one of the used register. For instance, an
1767    instruction such as <tt>ADD %EAX, %EBX</tt>, in X86 is actually equivalent
1768    to <tt>%EAX = %EAX + %EBX</tt>.</p>
1769
1770 <p>In order to produce correct code, LLVM must convert three address
1771    instructions that represent two address instructions into true two address
1772    instructions. LLVM provides the pass <tt>TwoAddressInstructionPass</tt> for
1773    this specific purpose. It must be run before register allocation takes
1774    place. After its execution, the resulting code may no longer be in SSA
1775    form. This happens, for instance, in situations where an instruction such
1776    as <tt>%a = ADD %b %c</tt> is converted to two instructions such as:</p>
1777
1778 <div class="doc_code">
1779 <pre>
1780 %a = MOVE %b
1781 %a = ADD %a %c
1782 </pre>
1783 </div>
1784
1785 <p>Notice that, internally, the second instruction is represented as
1786    <tt>ADD %a[def/use] %c</tt>. I.e., the register operand <tt>%a</tt> is both
1787    used and defined by the instruction.</p>
1788
1789 </div>
1790
1791 <!-- _______________________________________________________________________ -->
1792 <h4>
1793   <a name="regAlloc_ssaDecon">The SSA deconstruction phase</a>
1794 </h4>
1795
1796 <div>
1797
1798 <p>An important transformation that happens during register allocation is called
1799    the <i>SSA Deconstruction Phase</i>. The SSA form simplifies many analyses
1800    that are performed on the control flow graph of programs. However,
1801    traditional instruction sets do not implement PHI instructions. Thus, in
1802    order to generate executable code, compilers must replace PHI instructions
1803    with other instructions that preserve their semantics.</p>
1804
1805 <p>There are many ways in which PHI instructions can safely be removed from the
1806    target code. The most traditional PHI deconstruction algorithm replaces PHI
1807    instructions with copy instructions. That is the strategy adopted by
1808    LLVM. The SSA deconstruction algorithm is implemented
1809    in <tt>lib/CodeGen/PHIElimination.cpp</tt>. In order to invoke this pass, the
1810    identifier <tt>PHIEliminationID</tt> must be marked as required in the code
1811    of the register allocator.</p>
1812
1813 </div>
1814
1815 <!-- _______________________________________________________________________ -->
1816 <h4>
1817   <a name="regAlloc_fold">Instruction folding</a>
1818 </h4>
1819
1820 <div>
1821
1822 <p><i>Instruction folding</i> is an optimization performed during register
1823    allocation that removes unnecessary copy instructions. For instance, a
1824    sequence of instructions such as:</p>
1825
1826 <div class="doc_code">
1827 <pre>
1828 %EBX = LOAD %mem_address
1829 %EAX = COPY %EBX
1830 </pre>
1831 </div>
1832
1833 <p>can be safely substituted by the single instruction:</p>
1834
1835 <div class="doc_code">
1836 <pre>
1837 %EAX = LOAD %mem_address
1838 </pre>
1839 </div>
1840
1841 <p>Instructions can be folded with
1842    the <tt>TargetRegisterInfo::foldMemoryOperand(...)</tt> method. Care must be
1843    taken when folding instructions; a folded instruction can be quite different
1844    from the original
1845    instruction. See <tt>LiveIntervals::addIntervalsForSpills</tt>
1846    in <tt>lib/CodeGen/LiveIntervalAnalysis.cpp</tt> for an example of its
1847    use.</p>
1848
1849 </div>
1850
1851 <!-- _______________________________________________________________________ -->
1852
1853 <h4>
1854   <a name="regAlloc_builtIn">Built in register allocators</a>
1855 </h4>
1856
1857 <div>
1858
1859 <p>The LLVM infrastructure provides the application developer with three
1860    different register allocators:</p>
1861
1862 <ul>
1863   <li><i>Fast</i> &mdash; This register allocator is the default for debug
1864       builds. It allocates registers on a basic block level, attempting to keep
1865       values in registers and reusing registers as appropriate.</li>
1866
1867   <li><i>Basic</i> &mdash; This is an incremental approach to register
1868   allocation. Live ranges are assigned to registers one at a time in
1869   an order that is driven by heuristics. Since code can be rewritten
1870   on-the-fly during allocation, this framework allows interesting
1871   allocators to be developed as extensions. It is not itself a
1872   production register allocator but is a potentially useful
1873   stand-alone mode for triaging bugs and as a performance baseline.
1874
1875   <li><i>Greedy</i> &mdash; <i>The default allocator</i>. This is a
1876   highly tuned implementation of the <i>Basic</i> allocator that
1877   incorporates global live range splitting. This allocator works hard
1878   to minimize the cost of spill code.
1879
1880   <li><i>PBQP</i> &mdash; A Partitioned Boolean Quadratic Programming (PBQP)
1881       based register allocator. This allocator works by constructing a PBQP
1882       problem representing the register allocation problem under consideration,
1883       solving this using a PBQP solver, and mapping the solution back to a
1884       register assignment.</li>
1885 </ul>
1886
1887 <p>The type of register allocator used in <tt>llc</tt> can be chosen with the
1888    command line option <tt>-regalloc=...</tt>:</p>
1889
1890 <div class="doc_code">
1891 <pre>
1892 $ llc -regalloc=linearscan file.bc -o ln.s;
1893 $ llc -regalloc=fast file.bc -o fa.s;
1894 $ llc -regalloc=pbqp file.bc -o pbqp.s;
1895 </pre>
1896 </div>
1897
1898 </div>
1899
1900 </div>
1901
1902 <!-- ======================================================================= -->
1903 <h3>
1904   <a name="proepicode">Prolog/Epilog Code Insertion</a>
1905 </h3>
1906
1907 <div>
1908
1909 <!-- _______________________________________________________________________ -->
1910 <h4>
1911   <a name="compact_unwind">Compact Unwind</a>
1912 </h4>
1913
1914 <div>
1915
1916 <p>Throwing an exception requires <em>unwinding</em> out of a function. The
1917    information on how to unwind a given function is traditionally expressed in
1918    DWARF unwind (a.k.a. frame) info. But that format was originally developed
1919    for debuggers to backtrace, and each Frame Description Entry (FDE) requires
1920    ~20-30 bytes per function. There is also the cost of mapping from an address
1921    in a function to the corresponding FDE at runtime. An alternative unwind
1922    encoding is called <em>compact unwind</em> and requires just 4-bytes per
1923    function.</p>
1924
1925 <p>The compact unwind encoding is a 32-bit value, which is encoded in an
1926    architecture-specific way. It specifies which registers to restore and from
1927    where, and how to unwind out of the function. When the linker creates a final
1928    linked image, it will create a <code>__TEXT,__unwind_info</code>
1929    section. This section is a small and fast way for the runtime to access
1930    unwind info for any given function. If we emit compact unwind info for the
1931    function, that compact unwind info will be encoded in
1932    the <code>__TEXT,__unwind_info</code> section. If we emit DWARF unwind info,
1933    the <code>__TEXT,__unwind_info</code> section will contain the offset of the
1934    FDE in the <code>__TEXT,__eh_frame</code> section in the final linked
1935    image.</p>
1936
1937 <p>For X86, there are three modes for the compact unwind encoding:</p>
1938
1939 <dl>
1940   <dt><i>Function with a Frame Pointer (<code>EBP</code> or <code>RBP</code>)</i></dt>
1941   <dd><p><code>EBP/RBP</code>-based frame, where <code>EBP/RBP</code> is pushed
1942       onto the stack immediately after the return address,
1943       then <code>ESP/RSP</code> is moved to <code>EBP/RBP</code>. Thus to
1944       unwind, <code>ESP/RSP</code> is restored with the
1945       current <code>EBP/RBP</code> value, then <code>EBP/RBP</code> is restored
1946       by popping the stack, and the return is done by popping the stack once
1947       more into the PC. All non-volatile registers that need to be restored must
1948       have been saved in a small range on the stack that
1949       starts <code>EBP-4</code> to <code>EBP-1020</code> (<code>RBP-8</code>
1950       to <code>RBP-1020</code>). The offset (divided by 4 in 32-bit mode and 8
1951       in 64-bit mode) is encoded in bits 16-23 (mask: <code>0x00FF0000</code>).
1952       The registers saved are encoded in bits 0-14
1953       (mask: <code>0x00007FFF</code>) as five 3-bit entries from the following
1954       table:</p>
1955 <table border="1" cellspacing="0">
1956   <tr>
1957     <th>Compact Number</th>
1958     <th>i386 Register</th>
1959     <th>x86-64 Regiser</th>
1960   </tr>
1961   <tr>
1962     <td>1</td>
1963     <td><code>EBX</code></td>
1964     <td><code>RBX</code></td>
1965   </tr>
1966   <tr>
1967     <td>2</td>
1968     <td><code>ECX</code></td>
1969     <td><code>R12</code></td>
1970   </tr>
1971   <tr>
1972     <td>3</td>
1973     <td><code>EDX</code></td>
1974     <td><code>R13</code></td>
1975   </tr>
1976   <tr>
1977     <td>4</td>
1978     <td><code>EDI</code></td>
1979     <td><code>R14</code></td>
1980   </tr>
1981   <tr>
1982     <td>5</td>
1983     <td><code>ESI</code></td>
1984     <td><code>R15</code></td>
1985   </tr>
1986   <tr>
1987     <td>6</td>
1988     <td><code>EBP</code></td>
1989     <td><code>RBP</code></td>
1990   </tr>
1991 </table>
1992
1993 </dd>
1994
1995   <dt><i>Frameless with a Small Constant Stack Size (<code>EBP</code>
1996          or <code>RBP</code> is not used as a frame pointer)</i></dt>
1997   <dd><p>To return, a constant (encoded in the compact unwind encoding) is added
1998       to the <code>ESP/RSP</code>.  Then the return is done by popping the stack
1999       into the PC. All non-volatile registers that need to be restored must have
2000       been saved on the stack immediately after the return address. The stack
2001       size (divided by 4 in 32-bit mode and 8 in 64-bit mode) is encoded in bits
2002       16-23 (mask: <code>0x00FF0000</code>). There is a maximum stack size of
2003       1024 bytes in 32-bit mode and 2048 in 64-bit mode. The number of registers
2004       saved is encoded in bits 9-12 (mask: <code>0x00001C00</code>). Bits 0-9
2005       (mask: <code>0x000003FF</code>) contain which registers were saved and
2006       their order. (See
2007       the <code>encodeCompactUnwindRegistersWithoutFrame()</code> function
2008       in <code>lib/Target/X86FrameLowering.cpp</code> for the encoding
2009       algorithm.)</p></dd>
2010
2011   <dt><i>Frameless with a Large Constant Stack Size (<code>EBP</code>
2012          or <code>RBP</code> is not used as a frame pointer)</i></dt>
2013   <dd><p>This case is like the "Frameless with a Small Constant Stack Size"
2014       case, but the stack size is too large to encode in the compact unwind
2015       encoding. Instead it requires that the function contains "<code>subl
2016       $nnnnnn, %esp</code>" in its prolog. The compact encoding contains the
2017       offset to the <code>$nnnnnn</code> value in the function in bits 9-12
2018       (mask: <code>0x00001C00</code>).</p></dd>
2019 </dl>
2020
2021 </div>
2022
2023 </div>
2024
2025 <!-- ======================================================================= -->
2026 <h3>
2027   <a name="latemco">Late Machine Code Optimizations</a>
2028 </h3>
2029 <div><p>To Be Written</p></div>
2030
2031 <!-- ======================================================================= -->
2032 <h3>
2033   <a name="codeemit">Code Emission</a>
2034 </h3>
2035
2036 <div>
2037
2038 <p>The code emission step of code generation is responsible for lowering from
2039 the code generator abstractions (like <a 
2040 href="#machinefunction">MachineFunction</a>, <a 
2041 href="#machineinstr">MachineInstr</a>, etc) down
2042 to the abstractions used by the MC layer (<a href="#mcinst">MCInst</a>, 
2043 <a href="#mcstreamer">MCStreamer</a>, etc).  This is
2044 done with a combination of several different classes: the (misnamed)
2045 target-independent AsmPrinter class, target-specific subclasses of AsmPrinter
2046 (such as SparcAsmPrinter), and the TargetLoweringObjectFile class.</p>
2047
2048 <p>Since the MC layer works at the level of abstraction of object files, it
2049 doesn't have a notion of functions, global variables etc.  Instead, it thinks
2050 about labels, directives, and instructions.  A key class used at this time is
2051 the MCStreamer class.  This is an abstract API that is implemented in different
2052 ways (e.g. to output a .s file, output an ELF .o file, etc) that is effectively
2053 an "assembler API".  MCStreamer has one method per directive, such as EmitLabel,
2054 EmitSymbolAttribute, SwitchSection, etc, which directly correspond to assembly
2055 level directives.
2056 </p>
2057
2058 <p>If you are interested in implementing a code generator for a target, there
2059 are three important things that you have to implement for your target:</p>
2060
2061 <ol>
2062 <li>First, you need a subclass of AsmPrinter for your target.  This class
2063 implements the general lowering process converting MachineFunction's into MC
2064 label constructs.  The AsmPrinter base class provides a number of useful methods
2065 and routines, and also allows you to override the lowering process in some
2066 important ways.  You should get much of the lowering for free if you are
2067 implementing an ELF, COFF, or MachO target, because the TargetLoweringObjectFile
2068 class implements much of the common logic.</li>
2069
2070 <li>Second, you need to implement an instruction printer for your target.  The
2071 instruction printer takes an <a href="#mcinst">MCInst</a> and renders it to a
2072 raw_ostream as text.  Most of this is automatically generated from the .td file
2073 (when you specify something like "<tt>add $dst, $src1, $src2</tt>" in the
2074 instructions), but you need to implement routines to print operands.</li>
2075
2076 <li>Third, you need to implement code that lowers a <a
2077 href="#machineinstr">MachineInstr</a> to an MCInst, usually implemented in
2078 "&lt;target&gt;MCInstLower.cpp".  This lowering process is often target
2079 specific, and is responsible for turning jump table entries, constant pool
2080 indices, global variable addresses, etc into MCLabels as appropriate.  This
2081 translation layer is also responsible for expanding pseudo ops used by the code
2082 generator into the actual machine instructions they correspond to. The MCInsts
2083 that are generated by this are fed into the instruction printer or the encoder.
2084 </li>
2085
2086 </ol>
2087
2088 <p>Finally, at your choosing, you can also implement an subclass of
2089 MCCodeEmitter which lowers MCInst's into machine code bytes and relocations.
2090 This is important if you want to support direct .o file emission, or would like
2091 to implement an assembler for your target.</p>
2092
2093 </div>
2094
2095 <!-- ======================================================================= -->
2096 <h3>
2097   <a name="vliw_packetizer">VLIW Packetizer</a>
2098 </h3>
2099
2100 <div>
2101
2102 <p>In a Very Long Instruction Word (VLIW) architecture, the compiler is
2103    responsible for mapping instructions to functional-units available on
2104    the architecture. To that end, the compiler creates groups of instructions
2105    called <i>packets</i> or <i>bundles</i>. The VLIW packetizer in LLVM is
2106    a target-independent mechanism to enable the packetization of machine
2107    instructions.</p>
2108
2109 <!-- _______________________________________________________________________ -->
2110
2111 <h4>
2112   <a name="vliw_mapping">Mapping from instructions to functional units</a>
2113 </h4>
2114
2115 <div>
2116
2117 <p>Instructions in a VLIW target can typically be mapped to multiple functional
2118 units. During the process of packetizing, the compiler must be able to reason
2119 about whether an instruction can be added to a packet. This decision can be
2120 complex since the compiler has to examine all possible mappings of instructions
2121 to functional units. Therefore to alleviate compilation-time complexity, the
2122 VLIW packetizer parses the instruction classes of a target and generates tables
2123 at compiler build time. These tables can then be queried by the provided
2124 machine-independent API to determine if an instruction can be accommodated in a
2125 packet.</p>
2126 </div>
2127
2128 <!-- ======================================================================= -->
2129 <h4>
2130   <a name="vliw_repr">
2131     How the packetization tables are generated and used
2132   </a>
2133 </h4>
2134
2135 <div>
2136
2137 <p>The packetizer reads instruction classes from a target's itineraries and
2138 creates a deterministic finite automaton (DFA) to represent the state of a
2139 packet. A DFA consists of three major elements: inputs, states, and
2140 transitions. The set of inputs for the generated DFA represents the instruction
2141 being added to a packet. The states represent the possible consumption
2142 of functional units by instructions in a packet. In the DFA, transitions from
2143 one state to another occur on the addition of an instruction to an existing
2144 packet. If there is a legal mapping of functional units to instructions, then
2145 the DFA contains a corresponding transition. The absence of a transition
2146 indicates that a legal mapping does not exist and that the instruction cannot
2147 be added to the packet.</p>
2148
2149 <p>To generate tables for a VLIW target, add <i>Target</i>GenDFAPacketizer.inc
2150 as a target to the Makefile in the target directory. The exported API provides
2151 three functions: <tt>DFAPacketizer::clearResources()</tt>,
2152 <tt>DFAPacketizer::reserveResources(MachineInstr *MI)</tt>, and
2153 <tt>DFAPacketizer::canReserveResources(MachineInstr *MI)</tt>. These functions
2154 allow a target packetizer to add an instruction to an existing packet and to
2155 check whether an instruction can be added to a packet. See
2156 <tt>llvm/CodeGen/DFAPacketizer.h</tt> for more information.</p>
2157
2158 </div>
2159
2160 </div>
2161
2162 </div>
2163
2164 <!-- *********************************************************************** -->
2165 <h2>
2166   <a name="nativeassembler">Implementing a Native Assembler</a>
2167 </h2>
2168 <!-- *********************************************************************** -->
2169
2170 <div>
2171
2172 <p>Though you're probably reading this because you want to write or maintain a
2173 compiler backend, LLVM also fully supports building a native assemblers too.
2174 We've tried hard to automate the generation of the assembler from the .td files
2175 (in particular the instruction syntax and encodings), which means that a large
2176 part of the manual and repetitive data entry can be factored and shared with the
2177 compiler.</p>
2178
2179 <!-- ======================================================================= -->
2180 <h3 id="na_instparsing">Instruction Parsing</h3>
2181
2182 <div><p>To Be Written</p></div>
2183
2184
2185 <!-- ======================================================================= -->
2186 <h3 id="na_instaliases">
2187   Instruction Alias Processing
2188 </h3>
2189
2190 <div>
2191 <p>Once the instruction is parsed, it enters the MatchInstructionImpl function.
2192 The MatchInstructionImpl function performs alias processing and then does
2193 actual matching.</p>
2194
2195 <p>Alias processing is the phase that canonicalizes different lexical forms of
2196 the same instructions down to one representation.  There are several different
2197 kinds of alias that are possible to implement and they are listed below in the
2198 order that they are processed (which is in order from simplest/weakest to most
2199 complex/powerful).  Generally you want to use the first alias mechanism that
2200 meets the needs of your instruction, because it will allow a more concise
2201 description.</p>
2202
2203 <!-- _______________________________________________________________________ -->
2204 <h4>Mnemonic Aliases</h4>
2205
2206 <div>
2207
2208 <p>The first phase of alias processing is simple instruction mnemonic
2209 remapping for classes of instructions which are allowed with two different
2210 mnemonics.  This phase is a simple and unconditionally remapping from one input
2211 mnemonic to one output mnemonic.  It isn't possible for this form of alias to
2212 look at the operands at all, so the remapping must apply for all forms of a
2213 given mnemonic.  Mnemonic aliases are defined simply, for example X86 has:
2214 </p>
2215
2216 <div class="doc_code">
2217 <pre>
2218 def : MnemonicAlias&lt;"cbw",     "cbtw"&gt;;
2219 def : MnemonicAlias&lt;"smovq",   "movsq"&gt;;
2220 def : MnemonicAlias&lt;"fldcww",  "fldcw"&gt;;
2221 def : MnemonicAlias&lt;"fucompi", "fucomip"&gt;;
2222 def : MnemonicAlias&lt;"ud2a",    "ud2"&gt;;
2223 </pre>
2224 </div>
2225
2226 <p>... and many others.  With a MnemonicAlias definition, the mnemonic is
2227 remapped simply and directly.  Though MnemonicAlias's can't look at any aspect
2228 of the instruction (such as the operands) they can depend on global modes (the
2229 same ones supported by the matcher), through a Requires clause:</p>
2230
2231 <div class="doc_code">
2232 <pre>
2233 def : MnemonicAlias&lt;"pushf", "pushfq"&gt;, Requires&lt;[In64BitMode]&gt;;
2234 def : MnemonicAlias&lt;"pushf", "pushfl"&gt;, Requires&lt;[In32BitMode]&gt;;
2235 </pre>
2236 </div>
2237
2238 <p>In this example, the mnemonic gets mapped into different a new one depending
2239 on the current instruction set.</p>
2240
2241 </div>
2242
2243 <!-- _______________________________________________________________________ -->
2244 <h4>Instruction Aliases</h4>
2245
2246 <div>
2247
2248 <p>The most general phase of alias processing occurs while matching is
2249 happening: it provides new forms for the matcher to match along with a specific
2250 instruction to generate.  An instruction alias has two parts: the string to
2251 match and the instruction to generate.  For example:
2252 </p>
2253
2254 <div class="doc_code">
2255 <pre>
2256 def : InstAlias&lt;"movsx $src, $dst", (MOVSX16rr8W GR16:$dst, GR8  :$src)&gt;;
2257 def : InstAlias&lt;"movsx $src, $dst", (MOVSX16rm8W GR16:$dst, i8mem:$src)&gt;;
2258 def : InstAlias&lt;"movsx $src, $dst", (MOVSX32rr8  GR32:$dst, GR8  :$src)&gt;;
2259 def : InstAlias&lt;"movsx $src, $dst", (MOVSX32rr16 GR32:$dst, GR16 :$src)&gt;;
2260 def : InstAlias&lt;"movsx $src, $dst", (MOVSX64rr8  GR64:$dst, GR8  :$src)&gt;;
2261 def : InstAlias&lt;"movsx $src, $dst", (MOVSX64rr16 GR64:$dst, GR16 :$src)&gt;;
2262 def : InstAlias&lt;"movsx $src, $dst", (MOVSX64rr32 GR64:$dst, GR32 :$src)&gt;;
2263 </pre>
2264 </div>
2265
2266 <p>This shows a powerful example of the instruction aliases, matching the
2267 same mnemonic in multiple different ways depending on what operands are present
2268 in the assembly.  The result of instruction aliases can include operands in a
2269 different order than the destination instruction, and can use an input
2270 multiple times, for example:</p>
2271
2272 <div class="doc_code">
2273 <pre>
2274 def : InstAlias&lt;"clrb $reg", (XOR8rr  GR8 :$reg, GR8 :$reg)&gt;;
2275 def : InstAlias&lt;"clrw $reg", (XOR16rr GR16:$reg, GR16:$reg)&gt;;
2276 def : InstAlias&lt;"clrl $reg", (XOR32rr GR32:$reg, GR32:$reg)&gt;;
2277 def : InstAlias&lt;"clrq $reg", (XOR64rr GR64:$reg, GR64:$reg)&gt;;
2278 </pre>
2279 </div>
2280
2281 <p>This example also shows that tied operands are only listed once.  In the X86
2282 backend, XOR8rr has two input GR8's and one output GR8 (where an input is tied
2283 to the output).  InstAliases take a flattened operand list without duplicates
2284 for tied operands.  The result of an instruction alias can also use immediates
2285 and fixed physical registers which are added as simple immediate operands in the
2286 result, for example:</p>
2287
2288 <div class="doc_code">
2289 <pre>
2290 // Fixed Immediate operand.
2291 def : InstAlias&lt;"aad", (AAD8i8 10)&gt;;
2292
2293 // Fixed register operand.
2294 def : InstAlias&lt;"fcomi", (COM_FIr ST1)&gt;;
2295
2296 // Simple alias.
2297 def : InstAlias&lt;"fcomi $reg", (COM_FIr RST:$reg)&gt;;
2298 </pre>
2299 </div>
2300
2301
2302 <p>Instruction aliases can also have a Requires clause to make them
2303 subtarget specific.</p>
2304
2305 <p>If the back-end supports it, the instruction printer can automatically emit
2306    the alias rather than what's being aliased. It typically leads to better,
2307    more readable code. If it's better to print out what's being aliased, then
2308    pass a '0' as the third parameter to the InstAlias definition.</p>
2309
2310 </div>
2311
2312 </div>
2313
2314 <!-- ======================================================================= -->
2315 <h3 id="na_matching">Instruction Matching</h3>
2316
2317 <div><p>To Be Written</p></div>
2318
2319 </div>
2320
2321 <!-- *********************************************************************** -->
2322 <h2>
2323   <a name="targetimpls">Target-specific Implementation Notes</a>
2324 </h2>
2325 <!-- *********************************************************************** -->
2326
2327 <div>
2328
2329 <p>This section of the document explains features or design decisions that are
2330    specific to the code generator for a particular target.  First we start
2331    with a table that summarizes what features are supported by each target.</p>
2332
2333 <!-- ======================================================================= -->
2334 <h3>
2335   <a name="targetfeatures">Target Feature Matrix</a>
2336 </h3>
2337
2338 <div>
2339
2340 <p>Note that this table does not include the C backend or Cpp backends, since
2341 they do not use the target independent code generator infrastructure.  It also
2342 doesn't list features that are not supported fully by any target yet.  It
2343 considers a feature to be supported if at least one subtarget supports it.  A
2344 feature being supported means that it is useful and works for most cases, it
2345 does not indicate that there are zero known bugs in the implementation.  Here
2346 is the key:</p>
2347
2348
2349 <table border="1" cellspacing="0">
2350   <tr>
2351     <th>Unknown</th>
2352     <th>No support</th>
2353     <th>Partial Support</th>
2354     <th>Complete Support</th>
2355   </tr>
2356   <tr>
2357     <td class="unknown"></td>
2358     <td class="no"></td>
2359     <td class="partial"></td>
2360     <td class="yes"></td>
2361   </tr>
2362 </table>
2363
2364 <p>Here is the table:</p>
2365
2366 <table width="689" border="1" cellspacing="0">
2367 <tr><td></td>
2368 <td colspan="13" align="center" style="background-color:#ffc">Target</td>
2369 </tr>
2370   <tr>
2371     <th>Feature</th>
2372     <th>ARM</th>
2373     <th>CellSPU</th>
2374     <th>Hexagon</th>
2375     <th>MBlaze</th>
2376     <th>MSP430</th>
2377     <th>Mips</th>
2378     <th>PTX</th>
2379     <th>PowerPC</th>
2380     <th>Sparc</th>
2381     <th>X86</th>
2382     <th>XCore</th>
2383   </tr>
2384
2385 <tr>
2386   <td><a href="#feat_reliable">is generally reliable</a></td>
2387   <td class="yes"></td> <!-- ARM -->
2388   <td class="no"></td> <!-- CellSPU -->
2389   <td class="yes"></td> <!-- Hexagon -->
2390   <td class="no"></td> <!-- MBlaze -->
2391   <td class="unknown"></td> <!-- MSP430 -->
2392   <td class="yes"></td> <!-- Mips -->
2393   <td class="no"></td> <!-- PTX -->
2394   <td class="yes"></td> <!-- PowerPC -->
2395   <td class="yes"></td> <!-- Sparc -->
2396   <td class="yes"></td> <!-- X86 -->
2397   <td class="unknown"></td> <!-- XCore -->
2398 </tr>
2399
2400 <tr>
2401   <td><a href="#feat_asmparser">assembly parser</a></td>
2402   <td class="no"></td> <!-- ARM -->
2403   <td class="no"></td> <!-- CellSPU -->
2404   <td class="no"></td> <!-- Hexagon -->
2405   <td class="yes"></td> <!-- MBlaze -->
2406   <td class="no"></td> <!-- MSP430 -->
2407   <td class="no"></td> <!-- Mips -->
2408   <td class="no"></td> <!-- PTX -->
2409   <td class="no"></td> <!-- PowerPC -->
2410   <td class="no"></td> <!-- Sparc -->
2411   <td class="yes"></td> <!-- X86 -->
2412   <td class="no"></td> <!-- XCore -->
2413 </tr>
2414
2415 <tr>
2416   <td><a href="#feat_disassembler">disassembler</a></td>
2417   <td class="yes"></td> <!-- ARM -->
2418   <td class="no"></td> <!-- CellSPU -->
2419   <td class="no"></td> <!-- Hexagon -->
2420   <td class="yes"></td> <!-- MBlaze -->
2421   <td class="no"></td> <!-- MSP430 -->
2422   <td class="no"></td> <!-- Mips -->
2423   <td class="no"></td> <!-- PTX -->
2424   <td class="no"></td> <!-- PowerPC -->
2425   <td class="no"></td> <!-- Sparc -->
2426   <td class="yes"></td> <!-- X86 -->
2427   <td class="no"></td> <!-- XCore -->
2428 </tr>
2429
2430 <tr>
2431   <td><a href="#feat_inlineasm">inline asm</a></td>
2432   <td class="yes"></td> <!-- ARM -->
2433   <td class="no"></td> <!-- CellSPU -->
2434   <td class="yes"></td> <!-- Hexagon -->
2435   <td class="yes"></td> <!-- MBlaze -->
2436   <td class="unknown"></td> <!-- MSP430 -->
2437   <td class="no"></td> <!-- Mips -->
2438   <td class="unknown"></td> <!-- PTX -->
2439   <td class="yes"></td> <!-- PowerPC -->
2440   <td class="unknown"></td> <!-- Sparc -->
2441   <td class="yes"></td> <!-- X86 -->
2442   <td class="unknown"></td> <!-- XCore -->
2443 </tr>
2444
2445 <tr>
2446   <td><a href="#feat_jit">jit</a></td>
2447   <td class="partial"><a href="#feat_jit_arm">*</a></td> <!-- ARM -->
2448   <td class="no"></td> <!-- CellSPU -->
2449   <td class="no"></td> <!-- Hexagon -->
2450   <td class="no"></td> <!-- MBlaze -->
2451   <td class="unknown"></td> <!-- MSP430 -->
2452   <td class="yes"></td> <!-- Mips -->
2453   <td class="unknown"></td> <!-- PTX -->
2454   <td class="yes"></td> <!-- PowerPC -->
2455   <td class="unknown"></td> <!-- Sparc -->
2456   <td class="yes"></td> <!-- X86 -->
2457   <td class="unknown"></td> <!-- XCore -->
2458 </tr>
2459
2460 <tr>
2461   <td><a href="#feat_objectwrite">.o&nbsp;file writing</a></td>
2462   <td class="no"></td> <!-- ARM -->
2463   <td class="no"></td> <!-- CellSPU -->
2464   <td class="no"></td> <!-- Hexagon -->
2465   <td class="yes"></td> <!-- MBlaze -->
2466   <td class="no"></td> <!-- MSP430 -->
2467   <td class="no"></td> <!-- Mips -->
2468   <td class="no"></td> <!-- PTX -->
2469   <td class="no"></td> <!-- PowerPC -->
2470   <td class="no"></td> <!-- Sparc -->
2471   <td class="yes"></td> <!-- X86 -->
2472   <td class="no"></td> <!-- XCore -->
2473 </tr>
2474
2475 <tr>
2476   <td><a href="#feat_tailcall">tail calls</a></td>
2477   <td class="yes"></td> <!-- ARM -->
2478   <td class="no"></td> <!-- CellSPU -->
2479   <td class="yes"></td> <!-- Hexagon -->
2480   <td class="no"></td> <!-- MBlaze -->
2481   <td class="unknown"></td> <!-- MSP430 -->
2482   <td class="no"></td> <!-- Mips -->
2483   <td class="unknown"></td> <!-- PTX -->
2484   <td class="yes"></td> <!-- PowerPC -->
2485   <td class="unknown"></td> <!-- Sparc -->
2486   <td class="yes"></td> <!-- X86 -->
2487   <td class="unknown"></td> <!-- XCore -->
2488 </tr>
2489
2490 <tr>
2491   <td><a href="#feat_segstacks">segmented stacks</a></td>
2492   <td class="no"></td> <!-- ARM -->
2493   <td class="no"></td> <!-- CellSPU -->
2494   <td class="no"></td> <!-- MBlaze -->
2495   <td class="no"></td> <!-- MSP430 -->
2496   <td class="no"></td> <!-- Mips -->
2497   <td class="no"></td> <!-- PTX -->
2498   <td class="no"></td> <!-- PowerPC -->
2499   <td class="no"></td> <!-- Sparc -->
2500   <td class="partial"><a href="#feat_segstacks_x86">*</a></td> <!-- X86 -->
2501   <td class="no"></td> <!-- XCore -->
2502 </tr>
2503
2504
2505 </table>
2506
2507 <!-- _______________________________________________________________________ -->
2508 <h4 id="feat_reliable">Is Generally Reliable</h4>
2509
2510 <div>
2511 <p>This box indicates whether the target is considered to be production quality.
2512 This indicates that the target has been used as a static compiler to
2513 compile large amounts of code by a variety of different people and is in
2514 continuous use.</p>
2515 </div>
2516
2517 <!-- _______________________________________________________________________ -->
2518 <h4 id="feat_asmparser">Assembly Parser</h4>
2519
2520 <div>
2521 <p>This box indicates whether the target supports parsing target specific .s
2522 files by implementing the MCAsmParser interface.  This is required for llvm-mc
2523 to be able to act as a native assembler and is required for inline assembly
2524 support in the native .o file writer.</p>
2525
2526 </div>
2527
2528
2529 <!-- _______________________________________________________________________ -->
2530 <h4 id="feat_disassembler">Disassembler</h4>
2531
2532 <div>
2533 <p>This box indicates whether the target supports the MCDisassembler API for
2534 disassembling machine opcode bytes into MCInst's.</p>
2535
2536 </div>
2537
2538 <!-- _______________________________________________________________________ -->
2539 <h4 id="feat_inlineasm">Inline Asm</h4>
2540
2541 <div>
2542 <p>This box indicates whether the target supports most popular inline assembly
2543 constraints and modifiers.</p>
2544
2545 </div>
2546
2547 <!-- _______________________________________________________________________ -->
2548 <h4 id="feat_jit">JIT Support</h4>
2549
2550 <div>
2551 <p>This box indicates whether the target supports the JIT compiler through
2552 the ExecutionEngine interface.</p>
2553
2554 <p id="feat_jit_arm">The ARM backend has basic support for integer code
2555 in ARM codegen mode, but lacks NEON and full Thumb support.</p>
2556
2557 </div>
2558
2559 <!-- _______________________________________________________________________ -->
2560 <h4 id="feat_objectwrite">.o File Writing</h4>
2561
2562 <div>
2563
2564 <p>This box indicates whether the target supports writing .o files (e.g. MachO,
2565 ELF, and/or COFF) files directly from the target.  Note that the target also
2566 must include an assembly parser and general inline assembly support for full
2567 inline assembly support in the .o writer.</p>
2568
2569 <p>Targets that don't support this feature can obviously still write out .o
2570 files, they just rely on having an external assembler to translate from a .s
2571 file to a .o file (as is the case for many C compilers).</p>
2572
2573 </div>
2574
2575 <!-- _______________________________________________________________________ -->
2576 <h4 id="feat_tailcall">Tail Calls</h4>
2577
2578 <div>
2579
2580 <p>This box indicates whether the target supports guaranteed tail calls.  These
2581 are calls marked "<a href="LangRef.html#i_call">tail</a>" and use the fastcc
2582 calling convention.  Please see the <a href="#tailcallopt">tail call section
2583 more more details</a>.</p>
2584
2585 </div>
2586
2587 <!-- _______________________________________________________________________ -->
2588 <h4 id="feat_segstacks">Segmented Stacks</h4>
2589
2590 <div>
2591
2592 <p>This box indicates whether the target supports segmented stacks. This
2593 replaces the traditional large C stack with many linked segments. It
2594 is compatible with the <a href="http://gcc.gnu.org/wiki/SplitStacks">gcc
2595 implementation</a> used by the Go front end.</p>
2596
2597 <p id="feat_segstacks_x86">Basic support exists on the X86 backend. Currently
2598 vararg doesn't work and the object files are not marked the way the gold
2599 linker expects, but simple Go programs can be built by dragonegg.</p>
2600
2601 </div>
2602
2603 </div>
2604
2605 <!-- ======================================================================= -->
2606 <h3>
2607   <a name="tailcallopt">Tail call optimization</a>
2608 </h3>
2609
2610 <div>
2611
2612 <p>Tail call optimization, callee reusing the stack of the caller, is currently
2613    supported on x86/x86-64 and PowerPC. It is performed if:</p>
2614
2615 <ul>
2616   <li>Caller and callee have the calling convention <tt>fastcc</tt> or
2617        <tt>cc 10</tt> (GHC call convention).</li>
2618
2619   <li>The call is a tail call - in tail position (ret immediately follows call
2620       and ret uses value of call or is void).</li>
2621
2622   <li>Option <tt>-tailcallopt</tt> is enabled.</li>
2623
2624   <li>Platform specific constraints are met.</li>
2625 </ul>
2626
2627 <p>x86/x86-64 constraints:</p>
2628
2629 <ul>
2630   <li>No variable argument lists are used.</li>
2631
2632   <li>On x86-64 when generating GOT/PIC code only module-local calls (visibility
2633   = hidden or protected) are supported.</li>
2634 </ul>
2635
2636 <p>PowerPC constraints:</p>
2637
2638 <ul>
2639   <li>No variable argument lists are used.</li>
2640
2641   <li>No byval parameters are used.</li>
2642
2643   <li>On ppc32/64 GOT/PIC only module-local calls (visibility = hidden or protected) are supported.</li>
2644 </ul>
2645
2646 <p>Example:</p>
2647
2648 <p>Call as <tt>llc -tailcallopt test.ll</tt>.</p>
2649
2650 <div class="doc_code">
2651 <pre>
2652 declare fastcc i32 @tailcallee(i32 inreg %a1, i32 inreg %a2, i32 %a3, i32 %a4)
2653
2654 define fastcc i32 @tailcaller(i32 %in1, i32 %in2) {
2655   %l1 = add i32 %in1, %in2
2656   %tmp = tail call fastcc i32 @tailcallee(i32 %in1 inreg, i32 %in2 inreg, i32 %in1, i32 %l1)
2657   ret i32 %tmp
2658 }
2659 </pre>
2660 </div>
2661
2662 <p>Implications of <tt>-tailcallopt</tt>:</p>
2663
2664 <p>To support tail call optimization in situations where the callee has more
2665    arguments than the caller a 'callee pops arguments' convention is used. This
2666    currently causes each <tt>fastcc</tt> call that is not tail call optimized
2667    (because one or more of above constraints are not met) to be followed by a
2668    readjustment of the stack. So performance might be worse in such cases.</p>
2669
2670 </div>
2671 <!-- ======================================================================= -->
2672 <h3>
2673   <a name="sibcallopt">Sibling call optimization</a>
2674 </h3>
2675
2676 <div>
2677
2678 <p>Sibling call optimization is a restricted form of tail call optimization.
2679    Unlike tail call optimization described in the previous section, it can be
2680    performed automatically on any tail calls when <tt>-tailcallopt</tt> option
2681    is not specified.</p>
2682
2683 <p>Sibling call optimization is currently performed on x86/x86-64 when the
2684    following constraints are met:</p>
2685
2686 <ul>
2687   <li>Caller and callee have the same calling convention. It can be either
2688       <tt>c</tt> or <tt>fastcc</tt>.
2689
2690   <li>The call is a tail call - in tail position (ret immediately follows call
2691       and ret uses value of call or is void).</li>
2692
2693   <li>Caller and callee have matching return type or the callee result is not
2694       used.
2695
2696   <li>If any of the callee arguments are being passed in stack, they must be
2697       available in caller's own incoming argument stack and the frame offsets
2698       must be the same.
2699 </ul>
2700
2701 <p>Example:</p>
2702 <div class="doc_code">
2703 <pre>
2704 declare i32 @bar(i32, i32)
2705
2706 define i32 @foo(i32 %a, i32 %b, i32 %c) {
2707 entry:
2708   %0 = tail call i32 @bar(i32 %a, i32 %b)
2709   ret i32 %0
2710 }
2711 </pre>
2712 </div>
2713
2714 </div>
2715 <!-- ======================================================================= -->
2716 <h3>
2717   <a name="x86">The X86 backend</a>
2718 </h3>
2719
2720 <div>
2721
2722 <p>The X86 code generator lives in the <tt>lib/Target/X86</tt> directory.  This
2723    code generator is capable of targeting a variety of x86-32 and x86-64
2724    processors, and includes support for ISA extensions such as MMX and SSE.</p>
2725
2726 <!-- _______________________________________________________________________ -->
2727 <h4>
2728   <a name="x86_tt">X86 Target Triples supported</a>
2729 </h4>
2730
2731 <div>
2732
2733 <p>The following are the known target triples that are supported by the X86
2734    backend.  This is not an exhaustive list, and it would be useful to add those
2735    that people test.</p>
2736
2737 <ul>
2738   <li><b>i686-pc-linux-gnu</b> &mdash; Linux</li>
2739
2740   <li><b>i386-unknown-freebsd5.3</b> &mdash; FreeBSD 5.3</li>
2741
2742   <li><b>i686-pc-cygwin</b> &mdash; Cygwin on Win32</li>
2743
2744   <li><b>i686-pc-mingw32</b> &mdash; MingW on Win32</li>
2745
2746   <li><b>i386-pc-mingw32msvc</b> &mdash; MingW crosscompiler on Linux</li>
2747
2748   <li><b>i686-apple-darwin*</b> &mdash; Apple Darwin on X86</li>
2749
2750   <li><b>x86_64-unknown-linux-gnu</b> &mdash; Linux</li>
2751 </ul>
2752
2753 </div>
2754
2755 <!-- _______________________________________________________________________ -->
2756 <h4>
2757   <a name="x86_cc">X86 Calling Conventions supported</a>
2758 </h4>
2759
2760
2761 <div>
2762
2763 <p>The following target-specific calling conventions are known to backend:</p>
2764
2765 <ul>
2766 <li><b>x86_StdCall</b> &mdash; stdcall calling convention seen on Microsoft
2767     Windows platform (CC ID = 64).</li>
2768 <li><b>x86_FastCall</b> &mdash; fastcall calling convention seen on Microsoft
2769     Windows platform (CC ID = 65).</li>
2770 <li><b>x86_ThisCall</b> &mdash; Similar to X86_StdCall. Passes first argument
2771     in ECX,  others via stack. Callee is responsible for stack cleaning. This
2772     convention is used by MSVC by default for methods in its ABI
2773     (CC ID = 70).</li>
2774 </ul>
2775
2776 </div>
2777
2778 <!-- _______________________________________________________________________ -->
2779 <h4>
2780   <a name="x86_memory">Representing X86 addressing modes in MachineInstrs</a>
2781 </h4>
2782
2783 <div>
2784
2785 <p>The x86 has a very flexible way of accessing memory.  It is capable of
2786    forming memory addresses of the following expression directly in integer
2787    instructions (which use ModR/M addressing):</p>
2788
2789 <div class="doc_code">
2790 <pre>
2791 SegmentReg: Base + [1,2,4,8] * IndexReg + Disp32
2792 </pre>
2793 </div>
2794
2795 <p>In order to represent this, LLVM tracks no less than 5 operands for each
2796    memory operand of this form.  This means that the "load" form of
2797    '<tt>mov</tt>' has the following <tt>MachineOperand</tt>s in this order:</p>
2798
2799 <div class="doc_code">
2800 <pre>
2801 Index:        0     |    1        2       3           4          5
2802 Meaning:   DestReg, | BaseReg,  Scale, IndexReg, Displacement Segment
2803 OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg,   SignExtImm  PhysReg
2804 </pre>
2805 </div>
2806
2807 <p>Stores, and all other instructions, treat the four memory operands in the
2808    same way and in the same order.  If the segment register is unspecified
2809    (regno = 0), then no segment override is generated.  "Lea" operations do not
2810    have a segment register specified, so they only have 4 operands for their
2811    memory reference.</p>
2812
2813 </div>
2814
2815 <!-- _______________________________________________________________________ -->
2816 <h4>
2817   <a name="x86_memory">X86 address spaces supported</a>
2818 </h4>
2819
2820 <div>
2821
2822 <p>x86 has a feature which provides
2823    the ability to perform loads and stores to different address spaces
2824    via the x86 segment registers.  A segment override prefix byte on an
2825    instruction causes the instruction's memory access to go to the specified
2826    segment.  LLVM address space 0 is the default address space, which includes
2827    the stack, and any unqualified memory accesses in a program.  Address spaces
2828    1-255 are currently reserved for user-defined code.  The GS-segment is
2829    represented by address space 256, while the FS-segment is represented by 
2830    address space 257. Other x86 segments have yet to be allocated address space
2831    numbers.</p>
2832
2833 <p>While these address spaces may seem similar to TLS via the
2834    <tt>thread_local</tt> keyword, and often use the same underlying hardware,
2835    there are some fundamental differences.</p>
2836
2837 <p>The <tt>thread_local</tt> keyword applies to global variables and
2838    specifies that they are to be allocated in thread-local memory. There are
2839    no type qualifiers involved, and these variables can be pointed to with
2840    normal pointers and accessed with normal loads and stores.
2841    The <tt>thread_local</tt> keyword is target-independent at the LLVM IR
2842    level (though LLVM doesn't yet have implementations of it for some
2843    configurations).<p>
2844
2845 <p>Special address spaces, in contrast, apply to static types. Every
2846    load and store has a particular address space in its address operand type,
2847    and this is what determines which address space is accessed.
2848    LLVM ignores these special address space qualifiers on global variables,
2849    and does not provide a way to directly allocate storage in them.
2850    At the LLVM IR level, the behavior of these special address spaces depends
2851    in part on the underlying OS or runtime environment, and they are specific
2852    to x86 (and LLVM doesn't yet handle them correctly in some cases).</p>
2853
2854 <p>Some operating systems and runtime environments use (or may in the future
2855    use) the FS/GS-segment registers for various low-level purposes, so care
2856    should be taken when considering them.</p>
2857
2858 </div>
2859
2860 <!-- _______________________________________________________________________ -->
2861 <h4>
2862   <a name="x86_names">Instruction naming</a>
2863 </h4>
2864
2865 <div>
2866
2867 <p>An instruction name consists of the base name, a default operand size, and a
2868    a character per operand with an optional special size. For example:</p>
2869
2870 <div class="doc_code">
2871 <pre>
2872 ADD8rr      -&gt; add, 8-bit register, 8-bit register
2873 IMUL16rmi   -&gt; imul, 16-bit register, 16-bit memory, 16-bit immediate
2874 IMUL16rmi8  -&gt; imul, 16-bit register, 16-bit memory, 8-bit immediate
2875 MOVSX32rm16 -&gt; movsx, 32-bit register, 16-bit memory
2876 </pre>
2877 </div>
2878
2879 </div>
2880
2881 </div>
2882
2883 <!-- ======================================================================= -->
2884 <h3>
2885   <a name="ppc">The PowerPC backend</a>
2886 </h3>
2887
2888 <div>
2889
2890 <p>The PowerPC code generator lives in the lib/Target/PowerPC directory.  The
2891    code generation is retargetable to several variations or <i>subtargets</i> of
2892    the PowerPC ISA; including ppc32, ppc64 and altivec.</p>
2893
2894 <!-- _______________________________________________________________________ -->
2895 <h4>
2896   <a name="ppc_abi">LLVM PowerPC ABI</a>
2897 </h4>
2898
2899 <div>
2900
2901 <p>LLVM follows the AIX PowerPC ABI, with two deviations. LLVM uses a PC
2902    relative (PIC) or static addressing for accessing global values, so no TOC
2903    (r2) is used. Second, r31 is used as a frame pointer to allow dynamic growth
2904    of a stack frame.  LLVM takes advantage of having no TOC to provide space to
2905    save the frame pointer in the PowerPC linkage area of the caller frame.
2906    Other details of PowerPC ABI can be found at <a href=
2907    "http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/Articles/32bitPowerPC.html"
2908    >PowerPC ABI.</a> Note: This link describes the 32 bit ABI.  The 64 bit ABI
2909    is similar except space for GPRs are 8 bytes wide (not 4) and r13 is reserved
2910    for system use.</p>
2911
2912 </div>
2913
2914 <!-- _______________________________________________________________________ -->
2915 <h4>
2916   <a name="ppc_frame">Frame Layout</a>
2917 </h4>
2918
2919 <div>
2920
2921 <p>The size of a PowerPC frame is usually fixed for the duration of a
2922    function's invocation.  Since the frame is fixed size, all references
2923    into the frame can be accessed via fixed offsets from the stack pointer.  The
2924    exception to this is when dynamic alloca or variable sized arrays are
2925    present, then a base pointer (r31) is used as a proxy for the stack pointer
2926    and stack pointer is free to grow or shrink.  A base pointer is also used if
2927    llvm-gcc is not passed the -fomit-frame-pointer flag. The stack pointer is
2928    always aligned to 16 bytes, so that space allocated for altivec vectors will
2929    be properly aligned.</p>
2930
2931 <p>An invocation frame is laid out as follows (low memory at top);</p>
2932
2933 <table class="layout">
2934   <tr>
2935     <td>Linkage<br><br></td>
2936   </tr>
2937   <tr>
2938     <td>Parameter area<br><br></td>
2939   </tr>
2940   <tr>
2941     <td>Dynamic area<br><br></td>
2942   </tr>
2943   <tr>
2944     <td>Locals area<br><br></td>
2945   </tr>
2946   <tr>
2947     <td>Saved registers area<br><br></td>
2948   </tr>
2949   <tr style="border-style: none hidden none hidden;">
2950     <td><br></td>
2951   </tr>
2952   <tr>
2953     <td>Previous Frame<br><br></td>
2954   </tr>
2955 </table>
2956
2957 <p>The <i>linkage</i> area is used by a callee to save special registers prior
2958    to allocating its own frame.  Only three entries are relevant to LLVM. The
2959    first entry is the previous stack pointer (sp), aka link.  This allows
2960    probing tools like gdb or exception handlers to quickly scan the frames in
2961    the stack.  A function epilog can also use the link to pop the frame from the
2962    stack.  The third entry in the linkage area is used to save the return
2963    address from the lr register. Finally, as mentioned above, the last entry is
2964    used to save the previous frame pointer (r31.)  The entries in the linkage
2965    area are the size of a GPR, thus the linkage area is 24 bytes long in 32 bit
2966    mode and 48 bytes in 64 bit mode.</p>
2967
2968 <p>32 bit linkage area</p>
2969
2970 <table class="layout">
2971   <tr>
2972     <td>0</td>
2973     <td>Saved SP (r1)</td>
2974   </tr>
2975   <tr>
2976     <td>4</td>
2977     <td>Saved CR</td>
2978   </tr>
2979   <tr>
2980     <td>8</td>
2981     <td>Saved LR</td>
2982   </tr>
2983   <tr>
2984     <td>12</td>
2985     <td>Reserved</td>
2986   </tr>
2987   <tr>
2988     <td>16</td>
2989     <td>Reserved</td>
2990   </tr>
2991   <tr>
2992     <td>20</td>
2993     <td>Saved FP (r31)</td>
2994   </tr>
2995 </table>
2996
2997 <p>64 bit linkage area</p>
2998
2999 <table class="layout">
3000   <tr>
3001     <td>0</td>
3002     <td>Saved SP (r1)</td>
3003   </tr>
3004   <tr>
3005     <td>8</td>
3006     <td>Saved CR</td>
3007   </tr>
3008   <tr>
3009     <td>16</td>
3010     <td>Saved LR</td>
3011   </tr>
3012   <tr>
3013     <td>24</td>
3014     <td>Reserved</td>
3015   </tr>
3016   <tr>
3017     <td>32</td>
3018     <td>Reserved</td>
3019   </tr>
3020   <tr>
3021     <td>40</td>
3022     <td>Saved FP (r31)</td>
3023   </tr>
3024 </table>
3025
3026 <p>The <i>parameter area</i> is used to store arguments being passed to a callee
3027    function.  Following the PowerPC ABI, the first few arguments are actually
3028    passed in registers, with the space in the parameter area unused.  However,
3029    if there are not enough registers or the callee is a thunk or vararg
3030    function, these register arguments can be spilled into the parameter area.
3031    Thus, the parameter area must be large enough to store all the parameters for
3032    the largest call sequence made by the caller.  The size must also be
3033    minimally large enough to spill registers r3-r10.  This allows callees blind
3034    to the call signature, such as thunks and vararg functions, enough space to
3035    cache the argument registers.  Therefore, the parameter area is minimally 32
3036    bytes (64 bytes in 64 bit mode.)  Also note that since the parameter area is
3037    a fixed offset from the top of the frame, that a callee can access its spilt
3038    arguments using fixed offsets from the stack pointer (or base pointer.)</p>
3039
3040 <p>Combining the information about the linkage, parameter areas and alignment. A
3041    stack frame is minimally 64 bytes in 32 bit mode and 128 bytes in 64 bit
3042    mode.</p>
3043
3044 <p>The <i>dynamic area</i> starts out as size zero.  If a function uses dynamic
3045    alloca then space is added to the stack, the linkage and parameter areas are
3046    shifted to top of stack, and the new space is available immediately below the
3047    linkage and parameter areas.  The cost of shifting the linkage and parameter
3048    areas is minor since only the link value needs to be copied.  The link value
3049    can be easily fetched by adding the original frame size to the base pointer.
3050    Note that allocations in the dynamic space need to observe 16 byte
3051    alignment.</p>
3052
3053 <p>The <i>locals area</i> is where the llvm compiler reserves space for local
3054    variables.</p>
3055
3056 <p>The <i>saved registers area</i> is where the llvm compiler spills callee
3057    saved registers on entry to the callee.</p>
3058
3059 </div>
3060
3061 <!-- _______________________________________________________________________ -->
3062 <h4>
3063   <a name="ppc_prolog">Prolog/Epilog</a>
3064 </h4>
3065
3066 <div>
3067
3068 <p>The llvm prolog and epilog are the same as described in the PowerPC ABI, with
3069    the following exceptions.  Callee saved registers are spilled after the frame
3070    is created.  This allows the llvm epilog/prolog support to be common with
3071    other targets.  The base pointer callee saved register r31 is saved in the
3072    TOC slot of linkage area.  This simplifies allocation of space for the base
3073    pointer and makes it convenient to locate programatically and during
3074    debugging.</p>
3075
3076 </div>
3077
3078 <!-- _______________________________________________________________________ -->
3079 <h4>
3080   <a name="ppc_dynamic">Dynamic Allocation</a>
3081 </h4>
3082
3083 <div>
3084
3085 <p><i>TODO - More to come.</i></p>
3086
3087 </div>
3088
3089 </div>
3090
3091 <!-- ======================================================================= -->
3092 <h3>
3093   <a name="ptx">The PTX backend</a>
3094 </h3>
3095
3096 <div>
3097
3098 <p>The PTX code generator lives in the lib/Target/PTX directory. It is
3099   currently a work-in-progress, but already supports most of the code
3100   generation functionality needed to generate correct PTX kernels for
3101   CUDA devices.</p>
3102
3103 <p>The code generator can target PTX 2.0+, and shader model 1.0+.  The
3104   PTX ISA Reference Manual is used as the primary source of ISA
3105   information, though an effort is made to make the output of the code
3106   generator match the output of the NVidia nvcc compiler, whenever
3107   possible.</p>
3108
3109 <p>Code Generator Options:</p>
3110 <table border="1" cellspacing="0">
3111   <tr>
3112     <th>Option</th>
3113     <th>Description</th>
3114  </tr>
3115    <tr>
3116      <td><code>double</code></td>
3117      <td align="left">If enabled, the map_f64_to_f32 directive is
3118        disabled in the PTX output, allowing native double-precision
3119        arithmetic</td>
3120   </tr>
3121   <tr>
3122     <td><code>no-fma</code></td>
3123     <td align="left">Disable generation of Fused-Multiply Add
3124       instructions, which may be beneficial for some devices</td>
3125   </tr>
3126   <tr>
3127     <td><code>smxy / computexy</code></td>
3128     <td align="left">Set shader model/compute capability to x.y,
3129     e.g. sm20 or compute13</td>
3130   </tr>
3131 </table>
3132
3133 <p>Working:</p>
3134 <ul>
3135   <li>Arithmetic instruction selection (including combo FMA)</li>
3136   <li>Bitwise instruction selection</li>
3137   <li>Control-flow instruction selection</li>
3138   <li>Function calls (only on SM 2.0+ and no return arguments)</li>
3139   <li>Addresses spaces (0 = global, 1 = constant, 2 = local, 4 =
3140   shared)</li>
3141   <li>Thread synchronization (bar.sync)</li>
3142   <li>Special register reads ([N]TID, [N]CTAID, PMx, CLOCK, etc.)</li>
3143 </ul>
3144
3145 <p>In Progress:</p>
3146 <ul>
3147   <li>Robust call instruction selection</li>
3148   <li>Stack frame allocation</li>
3149   <li>Device-specific instruction scheduling optimizations</li>
3150 </ul>
3151
3152
3153 </div>
3154
3155 </div>
3156
3157 <!-- *********************************************************************** -->
3158 <hr>
3159 <address>
3160   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
3161   src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
3162   <a href="http://validator.w3.org/check/referer"><img
3163   src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
3164
3165   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
3166   <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
3167   Last modified: $Date$
3168 </address>
3169
3170 </body>
3171 </html>