1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                      "http://www.w3.org/TR/html4/strict.dtd">
3<html>
4<head>
5  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
6  <title>Writing an LLVM Compiler Backend</title>
7  <link rel="stylesheet" href="_static/llvm.css" type="text/css">
8</head>
9
10<body>
11
12<h1>
13  Writing an LLVM Compiler Backend
14</h1>
15
16<ol>
17  <li><a href="#intro">Introduction</a>
18  <ul>
19    <li><a href="#Audience">Audience</a></li>
20    <li><a href="#Prerequisite">Prerequisite Reading</a></li>
21    <li><a href="#Basic">Basic Steps</a></li>
22    <li><a href="#Preliminaries">Preliminaries</a></li>
23  </ul>
24  <li><a href="#TargetMachine">Target Machine</a></li>
25  <li><a href="#TargetRegistration">Target Registration</a></li>
26  <li><a href="#RegisterSet">Register Set and Register Classes</a>
27  <ul>
28    <li><a href="#RegisterDef">Defining a Register</a></li>
29    <li><a href="#RegisterClassDef">Defining a Register Class</a></li>
30    <li><a href="#implementRegister">Implement a subclass of TargetRegisterInfo</a></li>
31  </ul></li>
32  <li><a href="#InstructionSet">Instruction Set</a>
33  <ul>  
34    <li><a href="#operandMapping">Instruction Operand Mapping</a></li>
35    <li><a href="#implementInstr">Implement a subclass of TargetInstrInfo</a></li>
36    <li><a href="#branchFolding">Branch Folding and If Conversion</a></li>
37  </ul></li>
38  <li><a href="#InstructionSelector">Instruction Selector</a>
39  <ul>
40    <li><a href="#LegalizePhase">The SelectionDAG Legalize Phase</a>
41    <ul>
42      <li><a href="#promote">Promote</a></li> 
43      <li><a href="#expand">Expand</a></li> 
44      <li><a href="#custom">Custom</a></li> 
45      <li><a href="#legal">Legal</a></li>       
46    </ul></li>
47    <li><a href="#callingConventions">Calling Conventions</a></li>     
48  </ul></li>
49  <li><a href="#assemblyPrinter">Assembly Printer</a></li> 
50  <li><a href="#subtargetSupport">Subtarget Support</a></li> 
51  <li><a href="#jitSupport">JIT Support</a>
52  <ul>  
53    <li><a href="#mce">Machine Code Emitter</a></li>   
54    <li><a href="#targetJITInfo">Target JIT Info</a></li>   
55  </ul></li>
56</ol>
57
58<div class="doc_author">    
59  <p>Written by <a href="http://www.woo.com">Mason Woo</a> and
60                <a href="http://misha.brukman.net">Misha Brukman</a></p>
61</div>
62
63<!-- *********************************************************************** -->
64<h2>
65  <a name="intro">Introduction</a>
66</h2>
67<!-- *********************************************************************** -->
68
69<div>
70
71<p>
72This document describes techniques for writing compiler backends that convert
73the LLVM Intermediate Representation (IR) to code for a specified machine or
74other languages. Code intended for a specific machine can take the form of
75either assembly code or binary code (usable for a JIT compiler).
76</p>
77
78<p>
79The backend of LLVM features a target-independent code generator that may create
80output for several types of target CPUs &mdash; including X86, PowerPC, ARM,
81and SPARC. The backend may also be used to generate code targeted at SPUs of the
82Cell processor or GPUs to support the execution of compute kernels.
83</p>
84
85<p>
86The document focuses on existing examples found in subdirectories
87of <tt>llvm/lib/Target</tt> in a downloaded LLVM release. In particular, this
88document focuses on the example of creating a static compiler (one that emits
89text assembly) for a SPARC target, because SPARC has fairly standard
90characteristics, such as a RISC instruction set and straightforward calling
91conventions.
92</p>
93
94<h3>
95  <a name="Audience">Audience</a>
96</h3>
97
98<div>
99
100<p>
101The audience for this document is anyone who needs to write an LLVM backend to
102generate code for a specific hardware or software target.
103</p>
104
105</div>
106
107<h3>
108  <a name="Prerequisite">Prerequisite Reading</a>
109</h3>
110
111<div>  
112
113<p>
114These essential documents must be read before reading this document:
115</p>
116
117<ul>
118<li><i><a href="LangRef.html">LLVM Language Reference
119    Manual</a></i> &mdash; a reference manual for the LLVM assembly language.</li>
120
121<li><i><a href="CodeGenerator.html">The LLVM
122    Target-Independent Code Generator</a></i> &mdash; a guide to the components
123    (classes and code generation algorithms) for translating the LLVM internal
124    representation into machine code for a specified target.  Pay particular
125    attention to the descriptions of code generation stages: Instruction
126    Selection, Scheduling and Formation, SSA-based Optimization, Register
127    Allocation, Prolog/Epilog Code Insertion, Late Machine Code Optimizations,
128    and Code Emission.</li>
129
130<li><i><a href="TableGenFundamentals.html">TableGen
131    Fundamentals</a></i> &mdash;a document that describes the TableGen
132    (<tt>tblgen</tt>) application that manages domain-specific information to
133    support LLVM code generation. TableGen processes input from a target
134    description file (<tt>.td</tt> suffix) and generates C++ code that can be
135    used for code generation.</li>
136
137<li><i><a href="WritingAnLLVMPass.html">Writing an LLVM
138    Pass</a></i> &mdash; The assembly printer is a <tt>FunctionPass</tt>, as are
139    several SelectionDAG processing steps.</li>
140</ul>
141
142<p>
143To follow the SPARC examples in this document, have a copy of
144<i><a href="http://www.sparc.org/standards/V8.pdf">The SPARC Architecture
145Manual, Version 8</a></i> for reference. For details about the ARM instruction
146set, refer to the <i><a href="http://infocenter.arm.com/">ARM Architecture
147Reference Manual</a></i>. For more about the GNU Assembler format
148(<tt>GAS</tt>), see
149<i><a href="http://sourceware.org/binutils/docs/as/index.html">Using As</a></i>,
150especially for the assembly printer. <i>Using As</i> contains a list of target
151machine dependent features.
152</p>
153
154</div>
155
156<h3>
157  <a name="Basic">Basic Steps</a>
158</h3>
159
160<div>
161
162<p>
163To write a compiler backend for LLVM that converts the LLVM IR to code for a
164specified target (machine or other language), follow these steps:
165</p>
166
167<ul>
168<li>Create a subclass of the TargetMachine class that describes characteristics
169    of your target machine. Copy existing examples of specific TargetMachine
170    class and header files; for example, start with
171    <tt>SparcTargetMachine.cpp</tt> and <tt>SparcTargetMachine.h</tt>, but
172    change the file names for your target. Similarly, change code that
173    references "Sparc" to reference your target. </li>
174
175<li>Describe the register set of the target. Use TableGen to generate code for
176    register definition, register aliases, and register classes from a
177    target-specific <tt>RegisterInfo.td</tt> input file. You should also write
178    additional code for a subclass of the TargetRegisterInfo class that
179    represents the class register file data used for register allocation and
180    also describes the interactions between registers.</li>
181
182<li>Describe the instruction set of the target. Use TableGen to generate code
183    for target-specific instructions from target-specific versions of
184    <tt>TargetInstrFormats.td</tt> and <tt>TargetInstrInfo.td</tt>. You should
185    write additional code for a subclass of the TargetInstrInfo class to
186    represent machine instructions supported by the target machine. </li>
187
188<li>Describe the selection and conversion of the LLVM IR from a Directed Acyclic
189    Graph (DAG) representation of instructions to native target-specific
190    instructions. Use TableGen to generate code that matches patterns and
191    selects instructions based on additional information in a target-specific
192    version of <tt>TargetInstrInfo.td</tt>. Write code
193    for <tt>XXXISelDAGToDAG.cpp</tt>, where XXX identifies the specific target,
194    to perform pattern matching and DAG-to-DAG instruction selection. Also write
195    code in <tt>XXXISelLowering.cpp</tt> to replace or remove operations and
196    data types that are not supported natively in a SelectionDAG. </li>
197
198<li>Write code for an assembly printer that converts LLVM IR to a GAS format for
199    your target machine.  You should add assembly strings to the instructions
200    defined in your target-specific version of <tt>TargetInstrInfo.td</tt>. You
201    should also write code for a subclass of AsmPrinter that performs the
202    LLVM-to-assembly conversion and a trivial subclass of TargetAsmInfo.</li>
203
204<li>Optionally, add support for subtargets (i.e., variants with different
205    capabilities). You should also write code for a subclass of the
206    TargetSubtarget class, which allows you to use the <tt>-mcpu=</tt>
207    and <tt>-mattr=</tt> command-line options.</li>
208
209<li>Optionally, add JIT support and create a machine code emitter (subclass of
210    TargetJITInfo) that is used to emit binary code directly into memory. </li>
211</ul>
212
213<p>
214In the <tt>.cpp</tt> and <tt>.h</tt>. files, initially stub up these methods and
215then implement them later. Initially, you may not know which private members
216that the class will need and which components will need to be subclassed.
217</p>
218
219</div>
220
221<h3>
222  <a name="Preliminaries">Preliminaries</a>
223</h3>
224
225<div>
226
227<p>
228To actually create your compiler backend, you need to create and modify a few
229files. The absolute minimum is discussed here. But to actually use the LLVM
230target-independent code generator, you must perform the steps described in
231the <a href="CodeGenerator.html">LLVM
232Target-Independent Code Generator</a> document.
233</p>
234
235<p>
236First, you should create a subdirectory under <tt>lib/Target</tt> to hold all
237the files related to your target. If your target is called "Dummy," create the
238directory <tt>lib/Target/Dummy</tt>.
239</p>
240
241<p>
242In this new
243directory, create a <tt>Makefile</tt>. It is easiest to copy a
244<tt>Makefile</tt> of another target and modify it. It should at least contain
245the <tt>LEVEL</tt>, <tt>LIBRARYNAME</tt> and <tt>TARGET</tt> variables, and then
246include <tt>$(LEVEL)/Makefile.common</tt>. The library can be
247named <tt>LLVMDummy</tt> (for example, see the MIPS target). Alternatively, you
248can split the library into <tt>LLVMDummyCodeGen</tt>
249and <tt>LLVMDummyAsmPrinter</tt>, the latter of which should be implemented in a
250subdirectory below <tt>lib/Target/Dummy</tt> (for example, see the PowerPC
251target).
252</p>
253
254<p>
255Note that these two naming schemes are hardcoded into <tt>llvm-config</tt>.
256Using any other naming scheme will confuse <tt>llvm-config</tt> and produce a
257lot of (seemingly unrelated) linker errors when linking <tt>llc</tt>.
258</p>
259
260<p>
261To make your target actually do something, you need to implement a subclass of
262<tt>TargetMachine</tt>. This implementation should typically be in the file
263<tt>lib/Target/DummyTargetMachine.cpp</tt>, but any file in
264the <tt>lib/Target</tt> directory will be built and should work. To use LLVM's
265target independent code generator, you should do what all current machine
266backends do: create a subclass of <tt>LLVMTargetMachine</tt>. (To create a
267target from scratch, create a subclass of <tt>TargetMachine</tt>.)
268</p>
269
270<p>
271To get LLVM to actually build and link your target, you need to add it to
272the <tt>TARGETS_TO_BUILD</tt> variable. To do this, you modify the configure
273script to know about your target when parsing the <tt>--enable-targets</tt>
274option. Search the configure script for <tt>TARGETS_TO_BUILD</tt>, add your
275target to the lists there (some creativity required), and then
276reconfigure. Alternatively, you can change <tt>autotools/configure.ac</tt> and
277regenerate configure by running <tt>/autoconf/AutoRegen.sh</tt>.
278</p>
279
280</div>
281
282</div>
283
284<!-- *********************************************************************** -->
285<h2>
286  <a name="TargetMachine">Target Machine</a>
287</h2>
288<!-- *********************************************************************** -->
289
290<div>
291
292<p>
293<tt>LLVMTargetMachine</tt> is designed as a base class for targets implemented
294with the LLVM target-independent code generator. The <tt>LLVMTargetMachine</tt>
295class should be specialized by a concrete target class that implements the
296various virtual methods. <tt>LLVMTargetMachine</tt> is defined as a subclass of
297<tt>TargetMachine</tt> in <tt>include/llvm/Target/TargetMachine.h</tt>. The
298<tt>TargetMachine</tt> class implementation (<tt>TargetMachine.cpp</tt>) also
299processes numerous command-line options.
300</p>
301
302<p>
303To create a concrete target-specific subclass of <tt>LLVMTargetMachine</tt>,
304start by copying an existing <tt>TargetMachine</tt> class and header.  You
305should name the files that you create to reflect your specific target. For
306instance, for the SPARC target, name the files <tt>SparcTargetMachine.h</tt> and
307<tt>SparcTargetMachine.cpp</tt>.
308</p>
309
310<p>
311For a target machine <tt>XXX</tt>, the implementation of
312<tt>XXXTargetMachine</tt> must have access methods to obtain objects that
313represent target components.  These methods are named <tt>get*Info</tt>, and are
314intended to obtain the instruction set (<tt>getInstrInfo</tt>), register set
315(<tt>getRegisterInfo</tt>), stack frame layout (<tt>getFrameInfo</tt>), and
316similar information. <tt>XXXTargetMachine</tt> must also implement the
317<tt>getTargetData</tt> method to access an object with target-specific data
318characteristics, such as data type size and alignment requirements.
319</p>
320
321<p>
322For instance, for the SPARC target, the header file
323<tt>SparcTargetMachine.h</tt> declares prototypes for several <tt>get*Info</tt>
324and <tt>getTargetData</tt> methods that simply return a class member.
325</p>
326
327<div class="doc_code">
328<pre>
329namespace llvm {
330
331class Module;
332
333class SparcTargetMachine : public LLVMTargetMachine {
334  const TargetData DataLayout;       // Calculates type size &amp; alignment
335  SparcSubtarget Subtarget;
336  SparcInstrInfo InstrInfo;
337  TargetFrameInfo FrameInfo;
338  
339protected:
340  virtual const TargetAsmInfo *createTargetAsmInfo() const;
341  
342public:
343  SparcTargetMachine(const Module &amp;M, const std::string &amp;FS);
344
345  virtual const SparcInstrInfo *getInstrInfo() const {return &amp;InstrInfo; }
346  virtual const TargetFrameInfo *getFrameInfo() const {return &amp;FrameInfo; }
347  virtual const TargetSubtarget *getSubtargetImpl() const{return &amp;Subtarget; }
348  virtual const TargetRegisterInfo *getRegisterInfo() const {
349    return &amp;InstrInfo.getRegisterInfo();
350  }
351  virtual const TargetData *getTargetData() const { return &amp;DataLayout; }
352  static unsigned getModuleMatchQuality(const Module &amp;M);
353
354  // Pass Pipeline Configuration
355  virtual bool addInstSelector(PassManagerBase &amp;PM, bool Fast);
356  virtual bool addPreEmitPass(PassManagerBase &amp;PM, bool Fast);
357};
358
359} // end namespace llvm
360</pre>
361</div>
362
363<ul>
364<li><tt>getInstrInfo()</tt></li>
365<li><tt>getRegisterInfo()</tt></li>
366<li><tt>getFrameInfo()</tt></li>
367<li><tt>getTargetData()</tt></li>
368<li><tt>getSubtargetImpl()</tt></li>
369</ul>
370
371<p>For some targets, you also need to support the following methods:</p>
372
373<ul>
374<li><tt>getTargetLowering()</tt></li>
375<li><tt>getJITInfo()</tt></li>
376</ul>
377
378<p>
379In addition, the <tt>XXXTargetMachine</tt> constructor should specify a
380<tt>TargetDescription</tt> string that determines the data layout for the target
381machine, including characteristics such as pointer size, alignment, and
382endianness. For example, the constructor for SparcTargetMachine contains the
383following:
384</p>
385
386<div class="doc_code">
387<pre>
388SparcTargetMachine::SparcTargetMachine(const Module &amp;M, const std::string &amp;FS)
389  : DataLayout("E-p:32:32-f128:128:128"),
390    Subtarget(M, FS), InstrInfo(Subtarget),
391    FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
392}
393</pre>
394</div>
395
396<p>Hyphens separate portions of the <tt>TargetDescription</tt> string.</p>
397
398<ul>
399<li>An upper-case "<tt>E</tt>" in the string indicates a big-endian target data
400    model. a lower-case "<tt>e</tt>" indicates little-endian.</li>
401
402<li>"<tt>p:</tt>" is followed by pointer information: size, ABI alignment, and
403    preferred alignment. If only two figures follow "<tt>p:</tt>", then the
404    first value is pointer size, and the second value is both ABI and preferred
405    alignment.</li>
406
407<li>Then a letter for numeric type alignment: "<tt>i</tt>", "<tt>f</tt>",
408    "<tt>v</tt>", or "<tt>a</tt>" (corresponding to integer, floating point,
409    vector, or aggregate). "<tt>i</tt>", "<tt>v</tt>", or "<tt>a</tt>" are
410    followed by ABI alignment and preferred alignment. "<tt>f</tt>" is followed
411    by three values: the first indicates the size of a long double, then ABI
412    alignment, and then ABI preferred alignment.</li>
413</ul>
414
415</div>
416
417<!-- *********************************************************************** -->
418<h2>
419  <a name="TargetRegistration">Target Registration</a>
420</h2>
421<!-- *********************************************************************** -->
422
423<div>
424
425<p>
426You must also register your target with the <tt>TargetRegistry</tt>, which is
427what other LLVM tools use to be able to lookup and use your target at
428runtime. The <tt>TargetRegistry</tt> can be used directly, but for most targets
429there are helper templates which should take care of the work for you.</p>
430
431<p>
432All targets should declare a global <tt>Target</tt> object which is used to
433represent the target during registration. Then, in the target's TargetInfo
434library, the target should define that object and use
435the <tt>RegisterTarget</tt> template to register the target. For example, the Sparc registration code looks like this:
436</p>
437
438<div class="doc_code">
439<pre>
440Target llvm::TheSparcTarget;
441
442extern "C" void LLVMInitializeSparcTargetInfo() { 
443  RegisterTarget&lt;Triple::sparc, /*HasJIT=*/false&gt;
444    X(TheSparcTarget, "sparc", "Sparc");
445}
446</pre>
447</div>
448
449<p>
450This allows the <tt>TargetRegistry</tt> to look up the target by name or by
451target triple. In addition, most targets will also register additional features
452which are available in separate libraries. These registration steps are
453separate, because some clients may wish to only link in some parts of the target
454-- the JIT code generator does not require the use of the assembler printer, for
455example. Here is an example of registering the Sparc assembly printer:
456</p>
457
458<div class="doc_code">
459<pre>
460extern "C" void LLVMInitializeSparcAsmPrinter() { 
461  RegisterAsmPrinter&lt;SparcAsmPrinter&gt; X(TheSparcTarget);
462}
463</pre>
464</div>
465
466<p>
467For more information, see
468"<a href="/doxygen/TargetRegistry_8h-source.html">llvm/Target/TargetRegistry.h</a>".
469</p>
470
471</div>
472
473<!-- *********************************************************************** -->
474<h2>
475  <a name="RegisterSet">Register Set and Register Classes</a>
476</h2>
477<!-- *********************************************************************** -->
478
479<div>
480
481<p>
482You should describe a concrete target-specific class that represents the
483register file of a target machine. This class is called <tt>XXXRegisterInfo</tt>
484(where <tt>XXX</tt> identifies the target) and represents the class register
485file data that is used for register allocation. It also describes the
486interactions between registers.
487</p>
488
489<p>
490You also need to define register classes to categorize related registers. A
491register class should be added for groups of registers that are all treated the
492same way for some instruction. Typical examples are register classes for
493integer, floating-point, or vector registers. A register allocator allows an
494instruction to use any register in a specified register class to perform the
495instruction in a similar manner. Register classes allocate virtual registers to
496instructions from these sets, and register classes let the target-independent
497register allocator automatically choose the actual registers.
498</p>
499
500<p>
501Much of the code for registers, including register definition, register aliases,
502and register classes, is generated by TableGen from <tt>XXXRegisterInfo.td</tt>
503input files and placed in <tt>XXXGenRegisterInfo.h.inc</tt> and
504<tt>XXXGenRegisterInfo.inc</tt> output files. Some of the code in the
505implementation of <tt>XXXRegisterInfo</tt> requires hand-coding.
506</p>
507
508<!-- ======================================================================= -->
509<h3>
510  <a name="RegisterDef">Defining a Register</a>
511</h3>
512
513<div>
514
515<p>
516The <tt>XXXRegisterInfo.td</tt> file typically starts with register definitions
517for a target machine. The <tt>Register</tt> class (specified
518in <tt>Target.td</tt>) is used to define an object for each register. The
519specified string <tt>n</tt> becomes the <tt>Name</tt> of the register. The
520basic <tt>Register</tt> object does not have any subregisters and does not
521specify any aliases.
522</p>
523
524<div class="doc_code">
525<pre>
526class Register&lt;string n&gt; {
527  string Namespace = "";
528  string AsmName = n;
529  string Name = n;
530  int SpillSize = 0;
531  int SpillAlignment = 0;
532  list&lt;Register&gt; Aliases = [];
533  list&lt;Register&gt; SubRegs = [];
534  list&lt;int&gt; DwarfNumbers = [];
535}
536</pre>
537</div>
538
539<p>
540For example, in the <tt>X86RegisterInfo.td</tt> file, there are register
541definitions that utilize the Register class, such as:
542</p>
543
544<div class="doc_code">
545<pre>
546def AL : Register&lt;"AL"&gt;, DwarfRegNum&lt;[0, 0, 0]&gt;;
547</pre>
548</div>
549
550<p>
551This defines the register <tt>AL</tt> and assigns it values (with
552<tt>DwarfRegNum</tt>) that are used by <tt>gcc</tt>, <tt>gdb</tt>, or a debug
553information writer to identify a register. For register
554<tt>AL</tt>, <tt>DwarfRegNum</tt> takes an array of 3 values representing 3
555different modes: the first element is for X86-64, the second for exception
556handling (EH) on X86-32, and the third is generic. -1 is a special Dwarf number
557that indicates the gcc number is undefined, and -2 indicates the register number
558is invalid for this mode.
559</p>
560
561<p>
562From the previously described line in the <tt>X86RegisterInfo.td</tt> file,
563TableGen generates this code in the <tt>X86GenRegisterInfo.inc</tt> file:
564</p>
565
566<div class="doc_code">
567<pre>
568static const unsigned GR8[] = { X86::AL, ... };
569
570const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 };
571
572const TargetRegisterDesc RegisterDescriptors[] = { 
573  ...
574{ "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ...
575</pre>
576</div>
577
578<p>
579From the register info file, TableGen generates a <tt>TargetRegisterDesc</tt>
580object for each register. <tt>TargetRegisterDesc</tt> is defined in
581<tt>include/llvm/Target/TargetRegisterInfo.h</tt> with the following fields:
582</p>
583
584<div class="doc_code">
585<pre>
586struct TargetRegisterDesc {
587  const char     *AsmName;      // Assembly language name for the register
588  const char     *Name;         // Printable name for the reg (for debugging)
589  const unsigned *AliasSet;     // Register Alias Set
590  const unsigned *SubRegs;      // Sub-register set
591  const unsigned *ImmSubRegs;   // Immediate sub-register set
592  const unsigned *SuperRegs;    // Super-register set
593};</pre>
594</div>
595
596<p>
597TableGen uses the entire target description file (<tt>.td</tt>) to determine
598text names for the register (in the <tt>AsmName</tt> and <tt>Name</tt> fields of
599<tt>TargetRegisterDesc</tt>) and the relationships of other registers to the
600defined register (in the other <tt>TargetRegisterDesc</tt> fields). In this
601example, other definitions establish the registers "<tt>AX</tt>",
602"<tt>EAX</tt>", and "<tt>RAX</tt>" as aliases for one another, so TableGen
603generates a null-terminated array (<tt>AL_AliasSet</tt>) for this register alias
604set.
605</p>
606
607<p>
608The <tt>Register</tt> class is commonly used as a base class for more complex
609classes. In <tt>Target.td</tt>, the <tt>Register</tt> class is the base for the
610<tt>RegisterWithSubRegs</tt> class that is used to define registers that need to
611specify subregisters in the <tt>SubRegs</tt> list, as shown here:
612</p>
613
614<div class="doc_code">
615<pre>
616class RegisterWithSubRegs&lt;string n,
617list&lt;Register&gt; subregs&gt; : Register&lt;n&gt; {
618  let SubRegs = subregs;
619}
620</pre>
621</div>
622
623<p>
624In <tt>SparcRegisterInfo.td</tt>, additional register classes are defined for
625SPARC: a Register subclass, SparcReg, and further subclasses: <tt>Ri</tt>,
626<tt>Rf</tt>, and <tt>Rd</tt>. SPARC registers are identified by 5-bit ID
627numbers, which is a feature common to these subclasses. Note the use of
628'<tt>let</tt>' expressions to override values that are initially defined in a
629superclass (such as <tt>SubRegs</tt> field in the <tt>Rd</tt> class).
630</p>
631
632<div class="doc_code">
633<pre>
634class SparcReg&lt;string n&gt; : Register&lt;n&gt; {
635  field bits&lt;5&gt; Num;
636  let Namespace = "SP";
637}
638// Ri - 32-bit integer registers
639class Ri&lt;bits&lt;5&gt; num, string n&gt; :
640SparcReg&lt;n&gt; {
641  let Num = num;
642}
643// Rf - 32-bit floating-point registers
644class Rf&lt;bits&lt;5&gt; num, string n&gt; :
645SparcReg&lt;n&gt; {
646  let Num = num;
647}
648// Rd - Slots in the FP register file for 64-bit
649floating-point values.
650class Rd&lt;bits&lt;5&gt; num, string n,
651list&lt;Register&gt; subregs&gt; : SparcReg&lt;n&gt; {
652  let Num = num;
653  let SubRegs = subregs;
654}
655</pre>
656</div>
657
658<p>
659In the <tt>SparcRegisterInfo.td</tt> file, there are register definitions that
660utilize these subclasses of <tt>Register</tt>, such as:
661</p>
662
663<div class="doc_code">
664<pre>
665def G0 : Ri&lt; 0, "G0"&gt;,
666DwarfRegNum&lt;[0]&gt;;
667def G1 : Ri&lt; 1, "G1"&gt;, DwarfRegNum&lt;[1]&gt;;
668...
669def F0 : Rf&lt; 0, "F0"&gt;,
670DwarfRegNum&lt;[32]&gt;;
671def F1 : Rf&lt; 1, "F1"&gt;,
672DwarfRegNum&lt;[33]&gt;;
673...
674def D0 : Rd&lt; 0, "F0", [F0, F1]&gt;,
675DwarfRegNum&lt;[32]&gt;;
676def D1 : Rd&lt; 2, "F2", [F2, F3]&gt;,
677DwarfRegNum&lt;[34]&gt;;
678</pre>
679</div>
680
681<p>
682The last two registers shown above (<tt>D0</tt> and <tt>D1</tt>) are
683double-precision floating-point registers that are aliases for pairs of
684single-precision floating-point sub-registers. In addition to aliases, the
685sub-register and super-register relationships of the defined register are in
686fields of a register's TargetRegisterDesc.
687</p>
688
689</div>
690
691<!-- ======================================================================= -->
692<h3>
693  <a name="RegisterClassDef">Defining a Register Class</a>
694</h3>
695
696<div>
697
698<p>
699The <tt>RegisterClass</tt> class (specified in <tt>Target.td</tt>) is used to
700define an object that represents a group of related registers and also defines
701the default allocation order of the registers. A target description file
702<tt>XXXRegisterInfo.td</tt> that uses <tt>Target.td</tt> can construct register
703classes using the following class:
704</p>
705
706<div class="doc_code">
707<pre>
708class RegisterClass&lt;string namespace,
709list&lt;ValueType&gt; regTypes, int alignment, dag regList&gt; {
710  string Namespace = namespace;
711  list&lt;ValueType&gt; RegTypes = regTypes;
712  int Size = 0;  // spill size, in bits; zero lets tblgen pick the size
713  int Alignment = alignment;
714
715  // CopyCost is the cost of copying a value between two registers
716  // default value 1 means a single instruction
717  // A negative value means copying is extremely expensive or impossible
718  int CopyCost = 1;  
719  dag MemberList = regList;
720  
721  // for register classes that are subregisters of this class
722  list&lt;RegisterClass&gt; SubRegClassList = [];  
723  
724  code MethodProtos = [{}];  // to insert arbitrary code
725  code MethodBodies = [{}];
726}
727</pre>
728</div>
729
730<p>To define a RegisterClass, use the following 4 arguments:</p>
731
732<ul>
733<li>The first argument of the definition is the name of the namespace.</li>
734
735<li>The second argument is a list of <tt>ValueType</tt> register type values
736    that are defined in <tt>include/llvm/CodeGen/ValueTypes.td</tt>. Defined
737    values include integer types (such as <tt>i16</tt>, <tt>i32</tt>,
738    and <tt>i1</tt> for Boolean), floating-point types
739    (<tt>f32</tt>, <tt>f64</tt>), and vector types (for example, <tt>v8i16</tt>
740    for an <tt>8 x i16</tt> vector). All registers in a <tt>RegisterClass</tt>
741    must have the same <tt>ValueType</tt>, but some registers may store vector
742    data in different configurations. For example a register that can process a
743    128-bit vector may be able to handle 16 8-bit integer elements, 8 16-bit
744    integers, 4 32-bit integers, and so on. </li>
745
746<li>The third argument of the <tt>RegisterClass</tt> definition specifies the
747    alignment required of the registers when they are stored or loaded to
748    memory.</li>
749
750<li>The final argument, <tt>regList</tt>, specifies which registers are in this
751    class. If an alternative allocation order method is not specified, then
752    <tt>regList</tt> also defines the order of allocation used by the register
753    allocator. Besides simply listing registers with <tt>(add R0, R1, ...)</tt>,
754    more advanced set operators are available. See
755    <tt>include/llvm/Target/Target.td</tt> for more information.</li>
756</ul>
757
758<p>
759In <tt>SparcRegisterInfo.td</tt>, three RegisterClass objects are defined:
760<tt>FPRegs</tt>, <tt>DFPRegs</tt>, and <tt>IntRegs</tt>. For all three register
761classes, the first argument defines the namespace with the string
762'<tt>SP</tt>'. <tt>FPRegs</tt> defines a group of 32 single-precision
763floating-point registers (<tt>F0</tt> to <tt>F31</tt>); <tt>DFPRegs</tt> defines
764a group of 16 double-precision registers
765(<tt>D0-D15</tt>).
766</p>
767
768<div class="doc_code">
769<pre>
770// F0, F1, F2, ..., F31
771def FPRegs : RegisterClass&lt;"SP", [f32], 32, (sequence "F%u", 0, 31)&gt;;
772
773def DFPRegs : RegisterClass&lt;"SP", [f64], 64,
774                            (add D0, D1, D2, D3, D4, D5, D6, D7, D8,
775                                 D9, D10, D11, D12, D13, D14, D15)&gt;;
776&nbsp;
777def IntRegs : RegisterClass&lt;"SP", [i32], 32,
778    (add L0, L1, L2, L3, L4, L5, L6, L7,
779         I0, I1, I2, I3, I4, I5,
780         O0, O1, O2, O3, O4, O5, O7,
781         G1,
782         // Non-allocatable regs:
783         G2, G3, G4,
784         O6,        // stack ptr
785         I6,        // frame ptr
786         I7,        // return address
787         G0,        // constant zero
788         G5, G6, G7 // reserved for kernel
789    )&gt;;
790</pre>
791</div>
792
793<p>
794Using <tt>SparcRegisterInfo.td</tt> with TableGen generates several output files
795that are intended for inclusion in other source code that you write.
796<tt>SparcRegisterInfo.td</tt> generates <tt>SparcGenRegisterInfo.h.inc</tt>,
797which should be included in the header file for the implementation of the SPARC
798register implementation that you write (<tt>SparcRegisterInfo.h</tt>). In
799<tt>SparcGenRegisterInfo.h.inc</tt> a new structure is defined called
800<tt>SparcGenRegisterInfo</tt> that uses <tt>TargetRegisterInfo</tt> as its
801base. It also specifies types, based upon the defined register
802classes: <tt>DFPRegsClass</tt>, <tt>FPRegsClass</tt>, and <tt>IntRegsClass</tt>.
803</p>
804
805<p>
806<tt>SparcRegisterInfo.td</tt> also generates <tt>SparcGenRegisterInfo.inc</tt>,
807which is included at the bottom of <tt>SparcRegisterInfo.cpp</tt>, the SPARC
808register implementation. The code below shows only the generated integer
809registers and associated register classes. The order of registers
810in <tt>IntRegs</tt> reflects the order in the definition of <tt>IntRegs</tt> in
811the target description file.
812</p>
813
814<div class="doc_code">
815<pre>  // IntRegs Register Class...
816  static const unsigned IntRegs[] = {
817    SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5,
818    SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3,
819    SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3,
820    SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3,
821    SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5,
822    SP::G6, SP::G7, 
823  };
824
825  // IntRegsVTs Register Class Value Types...
826  static const MVT::ValueType IntRegsVTs[] = {
827    MVT::i32, MVT::Other
828  };
829
830namespace SP {   // Register class instances
831  DFPRegsClass&nbsp;&nbsp;&nbsp; DFPRegsRegClass;
832  FPRegsClass&nbsp;&nbsp;&nbsp;&nbsp; FPRegsRegClass;
833  IntRegsClass&nbsp;&nbsp;&nbsp; IntRegsRegClass;
834...
835  // IntRegs Sub-register Classess...
836  static const TargetRegisterClass* const IntRegsSubRegClasses [] = {
837    NULL
838  };
839...
840  // IntRegs Super-register Classess...
841  static const TargetRegisterClass* const IntRegsSuperRegClasses [] = {
842    NULL
843  };
844...
845  // IntRegs Register Class sub-classes...
846  static const TargetRegisterClass* const IntRegsSubclasses [] = {
847    NULL
848  };
849...
850  // IntRegs Register Class super-classes...
851  static const TargetRegisterClass* const IntRegsSuperclasses [] = {
852    NULL
853  };
854
855  IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID, 
856    IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses, 
857    IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {}
858}
859</pre>
860</div>
861
862<p>
863The register allocators will avoid using reserved registers, and callee saved
864registers are not used until all the volatile registers have been used.  That
865is usually good enough, but in some cases it may be necessary to provide custom
866allocation orders.
867</p>
868
869</div>
870
871<!-- ======================================================================= -->
872<h3>
873  <a name="implementRegister">Implement a subclass of</a> 
874  <a href="CodeGenerator.html#targetregisterinfo">TargetRegisterInfo</a>
875</h3>
876
877<div>
878
879<p>
880The final step is to hand code portions of <tt>XXXRegisterInfo</tt>, which
881implements the interface described in <tt>TargetRegisterInfo.h</tt>. These
882functions return <tt>0</tt>, <tt>NULL</tt>, or <tt>false</tt>, unless
883overridden. Here is a list of functions that are overridden for the SPARC
884implementation in <tt>SparcRegisterInfo.cpp</tt>:
885</p>
886
887<ul>
888<li><tt>getCalleeSavedRegs</tt> &mdash; Returns a list of callee-saved registers
889    in the order of the desired callee-save stack frame offset.</li>
890
891<li><tt>getReservedRegs</tt> &mdash; Returns a bitset indexed by physical
892    register numbers, indicating if a particular register is unavailable.</li>
893
894<li><tt>hasFP</tt> &mdash; Return a Boolean indicating if a function should have
895    a dedicated frame pointer register.</li>
896
897<li><tt>eliminateCallFramePseudoInstr</tt> &mdash; If call frame setup or
898    destroy pseudo instructions are used, this can be called to eliminate
899    them.</li>
900
901<li><tt>eliminateFrameIndex</tt> &mdash; Eliminate abstract frame indices from
902    instructions that may use them.</li>
903
904<li><tt>emitPrologue</tt> &mdash; Insert prologue code into the function.</li>
905
906<li><tt>emitEpilogue</tt> &mdash; Insert epilogue code into the function.</li>
907</ul>
908
909</div>
910
911</div>
912
913<!-- *********************************************************************** -->
914<h2>
915  <a name="InstructionSet">Instruction Set</a>
916</h2>
917
918<!-- *********************************************************************** -->
919<div>
920
921<p>
922During the early stages of code generation, the LLVM IR code is converted to a
923<tt>SelectionDAG</tt> with nodes that are instances of the <tt>SDNode</tt> class
924containing target instructions. An <tt>SDNode</tt> has an opcode, operands, type
925requirements, and operation properties. For example, is an operation
926commutative, does an operation load from memory. The various operation node
927types are described in the <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>
928file (values of the <tt>NodeType</tt> enum in the <tt>ISD</tt> namespace).
929</p>
930
931<p>
932TableGen uses the following target description (<tt>.td</tt>) input files to
933generate much of the code for instruction definition:
934</p>
935
936<ul>
937<li><tt>Target.td</tt> &mdash; Where the <tt>Instruction</tt>, <tt>Operand</tt>,
938    <tt>InstrInfo</tt>, and other fundamental classes are defined.</li>
939
940<li><tt>TargetSelectionDAG.td</tt>&mdash; Used by <tt>SelectionDAG</tt>
941    instruction selection generators, contains <tt>SDTC*</tt> classes (selection
942    DAG type constraint), definitions of <tt>SelectionDAG</tt> nodes (such as
943    <tt>imm</tt>, <tt>cond</tt>, <tt>bb</tt>, <tt>add</tt>, <tt>fadd</tt>,
944    <tt>sub</tt>), and pattern support (<tt>Pattern</tt>, <tt>Pat</tt>,
945    <tt>PatFrag</tt>, <tt>PatLeaf</tt>, <tt>ComplexPattern</tt>.</li>
946
947<li><tt>XXXInstrFormats.td</tt> &mdash; Patterns for definitions of
948    target-specific instructions.</li>
949
950<li><tt>XXXInstrInfo.td</tt> &mdash; Target-specific definitions of instruction
951    templates, condition codes, and instructions of an instruction set. For
952    architecture modifications, a different file name may be used. For example,
953    for Pentium with SSE instruction, this file is <tt>X86InstrSSE.td</tt>, and
954    for Pentium with MMX, this file is <tt>X86InstrMMX.td</tt>.</li>
955</ul>
956
957<p>
958There is also a target-specific <tt>XXX.td</tt> file, where <tt>XXX</tt> is the
959name of the target. The <tt>XXX.td</tt> file includes the other <tt>.td</tt>
960input files, but its contents are only directly important for subtargets.
961</p>
962
963<p>
964You should describe a concrete target-specific class <tt>XXXInstrInfo</tt> that
965represents machine instructions supported by a target machine.
966<tt>XXXInstrInfo</tt> contains an array of <tt>XXXInstrDescriptor</tt> objects,
967each of which describes one instruction. An instruction descriptor defines:</p>
968
969<ul>
970<li>Opcode mnemonic</li>
971
972<li>Number of operands</li>
973
974<li>List of implicit register definitions and uses</li>
975
976<li>Target-independent properties (such as memory access, is commutable)</li>
977
978<li>Target-specific flags </li>
979</ul>
980
981<p>
982The Instruction class (defined in <tt>Target.td</tt>) is mostly used as a base
983for more complex instruction classes.
984</p>
985
986<div class="doc_code">
987<pre>class Instruction {
988  string Namespace = "";
989  dag OutOperandList;       // An dag containing the MI def operand list.
990  dag InOperandList;        // An dag containing the MI use operand list.
991  string AsmString = "";    // The .s format to print the instruction with.
992  list&lt;dag&gt; Pattern;  // Set to the DAG pattern for this instruction
993  list&lt;Register&gt; Uses = []; 
994  list&lt;Register&gt; Defs = [];
995  list&lt;Predicate&gt; Predicates = [];  // predicates turned into isel match code
996  ... remainder not shown for space ...
997}
998</pre>
999</div>
1000
1001<p>
1002A <tt>SelectionDAG</tt> node (<tt>SDNode</tt>) should contain an object
1003representing a target-specific instruction that is defined
1004in <tt>XXXInstrInfo.td</tt>. The instruction objects should represent
1005instructions from the architecture manual of the target machine (such as the
1006SPARC Architecture Manual for the SPARC target).
1007</p>
1008
1009<p>
1010A single instruction from the architecture manual is often modeled as multiple
1011target instructions, depending upon its operands. For example, a manual might
1012describe an add instruction that takes a register or an immediate operand. An
1013LLVM target could model this with two instructions named <tt>ADDri</tt> and
1014<tt>ADDrr</tt>.
1015</p>
1016
1017<p>
1018You should define a class for each instruction category and define each opcode
1019as a subclass of the category with appropriate parameters such as the fixed
1020binary encoding of opcodes and extended opcodes. You should map the register
1021bits to the bits of the instruction in which they are encoded (for the
1022JIT). Also you should specify how the instruction should be printed when the
1023automatic assembly printer is used.
1024</p>
1025
1026<p>
1027As is described in the SPARC Architecture Manual, Version 8, there are three
1028major 32-bit formats for instructions. Format 1 is only for the <tt>CALL</tt>
1029instruction. Format 2 is for branch on condition codes and <tt>SETHI</tt> (set
1030high bits of a register) instructions.  Format 3 is for other instructions.
1031</p>
1032
1033<p>
1034Each of these formats has corresponding classes in <tt>SparcInstrFormat.td</tt>.
1035<tt>InstSP</tt> is a base class for other instruction classes. Additional base
1036classes are specified for more precise formats: for example
1037in <tt>SparcInstrFormat.td</tt>, <tt>F2_1</tt> is for <tt>SETHI</tt>,
1038and <tt>F2_2</tt> is for branches. There are three other base
1039classes: <tt>F3_1</tt> for register/register operations, <tt>F3_2</tt> for
1040register/immediate operations, and <tt>F3_3</tt> for floating-point
1041operations. <tt>SparcInstrInfo.td</tt> also adds the base class Pseudo for
1042synthetic SPARC instructions.
1043</p>
1044
1045<p>
1046<tt>SparcInstrInfo.td</tt> largely consists of operand and instruction
1047definitions for the SPARC target. In <tt>SparcInstrInfo.td</tt>, the following
1048target description file entry, <tt>LDrr</tt>, defines the Load Integer
1049instruction for a Word (the <tt>LD</tt> SPARC opcode) from a memory address to a
1050register. The first parameter, the value 3 (<tt>11<sub>2</sub></tt>), is the
1051operation value for this category of operation. The second parameter
1052(<tt>000000<sub>2</sub></tt>) is the specific operation value
1053for <tt>LD</tt>/Load Word. The third parameter is the output destination, which
1054is a register operand and defined in the <tt>Register</tt> target description
1055file (<tt>IntRegs</tt>).
1056</p>
1057
1058<div class="doc_code">
1059<pre>def LDrr : F3_1 &lt;3, 0b000000, (outs IntRegs:$dst), (ins MEMrr:$addr),
1060                 "ld [$addr], $dst",
1061                 [(set IntRegs:$dst, (load ADDRrr:$addr))]&gt;;
1062</pre>
1063</div>
1064
1065<p>
1066The fourth parameter is the input source, which uses the address
1067operand <tt>MEMrr</tt> that is defined earlier in <tt>SparcInstrInfo.td</tt>:
1068</p>
1069
1070<div class="doc_code">
1071<pre>def MEMrr : Operand&lt;i32&gt; {
1072  let PrintMethod = "printMemOperand";
1073  let MIOperandInfo = (ops IntRegs, IntRegs);
1074}
1075</pre>
1076</div>
1077
1078<p>
1079The fifth parameter is a string that is used by the assembly printer and can be
1080left as an empty string until the assembly printer interface is implemented. The
1081sixth and final parameter is the pattern used to match the instruction during
1082the SelectionDAG Select Phase described in
1083(<a href="CodeGenerator.html">The LLVM
1084Target-Independent Code Generator</a>).  This parameter is detailed in the next
1085section, <a href="#InstructionSelector">Instruction Selector</a>.
1086</p>
1087
1088<p>
1089Instruction class definitions are not overloaded for different operand types, so
1090separate versions of instructions are needed for register, memory, or immediate
1091value operands. For example, to perform a Load Integer instruction for a Word
1092from an immediate operand to a register, the following instruction class is
1093defined:
1094</p>
1095
1096<div class="doc_code">
1097<pre>def LDri : F3_2 &lt;3, 0b000000, (outs IntRegs:$dst), (ins MEMri:$addr),
1098                 "ld [$addr], $dst",
1099                 [(set IntRegs:$dst, (load ADDRri:$addr))]&gt;;
1100</pre>
1101</div>
1102
1103<p>
1104Writing these definitions for so many similar instructions can involve a lot of
1105cut and paste. In td files, the <tt>multiclass</tt> directive enables the
1106creation of templates to define several instruction classes at once (using
1107the <tt>defm</tt> directive). For example in <tt>SparcInstrInfo.td</tt>, the
1108<tt>multiclass</tt> pattern <tt>F3_12</tt> is defined to create 2 instruction
1109classes each time <tt>F3_12</tt> is invoked:
1110</p>
1111
1112<div class="doc_code">
1113<pre>multiclass F3_12 &lt;string OpcStr, bits&lt;6&gt; Op3Val, SDNode OpNode&gt; {
1114  def rr  : F3_1 &lt;2, Op3Val, 
1115                 (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
1116                 !strconcat(OpcStr, " $b, $c, $dst"),
1117                 [(set IntRegs:$dst, (OpNode IntRegs:$b, IntRegs:$c))]&gt;;
1118  def ri  : F3_2 &lt;2, Op3Val,
1119                 (outs IntRegs:$dst), (ins IntRegs:$b, i32imm:$c),
1120                 !strconcat(OpcStr, " $b, $c, $dst"),
1121                 [(set IntRegs:$dst, (OpNode IntRegs:$b, simm13:$c))]&gt;;
1122}
1123</pre>
1124</div>
1125
1126<p>
1127So when the <tt>defm</tt> directive is used for the <tt>XOR</tt>
1128and <tt>ADD</tt> instructions, as seen below, it creates four instruction
1129objects: <tt>XORrr</tt>, <tt>XORri</tt>, <tt>ADDrr</tt>, and <tt>ADDri</tt>.
1130</p>
1131
1132<div class="doc_code">
1133<pre>
1134defm XOR   : F3_12&lt;"xor", 0b000011, xor&gt;;
1135defm ADD   : F3_12&lt;"add", 0b000000, add&gt;;
1136</pre>
1137</div>
1138
1139<p>
1140<tt>SparcInstrInfo.td</tt> also includes definitions for condition codes that
1141are referenced by branch instructions. The following definitions
1142in <tt>SparcInstrInfo.td</tt> indicate the bit location of the SPARC condition
1143code. For example, the 10<sup>th</sup> bit represents the 'greater than'
1144condition for integers, and the 22<sup>nd</sup> bit represents the 'greater
1145than' condition for floats.
1146</p>
1147
1148<div class="doc_code">
1149<pre>
1150def ICC_NE  : ICC_VAL&lt; 9&gt;;  // Not Equal
1151def ICC_E   : ICC_VAL&lt; 1&gt;;  // Equal
1152def ICC_G   : ICC_VAL&lt;10&gt;;  // Greater
1153...
1154def FCC_U   : FCC_VAL&lt;23&gt;;  // Unordered
1155def FCC_G   : FCC_VAL&lt;22&gt;;  // Greater
1156def FCC_UG  : FCC_VAL&lt;21&gt;;  // Unordered or Greater
1157...
1158</pre>
1159</div>
1160
1161<p>
1162(Note that <tt>Sparc.h</tt> also defines enums that correspond to the same SPARC
1163condition codes. Care must be taken to ensure the values in <tt>Sparc.h</tt>
1164correspond to the values in <tt>SparcInstrInfo.td</tt>. I.e.,
1165<tt>SPCC::ICC_NE = 9</tt>, <tt>SPCC::FCC_U = 23</tt> and so on.)
1166</p>
1167
1168<!-- ======================================================================= -->
1169<h3>
1170  <a name="operandMapping">Instruction Operand Mapping</a>
1171</h3>
1172
1173<div>
1174
1175<p>
1176The code generator backend maps instruction operands to fields in the
1177instruction.  Operands are assigned to unbound fields in the instruction in the
1178order they are defined. Fields are bound when they are assigned a value.  For
1179example, the Sparc target defines the <tt>XNORrr</tt> instruction as
1180a <tt>F3_1</tt> format instruction having three operands.
1181</p>
1182
1183<div class="doc_code">
1184<pre>
1185def XNORrr  : F3_1&lt;2, 0b000111,
1186                   (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
1187                   "xnor $b, $c, $dst",
1188                   [(set IntRegs:$dst, (not (xor IntRegs:$b, IntRegs:$c)))]&gt;;
1189</pre>
1190</div>
1191
1192<p>
1193The instruction templates in <tt>SparcInstrFormats.td</tt> show the base class
1194for <tt>F3_1</tt> is <tt>InstSP</tt>.
1195</p>
1196
1197<div class="doc_code">
1198<pre>
1199class InstSP&lt;dag outs, dag ins, string asmstr, list&lt;dag&gt; pattern&gt; : Instruction {
1200  field bits&lt;32&gt; Inst;
1201  let Namespace = "SP";
1202  bits&lt;2&gt; op;
1203  let Inst{31-30} = op;       
1204  dag OutOperandList = outs;
1205  dag InOperandList = ins;
1206  let AsmString   = asmstr;
1207  let Pattern = pattern;
1208}
1209</pre>
1210</div>
1211
1212<p><tt>InstSP</tt> leaves the <tt>op</tt> field unbound.</p>
1213
1214<div class="doc_code">
1215<pre>
1216class F3&lt;dag outs, dag ins, string asmstr, list&lt;dag&gt; pattern&gt;
1217    : InstSP&lt;outs, ins, asmstr, pattern&gt; {
1218  bits&lt;5&gt; rd;
1219  bits&lt;6&gt; op3;
1220  bits&lt;5&gt; rs1;
1221  let op{1} = 1;   // Op = 2 or 3
1222  let Inst{29-25} = rd;
1223  let Inst{24-19} = op3;
1224  let Inst{18-14} = rs1;
1225}
1226</pre>
1227</div>
1228
1229<p>
1230<tt>F3</tt> binds the <tt>op</tt> field and defines the <tt>rd</tt>,
1231<tt>op3</tt>, and <tt>rs1</tt> fields.  <tt>F3</tt> format instructions will
1232bind the operands <tt>rd</tt>, <tt>op3</tt>, and <tt>rs1</tt> fields.
1233</p>
1234
1235<div class="doc_code">
1236<pre>
1237class F3_1&lt;bits&lt;2&gt; opVal, bits&lt;6&gt; op3val, dag outs, dag ins,
1238           string asmstr, list&lt;dag&gt; pattern&gt; : F3&lt;outs, ins, asmstr, pattern&gt; {
1239  bits&lt;8&gt; asi = 0; // asi not currently used
1240  bits&lt;5&gt; rs2;
1241  let op         = opVal;
1242  let op3        = op3val;
1243  let Inst{13}   = 0;     // i field = 0
1244  let Inst{12-5} = asi;   // address space identifier
1245  let Inst{4-0}  = rs2;
1246}
1247</pre>
1248</div>
1249
1250<p>
1251<tt>F3_1</tt> binds the <tt>op3</tt> field and defines the <tt>rs2</tt>
1252fields.  <tt>F3_1</tt> format instructions will bind the operands to the <tt>rd</tt>,
1253<tt>rs1</tt>, and <tt>rs2</tt> fields. This results in the <tt>XNORrr</tt>
1254instruction binding <tt>$dst</tt>, <tt>$b</tt>, and <tt>$c</tt> operands to
1255the <tt>rd</tt>, <tt>rs1</tt>, and <tt>rs2</tt> fields respectively.
1256</p>
1257
1258</div>
1259
1260<!-- ======================================================================= -->
1261<h3>
1262  <a name="implementInstr">Implement a subclass of </a>
1263  <a href="CodeGenerator.html#targetinstrinfo">TargetInstrInfo</a>
1264</h3>
1265
1266<div>
1267
1268<p>
1269The final step is to hand code portions of <tt>XXXInstrInfo</tt>, which
1270implements the interface described in <tt>TargetInstrInfo.h</tt>. These
1271functions return <tt>0</tt> or a Boolean or they assert, unless
1272overridden. Here's a list of functions that are overridden for the SPARC
1273implementation in <tt>SparcInstrInfo.cpp</tt>:
1274</p>
1275
1276<ul>
1277<li><tt>isLoadFromStackSlot</tt> &mdash; If the specified machine instruction is
1278    a direct load from a stack slot, return the register number of the
1279    destination and the <tt>FrameIndex</tt> of the stack slot.</li>
1280
1281<li><tt>isStoreToStackSlot</tt> &mdash; If the specified machine instruction is
1282    a direct store to a stack slot, return the register number of the
1283    destination and the <tt>FrameIndex</tt> of the stack slot.</li>
1284
1285<li><tt>copyPhysReg</tt> &mdash; Copy values between a pair of physical
1286    registers.</li>
1287
1288<li><tt>storeRegToStackSlot</tt> &mdash; Store a register value to a stack
1289    slot.</li>
1290
1291<li><tt>loadRegFromStackSlot</tt> &mdash; Load a register value from a stack
1292    slot.</li>
1293
1294<li><tt>storeRegToAddr</tt> &mdash; Store a register value to memory.</li>
1295
1296<li><tt>loadRegFromAddr</tt> &mdash; Load a register value from memory.</li>
1297
1298<li><tt>foldMemoryOperand</tt> &mdash; Attempt to combine instructions of any
1299    load or store instruction for the specified operand(s).</li>
1300</ul>
1301
1302</div>
1303
1304<!-- ======================================================================= -->
1305<h3>
1306  <a name="branchFolding">Branch Folding and If Conversion</a>
1307</h3>
1308<div>
1309
1310<p>
1311Performance can be improved by combining instructions or by eliminating
1312instructions that are never reached. The <tt>AnalyzeBranch</tt> method
1313in <tt>XXXInstrInfo</tt> may be implemented to examine conditional instructions
1314and remove unnecessary instructions. <tt>AnalyzeBranch</tt> looks at the end of
1315a machine basic block (MBB) for opportunities for improvement, such as branch
1316folding and if conversion. The <tt>BranchFolder</tt> and <tt>IfConverter</tt>
1317machine function passes (see the source files <tt>BranchFolding.cpp</tt> and
1318<tt>IfConversion.cpp</tt> in the <tt>lib/CodeGen</tt> directory) call
1319<tt>AnalyzeBranch</tt> to improve the control flow graph that represents the
1320instructions.
1321</p>
1322
1323<p>
1324Several implementations of <tt>AnalyzeBranch</tt> (for ARM, Alpha, and X86) can
1325be examined as models for your own <tt>AnalyzeBranch</tt> implementation. Since
1326SPARC does not implement a useful <tt>AnalyzeBranch</tt>, the ARM target
1327implementation is shown below.
1328</p>
1329
1330<p><tt>AnalyzeBranch</tt> returns a Boolean value and takes four parameters:</p>
1331
1332<ul>
1333<li><tt>MachineBasicBlock &amp;MBB</tt> &mdash; The incoming block to be
1334    examined.</li>
1335
1336<li><tt>MachineBasicBlock *&amp;TBB</tt> &mdash; A destination block that is
1337    returned. For a conditional branch that evaluates to true, <tt>TBB</tt> is
1338    the destination.</li>
1339
1340<li><tt>MachineBasicBlock *&amp;FBB</tt> &mdash; For a conditional branch that
1341    evaluates to false, <tt>FBB</tt> is returned as the destination.</li>
1342
1343<li><tt>std::vector&lt;MachineOperand&gt; &amp;Cond</tt> &mdash; List of
1344    operands to evaluate a condition for a conditional branch.</li>
1345</ul>
1346
1347<p>
1348In the simplest case, if a block ends without a branch, then it falls through to
1349the successor block. No destination blocks are specified for either <tt>TBB</tt>
1350or <tt>FBB</tt>, so both parameters return <tt>NULL</tt>. The start of
1351the <tt>AnalyzeBranch</tt> (see code below for the ARM target) shows the
1352function parameters and the code for the simplest case.
1353</p>
1354
1355<div class="doc_code">
1356<pre>bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &amp;MBB,
1357        MachineBasicBlock *&amp;TBB, MachineBasicBlock *&amp;FBB,
1358        std::vector&lt;MachineOperand&gt; &amp;Cond) const
1359{
1360  MachineBasicBlock::iterator I = MBB.end();
1361  if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
1362    return false;
1363</pre>
1364</div>
1365
1366<p>
1367If a block ends with a single unconditional branch instruction, then
1368<tt>AnalyzeBranch</tt> (shown below) should return the destination of that
1369branch in the <tt>TBB</tt> parameter.
1370</p>
1371
1372<div class="doc_code">
1373<pre>
1374  if (LastOpc == ARM::B || LastOpc == ARM::tB) {
1375    TBB = LastInst-&gt;getOperand(0).getMBB();
1376    return false;
1377  }
1378</pre>
1379</div>
1380
1381<p>
1382If a block ends with two unconditional branches, then the second branch is never
1383reached. In that situation, as shown below, remove the last branch instruction
1384and return the penultimate branch in the <tt>TBB</tt> parameter.
1385</p>
1386
1387<div class="doc_code">
1388<pre>
1389  if ((SecondLastOpc == ARM::B || SecondLastOpc==ARM::tB) &amp;&amp;
1390      (LastOpc == ARM::B || LastOpc == ARM::tB)) {
1391    TBB = SecondLastInst-&gt;getOperand(0).getMBB();
1392    I = LastInst;
1393    I-&gt;eraseFromParent();
1394    return false;
1395  }
1396</pre>
1397</div>
1398
1399<p>
1400A block may end with a single conditional branch instruction that falls through
1401to successor block if the condition evaluates to false. In that case,
1402<tt>AnalyzeBranch</tt> (shown below) should return the destination of that
1403conditional branch in the <tt>TBB</tt> parameter and a list of operands in
1404the <tt>Cond</tt> parameter to evaluate the condition.
1405</p>
1406
1407<div class="doc_code">
1408<pre>
1409  if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
1410    // Block ends with fall-through condbranch.
1411    TBB = LastInst-&gt;getOperand(0).getMBB();
1412    Cond.push_back(LastInst-&gt;getOperand(1));
1413    Cond.push_back(LastInst-&gt;getOperand(2));
1414    return false;
1415  }
1416</pre>
1417</div>
1418
1419<p>
1420If a block ends with both a conditional branch and an ensuing unconditional
1421branch, then <tt>AnalyzeBranch</tt> (shown below) should return the conditional
1422branch destination (assuming it corresponds to a conditional evaluation of
1423'<tt>true</tt>') in the <tt>TBB</tt> parameter and the unconditional branch
1424destination in the <tt>FBB</tt> (corresponding to a conditional evaluation of
1425'<tt>false</tt>').  A list of operands to evaluate the condition should be
1426returned in the <tt>Cond</tt> parameter.
1427</p>
1428
1429<div class="doc_code">
1430<pre>
1431  unsigned SecondLastOpc = SecondLastInst-&gt;getOpcode();
1432
1433  if ((SecondLastOpc == ARM::Bcc &amp;&amp; LastOpc == ARM::B) ||
1434      (SecondLastOpc == ARM::tBcc &amp;&amp; LastOpc == ARM::tB)) {
1435    TBB =  SecondLastInst-&gt;getOperand(0).getMBB();
1436    Cond.push_back(SecondLastInst-&gt;getOperand(1));
1437    Cond.push_back(SecondLastInst-&gt;getOperand(2));
1438    FBB = LastInst-&gt;getOperand(0).getMBB();
1439    return false;
1440  }
1441</pre>
1442</div>
1443
1444<p>
1445For the last two cases (ending with a single conditional branch or ending with
1446one conditional and one unconditional branch), the operands returned in
1447the <tt>Cond</tt> parameter can be passed to methods of other instructions to
1448create new branches or perform other operations. An implementation
1449of <tt>AnalyzeBranch</tt> requires the helper methods <tt>RemoveBranch</tt>
1450and <tt>InsertBranch</tt> to manage subsequent operations.
1451</p>
1452
1453<p>
1454<tt>AnalyzeBranch</tt> should return false indicating success in most circumstances.
1455<tt>AnalyzeBranch</tt> should only return true when the method is stumped about what to
1456do, for example, if a block has three terminating branches. <tt>AnalyzeBranch</tt> may
1457return true if it encounters a terminator it cannot handle, such as an indirect
1458branch.
1459</p>
1460
1461</div>
1462
1463</div>
1464
1465<!-- *********************************************************************** -->
1466<h2>
1467  <a name="InstructionSelector">Instruction Selector</a>
1468</h2>
1469<!-- *********************************************************************** -->
1470
1471<div>
1472
1473<p>
1474LLVM uses a <tt>SelectionDAG</tt> to represent LLVM IR instructions, and nodes
1475of the <tt>SelectionDAG</tt> ideally represent native target
1476instructions. During code generation, instruction selection passes are performed
1477to convert non-native DAG instructions into native target-specific
1478instructions. The pass described in <tt>XXXISelDAGToDAG.cpp</tt> is used to
1479match patterns and perform DAG-to-DAG instruction selection. Optionally, a pass
1480may be defined (in <tt>XXXBranchSelector.cpp</tt>) to perform similar DAG-to-DAG
1481operations for branch instructions. Later, the code in
1482<tt>XXXISelLowering.cpp</tt> replaces or removes operations and data types not
1483supported natively (legalizes) in a <tt>SelectionDAG</tt>.
1484</p>
1485
1486<p>
1487TableGen generates code for instruction selection using the following target
1488description input files:
1489</p>
1490
1491<ul>
1492<li><tt>XXXInstrInfo.td</tt> &mdash; Contains definitions of instructions in a
1493    target-specific instruction set, generates <tt>XXXGenDAGISel.inc</tt>, which
1494    is included in <tt>XXXISelDAGToDAG.cpp</tt>.</li>
1495
1496<li><tt>XXXCallingConv.td</tt> &mdash; Contains the calling and return value
1497    conventions for the target architecture, and it generates
1498    <tt>XXXGenCallingConv.inc</tt>, which is included in
1499    <tt>XXXISelLowering.cpp</tt>.</li>
1500</ul>
1501
1502<p>
1503The implementation of an instruction selection pass must include a header that
1504declares the <tt>FunctionPass</tt> class or a subclass of <tt>FunctionPass</tt>. In
1505<tt>XXXTargetMachine.cpp</tt>, a Pass Manager (PM) should add each instruction
1506selection pass into the queue of passes to run.
1507</p>
1508
1509<p>
1510The LLVM static compiler (<tt>llc</tt>) is an excellent tool for visualizing the
1511contents of DAGs. To display the <tt>SelectionDAG</tt> before or after specific
1512processing phases, use the command line options for <tt>llc</tt>, described
1513at <a href="CodeGenerator.html#selectiondag_process">
1514SelectionDAG Instruction Selection Process</a>.
1515</p>
1516
1517<p>
1518To describe instruction selector behavior, you should add patterns for lowering
1519LLVM code into a <tt>SelectionDAG</tt> as the last parameter of the instruction
1520definitions in <tt>XXXInstrInfo.td</tt>. For example, in
1521<tt>SparcInstrInfo.td</tt>, this entry defines a register store operation, and
1522the last parameter describes a pattern with the store DAG operator.
1523</p>
1524
1525<div class="doc_code">
1526<pre>
1527def STrr  : F3_1&lt; 3, 0b000100, (outs), (ins MEMrr:$addr, IntRegs:$src),
1528                 "st $src, [$addr]", [(store IntRegs:$src, ADDRrr:$addr)]&gt;;
1529</pre>
1530</div>
1531
1532<p>
1533<tt>ADDRrr</tt> is a memory mode that is also defined in
1534<tt>SparcInstrInfo.td</tt>:
1535</p>
1536
1537<div class="doc_code">
1538<pre>
1539def ADDRrr : ComplexPattern&lt;i32, 2, "SelectADDRrr", [], []&gt;;
1540</pre>
1541</div>
1542
1543<p>
1544The definition of <tt>ADDRrr</tt> refers to <tt>SelectADDRrr</tt>, which is a
1545function defined in an implementation of the Instructor Selector (such
1546as <tt>SparcISelDAGToDAG.cpp</tt>).
1547</p>
1548
1549<p>
1550In <tt>lib/Target/TargetSelectionDAG.td</tt>, the DAG operator for store is
1551defined below:
1552</p>
1553
1554<div class="doc_code">
1555<pre>
1556def store : PatFrag&lt;(ops node:$val, node:$ptr),
1557                    (st node:$val, node:$ptr), [{
1558  if (StoreSDNode *ST = dyn_cast&lt;StoreSDNode&gt;(N))
1559    return !ST-&gt;isTruncatingStore() &amp;&amp; 
1560           ST-&gt;getAddressingMode() == ISD::UNINDEXED;
1561  return false;
1562}]&gt;;
1563</pre>
1564</div>
1565
1566<p>
1567<tt>XXXInstrInfo.td</tt> also generates (in <tt>XXXGenDAGISel.inc</tt>) the
1568<tt>SelectCode</tt> method that is used to call the appropriate processing
1569method for an instruction. In this example, <tt>SelectCode</tt>
1570calls <tt>Select_ISD_STORE</tt> for the <tt>ISD::STORE</tt> opcode.
1571</p>
1572
1573<div class="doc_code">
1574<pre>
1575SDNode *SelectCode(SDValue N) {
1576  ... 
1577  MVT::ValueType NVT = N.getNode()-&gt;getValueType(0);
1578  switch (N.getOpcode()) {
1579  case ISD::STORE: {
1580    switch (NVT) {
1581    default:
1582      return Select_ISD_STORE(N);
1583      break;
1584    }
1585    break;
1586  }
1587  ...
1588</pre>
1589</div>
1590
1591<p>
1592The pattern for <tt>STrr</tt> is matched, so elsewhere in
1593<tt>XXXGenDAGISel.inc</tt>, code for <tt>STrr</tt> is created for
1594<tt>Select_ISD_STORE</tt>. The <tt>Emit_22</tt> method is also generated
1595in <tt>XXXGenDAGISel.inc</tt> to complete the processing of this
1596instruction.
1597</p>
1598
1599<div class="doc_code">
1600<pre>
1601SDNode *Select_ISD_STORE(const SDValue &amp;N) {
1602  SDValue Chain = N.getOperand(0);
1603  if (Predicate_store(N.getNode())) {
1604    SDValue N1 = N.getOperand(1);
1605    SDValue N2 = N.getOperand(2);
1606    SDValue CPTmp0;
1607    SDValue CPTmp1;
1608
1609    // Pattern: (st:void IntRegs:i32:$src, 
1610    //           ADDRrr:i32:$addr)&lt;&lt;P:Predicate_store&gt;&gt;
1611    // Emits: (STrr:void ADDRrr:i32:$addr, IntRegs:i32:$src)
1612    // Pattern complexity = 13  cost = 1  size = 0
1613    if (SelectADDRrr(N, N2, CPTmp0, CPTmp1) &amp;&amp;
1614        N1.getNode()-&gt;getValueType(0) == MVT::i32 &amp;&amp;
1615        N2.getNode()-&gt;getValueType(0) == MVT::i32) {
1616      return Emit_22(N, SP::STrr, CPTmp0, CPTmp1);
1617    }
1618...
1619</pre>
1620</div>
1621
1622<!-- ======================================================================= -->
1623<h3>
1624  <a name="LegalizePhase">The SelectionDAG Legalize Phase</a>
1625</h3>
1626
1627<div>
1628
1629<p>
1630The Legalize phase converts a DAG to use types and operations that are natively
1631supported by the target. For natively unsupported types and operations, you need
1632to add code to the target-specific XXXTargetLowering implementation to convert
1633unsupported types and operations to supported ones.
1634</p>
1635
1636<p>
1637In the constructor for the <tt>XXXTargetLowering</tt> class, first use the
1638<tt>addRegisterClass</tt> method to specify which types are supports and which
1639register classes are associated with them. The code for the register classes are
1640generated by TableGen from <tt>XXXRegisterInfo.td</tt> and placed
1641in <tt>XXXGenRegisterInfo.h.inc</tt>. For example, the implementation of the
1642constructor for the SparcTargetLowering class (in
1643<tt>SparcISelLowering.cpp</tt>) starts with the following code:
1644</p>
1645
1646<div class="doc_code">
1647<pre>
1648addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
1649addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
1650addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass); 
1651</pre>
1652</div>
1653
1654<p>
1655You should examine the node types in the <tt>ISD</tt> namespace
1656(<tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>) and determine which
1657operations the target natively supports. For operations that do <b>not</b> have
1658native support, add a callback to the constructor for the XXXTargetLowering
1659class, so the instruction selection process knows what to do. The TargetLowering
1660class callback methods (declared in <tt>llvm/Target/TargetLowering.h</tt>) are:
1661</p>
1662
1663<ul>
1664<li><tt>setOperationAction</tt> &mdash; General operation.</li>
1665
1666<li><tt>setLoadExtAction</tt> &mdash; Load with extension.</li>
1667
1668<li><tt>setTruncStoreAction</tt> &mdash; Truncating store.</li>
1669
1670<li><tt>setIndexedLoadAction</tt> &mdash; Indexed load.</li>
1671
1672<li><tt>setIndexedStoreAction</tt> &mdash; Indexed store.</li>
1673
1674<li><tt>setConvertAction</tt> &mdash; Type conversion.</li>
1675
1676<li><tt>setCondCodeAction</tt> &mdash; Support for a given condition code.</li>
1677</ul>
1678
1679<p>
1680Note: on older releases, <tt>setLoadXAction</tt> is used instead
1681of <tt>setLoadExtAction</tt>.  Also, on older releases,
1682<tt>setCondCodeAction</tt> may not be supported. Examine your release
1683to see what methods are specifically supported.
1684</p>
1685
1686<p>
1687These callbacks are used to determine that an operation does or does not work
1688with a specified type (or types). And in all cases, the third parameter is
1689a <tt>LegalAction</tt> type enum value: <tt>Promote</tt>, <tt>Expand</tt>,
1690<tt>Custom</tt>, or <tt>Legal</tt>. <tt>SparcISelLowering.cpp</tt>
1691contains examples of all four <tt>LegalAction</tt> values.
1692</p>
1693
1694<!-- _______________________________________________________________________ -->
1695<h4>
1696  <a name="promote">Promote</a>
1697</h4>
1698
1699<div>
1700
1701<p>
1702For an operation without native support for a given type, the specified type may
1703be promoted to a larger type that is supported. For example, SPARC does not
1704support a sign-extending load for Boolean values (<tt>i1</tt> type), so
1705in <tt>SparcISelLowering.cpp</tt> the third parameter below, <tt>Promote</tt>,
1706changes <tt>i1</tt> type values to a large type before loading.
1707</p>
1708
1709<div class="doc_code">
1710<pre>
1711setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
1712</pre>
1713</div>
1714
1715</div>
1716
1717<!-- _______________________________________________________________________ -->
1718<h4>
1719  <a name="expand">Expand</a>
1720</h4>
1721
1722<div>
1723
1724<p>
1725For a type without native support, a value may need to be broken down further,
1726rather than promoted. For an operation without native support, a combination of
1727other operations may be used to similar effect. In SPARC, the floating-point
1728sine and cosine trig operations are supported by expansion to other operations,
1729as indicated by the third parameter, <tt>Expand</tt>, to
1730<tt>setOperationAction</tt>:
1731</p>
1732
1733<div class="doc_code">
1734<pre>
1735setOperationAction(ISD::FSIN, MVT::f32, Expand);
1736setOperationAction(ISD::FCOS, MVT::f32, Expand);
1737</pre>
1738</div>
1739
1740</div>
1741
1742<!-- _______________________________________________________________________ -->
1743<h4>
1744  <a name="custom">Custom</a>
1745</h4>
1746
1747<div>
1748
1749<p>
1750For some operations, simple type promotion or operation expansion may be
1751insufficient. In some cases, a special intrinsic function must be implemented.
1752</p>
1753
1754<p>
1755For example, a constant value may require special treatment, or an operation may
1756require spilling and restoring registers in the stack and working with register
1757allocators.
1758</p>
1759
1760<p>
1761As seen in <tt>SparcISelLowering.cpp</tt> code below, to perform a type
1762conversion from a floating point value to a signed integer, first the
1763<tt>setOperationAction</tt> should be called with <tt>Custom</tt> as the third
1764parameter:
1765</p>
1766
1767<div class="doc_code">
1768<pre>
1769setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1770</pre>
1771</div>    
1772
1773<p>
1774In the <tt>LowerOperation</tt> method, for each <tt>Custom</tt> operation, a
1775case statement should be added to indicate what function to call. In the
1776following code, an <tt>FP_TO_SINT</tt> opcode will call
1777the <tt>LowerFP_TO_SINT</tt> method:
1778</p>
1779
1780<div class="doc_code">
1781<pre>
1782SDValue SparcTargetLowering::LowerOperation(SDValue Op, SelectionDAG &amp;DAG) {
1783  switch (Op.getOpcode()) {
1784  case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
1785  ...
1786  }
1787}
1788</pre>
1789</div>
1790
1791<p>
1792Finally, the <tt>LowerFP_TO_SINT</tt> method is implemented, using an FP
1793register to convert the floating-point value to an integer.
1794</p>
1795
1796<div class="doc_code">
1797<pre>
1798static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &amp;DAG) {
1799  assert(Op.getValueType() == MVT::i32);
1800  Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
1801  return DAG.getNode(ISD::BITCAST, MVT::i32, Op);
1802}
1803</pre>
1804</div>    
1805
1806</div>
1807
1808<!-- _______________________________________________________________________ -->
1809<h4>
1810  <a name="legal">Legal</a>
1811</h4>
1812
1813<div>
1814
1815<p>
1816The <tt>Legal</tt> LegalizeAction enum value simply indicates that an
1817operation <b>is</b> natively supported. <tt>Legal</tt> represents the default
1818condition, so it is rarely used. In <tt>SparcISelLowering.cpp</tt>, the action
1819for <tt>CTPOP</tt> (an operation to count the bits set in an integer) is
1820natively supported only for SPARC v9. The following code enables
1821the <tt>Expand</tt> conversion technique for non-v9 SPARC implementations.
1822</p>
1823
1824<div class="doc_code">
1825<pre>
1826setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1827...
1828if (TM.getSubtarget&lt;SparcSubtarget&gt;().isV9())
1829  setOperationAction(ISD::CTPOP, MVT::i32, Legal);
1830  case ISD::SETULT: return SPCC::ICC_CS;
1831  case ISD::SETULE: return SPCC::ICC_LEU;
1832  case ISD::SETUGT: return SPCC::ICC_GU;
1833  case ISD::SETUGE: return SPCC::ICC_CC;
1834  }
1835}
1836</pre>
1837</div>
1838
1839</div>
1840
1841</div>
1842
1843<!-- ======================================================================= -->
1844<h3>
1845  <a name="callingConventions">Calling Conventions</a>
1846</h3>
1847
1848<div>
1849
1850<p>
1851To support target-specific calling conventions, <tt>XXXGenCallingConv.td</tt>
1852uses interfaces (such as CCIfType and CCAssignToReg) that are defined in
1853<tt>lib/Target/TargetCallingConv.td</tt>. TableGen can take the target
1854descriptor file <tt>XXXGenCallingConv.td</tt> and generate the header
1855file <tt>XXXGenCallingConv.inc</tt>, which is typically included
1856in <tt>XXXISelLowering.cpp</tt>. You can use the interfaces in
1857<tt>TargetCallingConv.td</tt> to specify:
1858</p>
1859
1860<ul>
1861<li>The order of parameter allocation.</li>
1862
1863<li>Where parameters and return values are placed (that is, on the stack or in
1864    registers).</li>
1865
1866<li>Which registers may be used.</li>
1867
1868<li>Whether the caller or callee unwinds the stack.</li>
1869</ul>
1870
1871<p>
1872The following example demonstrates the use of the <tt>CCIfType</tt> and
1873<tt>CCAssignToReg</tt> interfaces. If the <tt>CCIfType</tt> predicate is true
1874(that is, if the current argument is of type <tt>f32</tt> or <tt>f64</tt>), then
1875the action is performed. In this case, the <tt>CCAssignToReg</tt> action assigns
1876the argument value to the first available register: either <tt>R0</tt>
1877or <tt>R1</tt>.
1878</p>
1879
1880<div class="doc_code">
1881<pre>
1882CCIfType&lt;[f32,f64], CCAssignToReg&lt;[R0, R1]&gt;&gt;
1883</pre>
1884</div>
1885
1886<p>
1887<tt>SparcCallingConv.td</tt> contains definitions for a target-specific
1888return-value calling convention (RetCC_Sparc32) and a basic 32-bit C calling
1889convention (<tt>CC_Sparc32</tt>). The definition of <tt>RetCC_Sparc32</tt>
1890(shown below) indicates which registers are used for specified scalar return
1891types. A single-precision float is returned to register <tt>F0</tt>, and a
1892double-precision float goes to register <tt>D0</tt>. A 32-bit integer is
1893returned in register <tt>I0</tt> or <tt>I1</tt>.
1894</p>
1895
1896<div class="doc_code">
1897<pre>
1898def RetCC_Sparc32 : CallingConv&lt;[
1899  CCIfType&lt;[i32], CCAssignToReg&lt;[I0, I1]&gt;&gt;,
1900  CCIfType&lt;[f32], CCAssignToReg&lt;[F0]&gt;&gt;,
1901  CCIfType&lt;[f64], CCAssignToReg&lt;[D0]&gt;&gt;
1902]&gt;;
1903</pre>
1904</div>
1905
1906<p>
1907The definition of <tt>CC_Sparc32</tt> in <tt>SparcCallingConv.td</tt> introduces
1908<tt>CCAssignToStack</tt>, which assigns the value to a stack slot with the
1909specified size and alignment. In the example below, the first parameter, 4,
1910indicates the size of the slot, and the second parameter, also 4, indicates the
1911stack alignment along 4-byte units. (Special cases: if size is zero, then the
1912ABI size is used; if alignment is zero, then the ABI alignment is used.)
1913</p>
1914
1915<div class="doc_code">
1916<pre>
1917def CC_Sparc32 : CallingConv&lt;[
1918  // All arguments get passed in integer registers if there is space.
1919  CCIfType&lt;[i32, f32, f64], CCAssignToReg&lt;[I0, I1, I2, I3, I4, I5]&gt;&gt;,
1920  CCAssignToStack&lt;4, 4&gt;
1921]&gt;;
1922</pre>
1923</div>
1924
1925<p>
1926<tt>CCDelegateTo</tt> is another commonly used interface, which tries to find a
1927specified sub-calling convention, and, if a match is found, it is invoked. In
1928the following example (in <tt>X86CallingConv.td</tt>), the definition of
1929<tt>RetCC_X86_32_C</tt> ends with <tt>CCDelegateTo</tt>. After the current value
1930is assigned to the register <tt>ST0</tt> or <tt>ST1</tt>,
1931the <tt>RetCC_X86Common</tt> is invoked.
1932</p>
1933
1934<div class="doc_code">
1935<pre>
1936def RetCC_X86_32_C : CallingConv&lt;[
1937  CCIfType&lt;[f32], CCAssignToReg&lt;[ST0, ST1]&gt;&gt;,
1938  CCIfType&lt;[f64], CCAssignToReg&lt;[ST0, ST1]&gt;&gt;,
1939  CCDelegateTo&lt;RetCC_X86Common&gt;
1940]&gt;;
1941</pre>
1942</div>
1943
1944<p>
1945<tt>CCIfCC</tt> is an interface that attempts to match the given name to the
1946current calling convention. If the name identifies the current calling
1947convention, then a specified action is invoked. In the following example (in
1948<tt>X86CallingConv.td</tt>), if the <tt>Fast</tt> calling convention is in use,
1949then <tt>RetCC_X86_32_Fast</tt> is invoked. If the <tt>SSECall</tt> calling
1950convention is in use, then <tt>RetCC_X86_32_SSE</tt> is invoked.
1951</p>
1952
1953<div class="doc_code">
1954<pre>
1955def RetCC_X86_32 : CallingConv&lt;[
1956  CCIfCC&lt;"CallingConv::Fast", CCDelegateTo&lt;RetCC_X86_32_Fast&gt;&gt;,
1957  CCIfCC&lt;"CallingConv::X86_SSECall", CCDelegateTo&lt;RetCC_X86_32_SSE&gt;&gt;,
1958  CCDelegateTo&lt;RetCC_X86_32_C&gt;
1959]&gt;;
1960</pre>
1961</div>
1962
1963<p>Other calling convention interfaces include:</p>
1964
1965<ul>
1966<li><tt>CCIf &lt;predicate, action&gt;</tt> &mdash; If the predicate matches,
1967    apply the action.</li>
1968
1969<li><tt>CCIfInReg &lt;action&gt;</tt> &mdash; If the argument is marked with the
1970    '<tt>inreg</tt>' attribute, then apply the action.</li>
1971
1972<li><tt>CCIfNest &lt;action&gt;</tt> &mdash; Inf the argument is marked with the
1973    '<tt>nest</tt>' attribute, then apply the action.</li>
1974
1975<li><tt>CCIfNotVarArg &lt;action&gt;</tt> &mdash; If the current function does
1976    not take a variable number of arguments, apply the action.</li>
1977
1978<li><tt>CCAssignToRegWithShadow &lt;registerList, shadowList&gt;</tt> &mdash;
1979    similar to <tt>CCAssignToReg</tt>, but with a shadow list of registers.</li>
1980
1981<li><tt>CCPassByVal &lt;size, align&gt;</tt> &mdash; Assign value to a stack
1982    slot with the minimum specified size and alignment.</li>
1983
1984<li><tt>CCPromoteToType &lt;type&gt;</tt> &mdash; Promote the current value to
1985    the specified type.</li>
1986
1987<li><tt>CallingConv &lt;[actions]&gt;</tt> &mdash; Define each calling
1988    convention that is supported.</li>
1989</ul>
1990
1991</div>
1992
1993</div>
1994
1995<!-- *********************************************************************** -->
1996<h2>
1997  <a name="assemblyPrinter">Assembly Printer</a>
1998</h2>
1999<!-- *********************************************************************** -->
2000
2001<div>
2002
2003<p>
2004During the code emission stage, the code generator may utilize an LLVM pass to
2005produce assembly output. To do this, you want to implement the code for a
2006printer that converts LLVM IR to a GAS-format assembly language for your target
2007machine, using the following steps:
2008</p>
2009
2010<ul>
2011<li>Define all the assembly strings for your target, adding them to the
2012    instructions defined in the <tt>XXXInstrInfo.td</tt> file.
2013    (See <a href="#InstructionSet">Instruction Set</a>.)  TableGen will produce
2014    an output file (<tt>XXXGenAsmWriter.inc</tt>) with an implementation of
2015    the <tt>printInstruction</tt> method for the XXXAsmPrinter class.</li>
2016
2017<li>Write <tt>XXXTargetAsmInfo.h</tt>, which contains the bare-bones declaration
2018    of the <tt>XXXTargetAsmInfo</tt> class (a subclass
2019    of <tt>TargetAsmInfo</tt>).</li>
2020
2021<li>Write <tt>XXXTargetAsmInfo.cpp</tt>, which contains target-specific values
2022    for <tt>TargetAsmInfo</tt> properties and sometimes new implementations for
2023    methods.</li>
2024
2025<li>Write <tt>XXXAsmPrinter.cpp</tt>, which implements the <tt>AsmPrinter</tt>
2026    class that performs the LLVM-to-assembly conversion.</li>
2027</ul>
2028
2029<p>
2030The code in <tt>XXXTargetAsmInfo.h</tt> is usually a trivial declaration of the
2031<tt>XXXTargetAsmInfo</tt> class for use in <tt>XXXTargetAsmInfo.cpp</tt>.
2032Similarly, <tt>XXXTargetAsmInfo.cpp</tt> usually has a few declarations of
2033<tt>XXXTargetAsmInfo</tt> replacement values that override the default values
2034in <tt>TargetAsmInfo.cpp</tt>. For example in <tt>SparcTargetAsmInfo.cpp</tt>:
2035</p>
2036
2037<div class="doc_code">
2038<pre>
2039SparcTargetAsmInfo::SparcTargetAsmInfo(const SparcTargetMachine &amp;TM) {
2040  Data16bitsDirective = "\t.half\t";
2041  Data32bitsDirective = "\t.word\t";
2042  Data64bitsDirective = 0;  // .xword is only supported by V9.
2043  ZeroDirective = "\t.skip\t";
2044  CommentString = "!";
2045  ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
2046}
2047</pre>
2048</div>
2049
2050<p>
2051The X86 assembly printer implementation (<tt>X86TargetAsmInfo</tt>) is an
2052example where the target specific <tt>TargetAsmInfo</tt> class uses an 
2053overridden methods: <tt>ExpandInlineAsm</tt>.
2054</p>
2055
2056<p>
2057A target-specific implementation of AsmPrinter is written in
2058<tt>XXXAsmPrinter.cpp</tt>, which implements the <tt>AsmPrinter</tt> class that
2059converts the LLVM to printable assembly. The implementation must include the
2060following headers that have declarations for the <tt>AsmPrinter</tt> and
2061<tt>MachineFunctionPass</tt> classes. The <tt>MachineFunctionPass</tt> is a
2062subclass of <tt>FunctionPass</tt>.
2063</p>
2064
2065<div class="doc_code">
2066<pre>
2067#include "llvm/CodeGen/AsmPrinter.h"
2068#include "llvm/CodeGen/MachineFunctionPass.h" 
2069</pre>
2070</div>
2071
2072<p>
2073As a <tt>FunctionPass</tt>, <tt>AsmPrinter</tt> first
2074calls <tt>doInitialization</tt> to set up the <tt>AsmPrinter</tt>. In
2075<tt>SparcAsmPrinter</tt>, a <tt>Mangler</tt> object is instantiated to process
2076variable names.
2077</p>
2078
2079<p>
2080In <tt>XXXAsmPrinter.cpp</tt>, the <tt>runOnMachineFunction</tt> method
2081(declared in <tt>MachineFunctionPass</tt>) must be implemented
2082for <tt>XXXAsmPrinter</tt>. In <tt>MachineFunctionPass</tt>,
2083the <tt>runOnFunction</tt> method invokes <tt>runOnMachineFunction</tt>.
2084Target-specific implementations of <tt>runOnMachineFunction</tt> differ, but
2085generally do the following to process each machine function:
2086</p>
2087
2088<ul>
2089<li>Call <tt>SetupMachineFunction</tt> to perform initialization.</li>
2090
2091<li>Call <tt>EmitConstantPool</tt> to print out (to the output stream) constants
2092    which have been spilled to memory.</li>
2093
2094<li>Call <tt>EmitJumpTableInfo</tt> to print out jump tables used by the current
2095    function.</li>
2096
2097<li>Print out the label for the current function.</li>
2098
2099<li>Print out the code for the function, including basic block labels and the
2100    assembly for the instruction (using <tt>printInstruction</tt>)</li>
2101</ul>
2102
2103<p>
2104The <tt>XXXAsmPrinter</tt> implementation must also include the code generated
2105by TableGen that is output in the <tt>XXXGenAsmWriter.inc</tt> file. The code
2106in <tt>XXXGenAsmWriter.inc</tt> contains an implementation of the
2107<tt>printInstruction</tt> method that may call these methods:
2108</p>
2109
2110<ul>
2111<li><tt>printOperand</tt></li>
2112
2113<li><tt>printMemOperand</tt></li>
2114
2115<li><tt>printCCOperand (for conditional statements)</tt></li>
2116
2117<li><tt>printDataDirective</tt></li>
2118
2119<li><tt>printDeclare</tt></li>
2120
2121<li><tt>printImplicitDef</tt></li>
2122
2123<li><tt>printInlineAsm</tt></li>
2124</ul>
2125
2126<p>
2127The implementations of <tt>printDeclare</tt>, <tt>printImplicitDef</tt>,
2128<tt>printInlineAsm</tt>, and <tt>printLabel</tt> in <tt>AsmPrinter.cpp</tt> are
2129generally adequate for printing assembly and do not need to be
2130overridden.
2131</p>
2132
2133<p>
2134The <tt>printOperand</tt> method is implemented with a long switch/case
2135statement for the type of operand: register, immediate, basic block, external
2136symbol, global address, constant pool index, or jump table index. For an
2137instruction with a memory address operand, the <tt>printMemOperand</tt> method
2138should be implemented to generate the proper output. Similarly,
2139<tt>printCCOperand</tt> should be used to print a conditional operand.
2140</p>
2141
2142<p><tt>doFinalization</tt> should be overridden in <tt>XXXAsmPrinter</tt>, and
2143it should be called to shut down the assembly printer. During
2144<tt>doFinalization</tt>, global variables and constants are printed to
2145output.
2146</p>
2147
2148</div>
2149
2150<!-- *********************************************************************** -->
2151<h2>
2152  <a name="subtargetSupport">Subtarget Support</a>
2153</h2>
2154<!-- *********************************************************************** -->
2155
2156<div>
2157
2158<p>
2159Subtarget support is used to inform the code generation process of instruction
2160set variations for a given chip set.  For example, the LLVM SPARC implementation
2161provided covers three major versions of the SPARC microprocessor architecture:
2162Version 8 (V8, which is a 32-bit architecture), Version 9 (V9, a 64-bit
2163architecture), and the UltraSPARC architecture. V8 has 16 double-precision
2164floating-point registers that are also usable as either 32 single-precision or 8
2165quad-precision registers.  V8 is also purely big-endian. V9 has 32
2166double-precision floating-point registers that are also usable as 16
2167quad-precision registers, but cannot be used as single-precision registers. The
2168UltraSPARC architecture combines V9 with UltraSPARC Visual Instruction Set
2169extensions.
2170</p>
2171
2172<p>
2173If subtarget support is needed, you should implement a target-specific
2174XXXSubtarget class for your architecture. This class should process the
2175command-line options <tt>-mcpu=</tt> and <tt>-mattr=</tt>.
2176</p>
2177
2178<p>
2179TableGen uses definitions in the <tt>Target.td</tt> and <tt>Sparc.td</tt> files
2180to generate code in <tt>SparcGenSubtarget.inc</tt>. In <tt>Target.td</tt>, shown
2181below, the <tt>SubtargetFeature</tt> interface is defined. The first 4 string
2182parameters of the <tt>SubtargetFeature</tt> interface are a feature name, an
2183attribute set by the feature, the value of the attribute, and a description of
2184the feature. (The fifth parameter is a list of features whose presence is
2185implied, and its default value is an empty array.)
2186</p>
2187
2188<div class="doc_code">
2189<pre>
2190class SubtargetFeature&lt;string n, string a,  string v, string d,
2191                       list&lt;SubtargetFeature&gt; i = []&gt; {
2192  string Name = n;
2193  string Attribute = a;
2194  string Value = v;
2195  string Desc = d;
2196  list&lt;SubtargetFeature&gt; Implies = i;
2197}
2198</pre>
2199</div>
2200
2201<p>
2202In the <tt>Sparc.td</tt> file, the SubtargetFeature is used to define the
2203following features.
2204</p>
2205
2206<div class="doc_code">
2207<pre>
2208def FeatureV9 : SubtargetFeature&lt;"v9", "IsV9", "true",
2209                     "Enable SPARC-V9 instructions"&gt;;
2210def FeatureV8Deprecated : SubtargetFeature&lt;"deprecated-v8", 
2211                     "V8DeprecatedInsts", "true",
2212                     "Enable deprecated V8 instructions in V9 mode"&gt;;
2213def FeatureVIS : SubtargetFeature&lt;"vis", "IsVIS", "true",
2214                     "Enable UltraSPARC Visual Instruction Set extensions"&gt;;
2215</pre>
2216</div>
2217
2218<p>
2219Elsewhere in <tt>Sparc.td</tt>, the Proc class is defined and then is used to
2220define particular SPARC processor subtypes that may have the previously
2221described features.
2222</p>
2223
2224<div class="doc_code">
2225<pre>
2226class Proc&lt;string Name, list&lt;SubtargetFeature&gt; Features&gt;
2227  : Processor&lt;Name, NoItineraries, Features&gt;;
2228&nbsp;
2229def : Proc&lt;"generic",         []&gt;;
2230def : Proc&lt;"v8",              []&gt;;
2231def : Proc&lt;"supersparc",      []&gt;;
2232def : Proc&lt;"sparclite",       []&gt;;
2233def : Proc&lt;"f934",            []&gt;;
2234def : Proc&lt;"hypersparc",      []&gt;;
2235def : Proc&lt;"sparclite86x",    []&gt;;
2236def : Proc&lt;"sparclet",        []&gt;;
2237def : Proc&lt;"tsc701",          []&gt;;
2238def : Proc&lt;"v9",              [FeatureV9]&gt;;
2239def : Proc&lt;"ultrasparc",      [FeatureV9, FeatureV8Deprecated]&gt;;
2240def : Proc&lt;"ultrasparc3",     [FeatureV9, FeatureV8Deprecated]&gt;;
2241def : Proc&lt;"ultrasparc3-vis", [FeatureV9, FeatureV8Deprecated, FeatureVIS]&gt;;
2242</pre>
2243</div>
2244
2245<p>
2246From <tt>Target.td</tt> and <tt>Sparc.td</tt> files, the resulting
2247SparcGenSubtarget.inc specifies enum values to identify the features, arrays of
2248constants to represent the CPU features and CPU subtypes, and the
2249ParseSubtargetFeatures method that parses the features string that sets
2250specified subtarget options. The generated <tt>SparcGenSubtarget.inc</tt> file
2251should be included in the <tt>SparcSubtarget.cpp</tt>. The target-specific
2252implementation of the XXXSubtarget method should follow this pseudocode:
2253</p>
2254
2255<div class="doc_code">
2256<pre>
2257XXXSubtarget::XXXSubtarget(const Module &amp;M, const std::string &amp;FS) {
2258  // Set the default features
2259  // Determine default and user specified characteristics of the CPU
2260  // Call ParseSubtargetFeatures(FS, CPU) to parse the features string
2261  // Perform any additional operations
2262}
2263</pre>
2264</div>
2265
2266</div>
2267
2268<!-- *********************************************************************** -->
2269<h2>
2270  <a name="jitSupport">JIT Support</a>
2271</h2>
2272<!-- *********************************************************************** -->
2273
2274<div>
2275
2276<p>
2277The implementation of a target machine optionally includes a Just-In-Time (JIT)
2278code generator that emits machine code and auxiliary structures as binary output
2279that can be written directly to memory.  To do this, implement JIT code
2280generation by performing the following steps:
2281</p>
2282
2283<ul>
2284<li>Write an <tt>XXXCodeEmitter.cpp</tt> file that contains a machine function
2285    pass that transforms target-machine instructions into relocatable machine
2286    code.</li>
2287
2288<li>Write an <tt>XXXJITInfo.cpp</tt> file that implements the JIT interfaces for
2289    target-specific code-generation activities, such as emitting machine code
2290    and stubs.</li>
2291
2292<li>Modify <tt>XXXTargetMachine</tt> so that it provides a
2293    <tt>TargetJITInfo</tt> object through its <tt>getJITInfo</tt> method.</li>
2294</ul>
2295
2296<p>
2297There are several different approaches to writing the JIT support code. For
2298instance, TableGen and target descriptor files may be used for creating a JIT
2299code generator, but are not mandatory. For the Alpha and PowerPC target
2300machines, TableGen is used to generate <tt>XXXGenCodeEmitter.inc</tt>, which
2301contains the binary coding of machine instructions and the
2302<tt>getBinaryCodeForInstr</tt> method to access those codes. Other JIT
2303implementations do not.
2304</p>
2305
2306<p>
2307Both <tt>XXXJITInfo.cpp</tt> and <tt>XXXCodeEmitter.cpp</tt> must include the
2308<tt>llvm/CodeGen/MachineCodeEmitter.h</tt> header file that defines the
2309<tt>MachineCodeEmitter</tt> class containing code for several callback functions
2310that write data (in bytes, words, strings, etc.) to the output stream.
2311</p>
2312
2313<!-- ======================================================================= -->
2314<h3>
2315  <a name="mce">Machine Code Emitter</a>
2316</h3>
2317
2318<div>
2319
2320<p>
2321In <tt>XXXCodeEmitter.cpp</tt>, a target-specific of the <tt>Emitter</tt> class
2322is implemented as a function pass (subclass
2323of <tt>MachineFunctionPass</tt>). The target-specific implementation
2324of <tt>runOnMachineFunction</tt> (invoked by
2325<tt>runOnFunction</tt> in <tt>MachineFunctionPass</tt>) iterates through the
2326<tt>MachineBasicBlock</tt> calls <tt>emitInstruction</tt> to process each
2327instruction and emit binary code. <tt>emitInstruction</tt> is largely
2328implemented with case statements on the instruction types defined in
2329<tt>XXXInstrInfo.h</tt>. For example, in <tt>X86CodeEmitter.cpp</tt>,
2330the <tt>emitInstruction</tt> method is built around the following switch/case
2331statements:
2332</p>
2333
2334<div class="doc_code">
2335<pre>
2336switch (Desc-&gt;TSFlags &amp; X86::FormMask) {
2337case X86II::Pseudo:  // for not yet implemented instructions 
2338   ...               // or pseudo-instructions
2339   break;
2340case X86II::RawFrm:  // for instructions with a fixed opcode value
2341   ...
2342   break;
2343case X86II::AddRegFrm: // for instructions that have one register operand 
2344   ...                 // added to their opcode
2345   break;
2346case X86II::MRMDestReg:// for instructions that use the Mod/RM byte
2347   ...                 // to specify a destination (register)
2348   break;
2349case X86II::MRMDestMem:// for instructions that use the Mod/RM byte
2350   ...                 // to specify a destination (memory)
2351   break;
2352case X86II::MRMSrcReg: // for instructions that use the Mod/RM byte
2353   ...                 // to specify a source (register)
2354   break;
2355case X86II::MRMSrcMem: // for instructions that use the Mod/RM byte
2356   ...                 // to specify a source (memory)
2357   break;
2358case X86II::MRM0r: case X86II::MRM1r:  // for instructions that operate on 
2359case X86II::MRM2r: case X86II::MRM3r:  // a REGISTER r/m operand and
2360case X86II::MRM4r: case X86II::MRM5r:  // use the Mod/RM byte and a field
2361case X86II::MRM6r: case X86II::MRM7r:  // to hold extended opcode data
2362   ...  
2363   break;
2364case X86II::MRM0m: case X86II::MRM1m:  // for instructions that operate on
2365case X86II::MRM2m: case X86II::MRM3m:  // a MEMORY r/m operand and
2366case X86II::MRM4m: case X86II::MRM5m:  // use the Mod/RM byte and a field
2367case X86II::MRM6m: case X86II::MRM7m:  // to hold extended opcode data
2368   ...  
2369   break;
2370case X86II::MRMInitReg: // for instructions whose source and
2371   ...                  // destination are the same register
2372   break;
2373}
2374</pre>
2375</div>
2376
2377<p>
2378The implementations of these case statements often first emit the opcode and
2379then get the operand(s). Then depending upon the operand, helper methods may be
2380called to process the operand(s). For example, in <tt>X86CodeEmitter.cpp</tt>,
2381for the <tt>X86II::AddRegFrm</tt> case, the first data emitted
2382(by <tt>emitByte</tt>) is the opcode added to the register operand. Then an
2383object representing the machine operand, <tt>MO1</tt>, is extracted. The helper
2384methods such as <tt>isImmediate</tt>,
2385<tt>isGlobalAddress</tt>, <tt>isExternalSymbol</tt>, <tt>isConstantPoolIndex</tt>, and 
2386<tt>isJumpTableIndex</tt> determine the operand
2387type. (<tt>X86CodeEmitter.cpp</tt> also has private methods such
2388as <tt>emitConstant</tt>, <tt>emitGlobalAddress</tt>,
2389<tt>emitExternalSymbolAddress</tt>, <tt>emitConstPoolAddress</tt>,
2390and <tt>emitJumpTableAddress</tt> that emit the data into the output stream.)
2391</p>
2392
2393<div class="doc_code">
2394<pre>
2395case X86II::AddRegFrm:
2396  MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
2397  
2398  if (CurOp != NumOps) {
2399    const MachineOperand &amp;MO1 = MI.getOperand(CurOp++);
2400    unsigned Size = X86InstrInfo::sizeOfImm(Desc);
2401    if (MO1.isImmediate())
2402      emitConstant(MO1.getImm(), Size);
2403    else {
2404      unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
2405        : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
2406      if (Opcode == X86::MOV64ri) 
2407        rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
2408      if (MO1.isGlobalAddress()) {
2409        bool NeedStub = isa&lt;Function&gt;(MO1.getGlobal());
2410        bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());
2411        emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
2412                          NeedStub, isLazy);
2413      } else if (MO1.isExternalSymbol())
2414        emitExternalSymbolAddress(MO1.getSymbolName(), rt);
2415      else if (MO1.isConstantPoolIndex())
2416        emitConstPoolAddress(MO1.getIndex(), rt);
2417      else if (MO1.isJumpTableIndex())
2418        emitJumpTableAddress(MO1.getIndex(), rt);
2419    }
2420  }
2421  break;
2422</pre>
2423</div>
2424
2425<p>
2426In the previous example, <tt>XXXCodeEmitter.cpp</tt> uses the
2427variable <tt>rt</tt>, which is a RelocationType enum that may be used to
2428relocate addresses (for example, a global address with a PIC base offset). The
2429<tt>RelocationType</tt> enum for that target is defined in the short
2430target-specific <tt>XXXRelocations.h</tt> file. The <tt>RelocationType</tt> is used by
2431the <tt>relocate</tt> method defined in <tt>XXXJITInfo.cpp</tt> to rewrite
2432addresses for referenced global symbols.
2433</p>
2434
2435<p>
2436For example, <tt>X86Relocations.h</tt> specifies the following relocation types
2437for the X86 addresses. In all four cases, the relocated value is added to the
2438value already in memory. For <tt>reloc_pcrel_word</tt>
2439and <tt>reloc_picrel_word</tt>, there is an additional initial adjustment.
2440</p>
2441
2442<div class="doc_code">
2443<pre>
2444enum RelocationType {
2445  reloc_pcrel_word = 0,    // add reloc value after adjusting for the PC loc
2446  reloc_picrel_word = 1,   // add reloc value after adjusting for the PIC base
2447  reloc_absolute_word = 2, // absolute relocation; no additional adjustment 
2448  reloc_absolute_dword = 3 // absolute relocation; no additional adjustment
2449};
2450</pre>
2451</div>
2452
2453</div>
2454
2455<!-- ======================================================================= -->
2456<h3>
2457  <a name="targetJITInfo">Target JIT Info</a>
2458</h3>
2459
2460<div>
2461
2462<p>
2463<tt>XXXJITInfo.cpp</tt> implements the JIT interfaces for target-specific
2464code-generation activities, such as emitting machine code and stubs. At minimum,
2465a target-specific version of <tt>XXXJITInfo</tt> implements the following:
2466</p>
2467
2468<ul>
2469<li><tt>getLazyResolverFunction</tt> &mdash; Initializes the JIT, gives the
2470    target a function that is used for compilation.</li>
2471
2472<li><tt>emitFunctionStub</tt> &mdash; Returns a native function with a specified
2473    address for a callback function.</li>
2474
2475<li><tt>relocate</tt> &mdash; Changes the addresses of referenced globals, based
2476    on relocation types.</li>
2477
2478<li>Callback function that are wrappers to a function stub that is used when the
2479    real target is not initially known.</li>
2480</ul>
2481
2482<p>
2483<tt>getLazyResolverFunction</tt> is generally trivial to implement. It makes the
2484incoming parameter as the global <tt>JITCompilerFunction</tt> and returns the
2485callback function that will be used a function wrapper. For the Alpha target
2486(in <tt>AlphaJITInfo.cpp</tt>), the <tt>getLazyResolverFunction</tt>
2487implementation is simply:
2488</p>
2489
2490<div class="doc_code">
2491<pre>
2492TargetJITInfo::LazyResolverFn AlphaJITInfo::getLazyResolverFunction(  
2493                                            JITCompilerFn F) {
2494  JITCompilerFunction = F;
2495  return AlphaCompilationCallback;
2496}
2497</pre>
2498</div>
2499
2500<p>
2501For the X86 target, the <tt>getLazyResolverFunction</tt> implementation is a
2502little more complication, because it returns a different callback function for
2503processors with SSE instructions and XMM registers.
2504</p>
2505
2506<p>
2507The callback function initially saves and later restores the callee register
2508values, incoming arguments, and frame and return address. The callback function
2509needs low-level access to the registers or stack, so it is typically implemented
2510with assembler.
2511</p>
2512
2513</div>
2514
2515</div>
2516
2517<!-- *********************************************************************** -->
2518
2519<hr>
2520<address>
2521  <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
2522  src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
2523  <a href="http://validator.w3.org/check/referer"><img
2524  src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
2525
2526  <a href="http://www.woo.com">Mason Woo</a> and <a href="http://misha.brukman.net">Misha Brukman</a><br>
2527  <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a>
2528  <br>
2529  Last modified: $Date$
2530</address>
2531
2532</body>
2533</html>
2534