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