1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
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">
13 Writing an LLVM Compiler Backend
17 <li><a href="#intro">Introduction</a>
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>
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>
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>
32 <li><a href="#InstructionSet">Instruction Set</a>
34 <li><a href="#operandMapping">Instruction Operand Mapping</a></li>
35 <li><a href="#relationMapping">Instruction Relation Mapping</a></li>
36 <li><a href="#implementInstr">Implement a subclass of TargetInstrInfo</a></li>
37 <li><a href="#branchFolding">Branch Folding and If Conversion</a></li>
39 <li><a href="#InstructionSelector">Instruction Selector</a>
41 <li><a href="#LegalizePhase">The SelectionDAG Legalize Phase</a>
43 <li><a href="#promote">Promote</a></li>
44 <li><a href="#expand">Expand</a></li>
45 <li><a href="#custom">Custom</a></li>
46 <li><a href="#legal">Legal</a></li>
48 <li><a href="#callingConventions">Calling Conventions</a></li>
50 <li><a href="#assemblyPrinter">Assembly Printer</a></li>
51 <li><a href="#subtargetSupport">Subtarget Support</a></li>
52 <li><a href="#jitSupport">JIT Support</a>
54 <li><a href="#mce">Machine Code Emitter</a></li>
55 <li><a href="#targetJITInfo">Target JIT Info</a></li>
59 <div class="doc_author">
60 <p>Written by <a href="http://www.woo.com">Mason Woo</a> and
61 <a href="http://misha.brukman.net">Misha Brukman</a></p>
64 <!-- *********************************************************************** -->
66 <a name="intro">Introduction</a>
68 <!-- *********************************************************************** -->
73 This document describes techniques for writing compiler backends that convert
74 the LLVM Intermediate Representation (IR) to code for a specified machine or
75 other languages. Code intended for a specific machine can take the form of
76 either assembly code or binary code (usable for a JIT compiler).
80 The backend of LLVM features a target-independent code generator that may create
81 output for several types of target CPUs — including X86, PowerPC, ARM,
82 and SPARC. The backend may also be used to generate code targeted at SPUs of the
83 Cell processor or GPUs to support the execution of compute kernels.
87 The document focuses on existing examples found in subdirectories
88 of <tt>llvm/lib/Target</tt> in a downloaded LLVM release. In particular, this
89 document focuses on the example of creating a static compiler (one that emits
90 text assembly) for a SPARC target, because SPARC has fairly standard
91 characteristics, such as a RISC instruction set and straightforward calling
96 <a name="Audience">Audience</a>
102 The audience for this document is anyone who needs to write an LLVM backend to
103 generate code for a specific hardware or software target.
109 <a name="Prerequisite">Prerequisite Reading</a>
115 These essential documents must be read before reading this document:
119 <li><i><a href="LangRef.html">LLVM Language Reference
120 Manual</a></i> — a reference manual for the LLVM assembly language.</li>
122 <li><i><a href="CodeGenerator.html">The LLVM
123 Target-Independent Code Generator</a></i> — a guide to the components
124 (classes and code generation algorithms) for translating the LLVM internal
125 representation into machine code for a specified target. Pay particular
126 attention to the descriptions of code generation stages: Instruction
127 Selection, Scheduling and Formation, SSA-based Optimization, Register
128 Allocation, Prolog/Epilog Code Insertion, Late Machine Code Optimizations,
129 and Code Emission.</li>
131 <li><i><a href="TableGenFundamentals.html">TableGen
132 Fundamentals</a></i> —a document that describes the TableGen
133 (<tt>tblgen</tt>) application that manages domain-specific information to
134 support LLVM code generation. TableGen processes input from a target
135 description file (<tt>.td</tt> suffix) and generates C++ code that can be
136 used for code generation.</li>
138 <li><i><a href="WritingAnLLVMPass.html">Writing an LLVM
139 Pass</a></i> — The assembly printer is a <tt>FunctionPass</tt>, as are
140 several SelectionDAG processing steps.</li>
144 To follow the SPARC examples in this document, have a copy of
145 <i><a href="http://www.sparc.org/standards/V8.pdf">The SPARC Architecture
146 Manual, Version 8</a></i> for reference. For details about the ARM instruction
147 set, refer to the <i><a href="http://infocenter.arm.com/">ARM Architecture
148 Reference Manual</a></i>. For more about the GNU Assembler format
150 <i><a href="http://sourceware.org/binutils/docs/as/index.html">Using As</a></i>,
151 especially for the assembly printer. <i>Using As</i> contains a list of target
152 machine dependent features.
158 <a name="Basic">Basic Steps</a>
164 To write a compiler backend for LLVM that converts the LLVM IR to code for a
165 specified target (machine or other language), follow these steps:
169 <li>Create a subclass of the TargetMachine class that describes characteristics
170 of your target machine. Copy existing examples of specific TargetMachine
171 class and header files; for example, start with
172 <tt>SparcTargetMachine.cpp</tt> and <tt>SparcTargetMachine.h</tt>, but
173 change the file names for your target. Similarly, change code that
174 references "Sparc" to reference your target. </li>
176 <li>Describe the register set of the target. Use TableGen to generate code for
177 register definition, register aliases, and register classes from a
178 target-specific <tt>RegisterInfo.td</tt> input file. You should also write
179 additional code for a subclass of the TargetRegisterInfo class that
180 represents the class register file data used for register allocation and
181 also describes the interactions between registers.</li>
183 <li>Describe the instruction set of the target. Use TableGen to generate code
184 for target-specific instructions from target-specific versions of
185 <tt>TargetInstrFormats.td</tt> and <tt>TargetInstrInfo.td</tt>. You should
186 write additional code for a subclass of the TargetInstrInfo class to
187 represent machine instructions supported by the target machine. </li>
189 <li>Describe the selection and conversion of the LLVM IR from a Directed Acyclic
190 Graph (DAG) representation of instructions to native target-specific
191 instructions. Use TableGen to generate code that matches patterns and
192 selects instructions based on additional information in a target-specific
193 version of <tt>TargetInstrInfo.td</tt>. Write code
194 for <tt>XXXISelDAGToDAG.cpp</tt>, where XXX identifies the specific target,
195 to perform pattern matching and DAG-to-DAG instruction selection. Also write
196 code in <tt>XXXISelLowering.cpp</tt> to replace or remove operations and
197 data types that are not supported natively in a SelectionDAG. </li>
199 <li>Write code for an assembly printer that converts LLVM IR to a GAS format for
200 your target machine. You should add assembly strings to the instructions
201 defined in your target-specific version of <tt>TargetInstrInfo.td</tt>. You
202 should also write code for a subclass of AsmPrinter that performs the
203 LLVM-to-assembly conversion and a trivial subclass of TargetAsmInfo.</li>
205 <li>Optionally, add support for subtargets (i.e., variants with different
206 capabilities). You should also write code for a subclass of the
207 TargetSubtarget class, which allows you to use the <tt>-mcpu=</tt>
208 and <tt>-mattr=</tt> command-line options.</li>
210 <li>Optionally, add JIT support and create a machine code emitter (subclass of
211 TargetJITInfo) that is used to emit binary code directly into memory. </li>
215 In the <tt>.cpp</tt> and <tt>.h</tt>. files, initially stub up these methods and
216 then implement them later. Initially, you may not know which private members
217 that the class will need and which components will need to be subclassed.
223 <a name="Preliminaries">Preliminaries</a>
229 To actually create your compiler backend, you need to create and modify a few
230 files. The absolute minimum is discussed here. But to actually use the LLVM
231 target-independent code generator, you must perform the steps described in
232 the <a href="CodeGenerator.html">LLVM
233 Target-Independent Code Generator</a> document.
237 First, you should create a subdirectory under <tt>lib/Target</tt> to hold all
238 the files related to your target. If your target is called "Dummy," create the
239 directory <tt>lib/Target/Dummy</tt>.
244 directory, create a <tt>Makefile</tt>. It is easiest to copy a
245 <tt>Makefile</tt> of another target and modify it. It should at least contain
246 the <tt>LEVEL</tt>, <tt>LIBRARYNAME</tt> and <tt>TARGET</tt> variables, and then
247 include <tt>$(LEVEL)/Makefile.common</tt>. The library can be
248 named <tt>LLVMDummy</tt> (for example, see the MIPS target). Alternatively, you
249 can split the library into <tt>LLVMDummyCodeGen</tt>
250 and <tt>LLVMDummyAsmPrinter</tt>, the latter of which should be implemented in a
251 subdirectory below <tt>lib/Target/Dummy</tt> (for example, see the PowerPC
256 Note that these two naming schemes are hardcoded into <tt>llvm-config</tt>.
257 Using any other naming scheme will confuse <tt>llvm-config</tt> and produce a
258 lot of (seemingly unrelated) linker errors when linking <tt>llc</tt>.
262 To make your target actually do something, you need to implement a subclass of
263 <tt>TargetMachine</tt>. This implementation should typically be in the file
264 <tt>lib/Target/DummyTargetMachine.cpp</tt>, but any file in
265 the <tt>lib/Target</tt> directory will be built and should work. To use LLVM's
266 target independent code generator, you should do what all current machine
267 backends do: create a subclass of <tt>LLVMTargetMachine</tt>. (To create a
268 target from scratch, create a subclass of <tt>TargetMachine</tt>.)
272 To get LLVM to actually build and link your target, you need to add it to
273 the <tt>TARGETS_TO_BUILD</tt> variable. To do this, you modify the configure
274 script to know about your target when parsing the <tt>--enable-targets</tt>
275 option. Search the configure script for <tt>TARGETS_TO_BUILD</tt>, add your
276 target to the lists there (some creativity required), and then
277 reconfigure. Alternatively, you can change <tt>autotools/configure.ac</tt> and
278 regenerate configure by running <tt>./autoconf/AutoRegen.sh</tt>.
285 <!-- *********************************************************************** -->
287 <a name="TargetMachine">Target Machine</a>
289 <!-- *********************************************************************** -->
294 <tt>LLVMTargetMachine</tt> is designed as a base class for targets implemented
295 with the LLVM target-independent code generator. The <tt>LLVMTargetMachine</tt>
296 class should be specialized by a concrete target class that implements the
297 various virtual methods. <tt>LLVMTargetMachine</tt> is defined as a subclass of
298 <tt>TargetMachine</tt> in <tt>include/llvm/Target/TargetMachine.h</tt>. The
299 <tt>TargetMachine</tt> class implementation (<tt>TargetMachine.cpp</tt>) also
300 processes numerous command-line options.
304 To create a concrete target-specific subclass of <tt>LLVMTargetMachine</tt>,
305 start by copying an existing <tt>TargetMachine</tt> class and header. You
306 should name the files that you create to reflect your specific target. For
307 instance, for the SPARC target, name the files <tt>SparcTargetMachine.h</tt> and
308 <tt>SparcTargetMachine.cpp</tt>.
312 For a target machine <tt>XXX</tt>, the implementation of
313 <tt>XXXTargetMachine</tt> must have access methods to obtain objects that
314 represent target components. These methods are named <tt>get*Info</tt>, and are
315 intended to obtain the instruction set (<tt>getInstrInfo</tt>), register set
316 (<tt>getRegisterInfo</tt>), stack frame layout (<tt>getFrameInfo</tt>), and
317 similar information. <tt>XXXTargetMachine</tt> must also implement the
318 <tt>getDataLayout</tt> method to access an object with target-specific data
319 characteristics, such as data type size and alignment requirements.
323 For instance, for the SPARC target, the header file
324 <tt>SparcTargetMachine.h</tt> declares prototypes for several <tt>get*Info</tt>
325 and <tt>getDataLayout</tt> methods that simply return a class member.
328 <div class="doc_code">
334 class SparcTargetMachine : public LLVMTargetMachine {
335 const DataLayout DataLayout; // Calculates type size & alignment
336 SparcSubtarget Subtarget;
337 SparcInstrInfo InstrInfo;
338 TargetFrameInfo FrameInfo;
341 virtual const TargetAsmInfo *createTargetAsmInfo() const;
344 SparcTargetMachine(const Module &M, const std::string &FS);
346 virtual const SparcInstrInfo *getInstrInfo() const {return &InstrInfo; }
347 virtual const TargetFrameInfo *getFrameInfo() const {return &FrameInfo; }
348 virtual const TargetSubtarget *getSubtargetImpl() const{return &Subtarget; }
349 virtual const TargetRegisterInfo *getRegisterInfo() const {
350 return &InstrInfo.getRegisterInfo();
352 virtual const DataLayout *getDataLayout() const { return &DataLayout; }
353 static unsigned getModuleMatchQuality(const Module &M);
355 // Pass Pipeline Configuration
356 virtual bool addInstSelector(PassManagerBase &PM, bool Fast);
357 virtual bool addPreEmitPass(PassManagerBase &PM, bool Fast);
360 } // end namespace llvm
365 <li><tt>getInstrInfo()</tt></li>
366 <li><tt>getRegisterInfo()</tt></li>
367 <li><tt>getFrameInfo()</tt></li>
368 <li><tt>getDataLayout()</tt></li>
369 <li><tt>getSubtargetImpl()</tt></li>
372 <p>For some targets, you also need to support the following methods:</p>
375 <li><tt>getTargetLowering()</tt></li>
376 <li><tt>getJITInfo()</tt></li>
380 In addition, the <tt>XXXTargetMachine</tt> constructor should specify a
381 <tt>TargetDescription</tt> string that determines the data layout for the target
382 machine, including characteristics such as pointer size, alignment, and
383 endianness. For example, the constructor for SparcTargetMachine contains the
387 <div class="doc_code">
389 SparcTargetMachine::SparcTargetMachine(const Module &M, const std::string &FS)
390 : DataLayout("E-p:32:32-f128:128:128"),
391 Subtarget(M, FS), InstrInfo(Subtarget),
392 FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
397 <p>Hyphens separate portions of the <tt>TargetDescription</tt> string.</p>
400 <li>An upper-case "<tt>E</tt>" in the string indicates a big-endian target data
401 model. a lower-case "<tt>e</tt>" indicates little-endian.</li>
403 <li>"<tt>p:</tt>" is followed by pointer information: size, ABI alignment, and
404 preferred alignment. If only two figures follow "<tt>p:</tt>", then the
405 first value is pointer size, and the second value is both ABI and preferred
408 <li>Then a letter for numeric type alignment: "<tt>i</tt>", "<tt>f</tt>",
409 "<tt>v</tt>", or "<tt>a</tt>" (corresponding to integer, floating point,
410 vector, or aggregate). "<tt>i</tt>", "<tt>v</tt>", or "<tt>a</tt>" are
411 followed by ABI alignment and preferred alignment. "<tt>f</tt>" is followed
412 by three values: the first indicates the size of a long double, then ABI
413 alignment, and then ABI preferred alignment.</li>
418 <!-- *********************************************************************** -->
420 <a name="TargetRegistration">Target Registration</a>
422 <!-- *********************************************************************** -->
427 You must also register your target with the <tt>TargetRegistry</tt>, which is
428 what other LLVM tools use to be able to lookup and use your target at
429 runtime. The <tt>TargetRegistry</tt> can be used directly, but for most targets
430 there are helper templates which should take care of the work for you.</p>
433 All targets should declare a global <tt>Target</tt> object which is used to
434 represent the target during registration. Then, in the target's TargetInfo
435 library, the target should define that object and use
436 the <tt>RegisterTarget</tt> template to register the target. For example, the Sparc registration code looks like this:
439 <div class="doc_code">
441 Target llvm::TheSparcTarget;
443 extern "C" void LLVMInitializeSparcTargetInfo() {
444 RegisterTarget<Triple::sparc, /*HasJIT=*/false>
445 X(TheSparcTarget, "sparc", "Sparc");
451 This allows the <tt>TargetRegistry</tt> to look up the target by name or by
452 target triple. In addition, most targets will also register additional features
453 which are available in separate libraries. These registration steps are
454 separate, because some clients may wish to only link in some parts of the target
455 -- the JIT code generator does not require the use of the assembler printer, for
456 example. Here is an example of registering the Sparc assembly printer:
459 <div class="doc_code">
461 extern "C" void LLVMInitializeSparcAsmPrinter() {
462 RegisterAsmPrinter<SparcAsmPrinter> X(TheSparcTarget);
468 For more information, see
469 "<a href="/doxygen/TargetRegistry_8h-source.html">llvm/Target/TargetRegistry.h</a>".
474 <!-- *********************************************************************** -->
476 <a name="RegisterSet">Register Set and Register Classes</a>
478 <!-- *********************************************************************** -->
483 You should describe a concrete target-specific class that represents the
484 register file of a target machine. This class is called <tt>XXXRegisterInfo</tt>
485 (where <tt>XXX</tt> identifies the target) and represents the class register
486 file data that is used for register allocation. It also describes the
487 interactions between registers.
491 You also need to define register classes to categorize related registers. A
492 register class should be added for groups of registers that are all treated the
493 same way for some instruction. Typical examples are register classes for
494 integer, floating-point, or vector registers. A register allocator allows an
495 instruction to use any register in a specified register class to perform the
496 instruction in a similar manner. Register classes allocate virtual registers to
497 instructions from these sets, and register classes let the target-independent
498 register allocator automatically choose the actual registers.
502 Much of the code for registers, including register definition, register aliases,
503 and register classes, is generated by TableGen from <tt>XXXRegisterInfo.td</tt>
504 input files and placed in <tt>XXXGenRegisterInfo.h.inc</tt> and
505 <tt>XXXGenRegisterInfo.inc</tt> output files. Some of the code in the
506 implementation of <tt>XXXRegisterInfo</tt> requires hand-coding.
509 <!-- ======================================================================= -->
511 <a name="RegisterDef">Defining a Register</a>
517 The <tt>XXXRegisterInfo.td</tt> file typically starts with register definitions
518 for a target machine. The <tt>Register</tt> class (specified
519 in <tt>Target.td</tt>) is used to define an object for each register. The
520 specified string <tt>n</tt> becomes the <tt>Name</tt> of the register. The
521 basic <tt>Register</tt> object does not have any subregisters and does not
525 <div class="doc_code">
527 class Register<string n> {
528 string Namespace = "";
532 int SpillAlignment = 0;
533 list<Register> Aliases = [];
534 list<Register> SubRegs = [];
535 list<int> DwarfNumbers = [];
541 For example, in the <tt>X86RegisterInfo.td</tt> file, there are register
542 definitions that utilize the Register class, such as:
545 <div class="doc_code">
547 def AL : Register<"AL">, DwarfRegNum<[0, 0, 0]>;
552 This defines the register <tt>AL</tt> and assigns it values (with
553 <tt>DwarfRegNum</tt>) that are used by <tt>gcc</tt>, <tt>gdb</tt>, or a debug
554 information writer to identify a register. For register
555 <tt>AL</tt>, <tt>DwarfRegNum</tt> takes an array of 3 values representing 3
556 different modes: the first element is for X86-64, the second for exception
557 handling (EH) on X86-32, and the third is generic. -1 is a special Dwarf number
558 that indicates the gcc number is undefined, and -2 indicates the register number
559 is invalid for this mode.
563 From the previously described line in the <tt>X86RegisterInfo.td</tt> file,
564 TableGen generates this code in the <tt>X86GenRegisterInfo.inc</tt> file:
567 <div class="doc_code">
569 static const unsigned GR8[] = { X86::AL, ... };
571 const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 };
573 const TargetRegisterDesc RegisterDescriptors[] = {
575 { "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ...
580 From the register info file, TableGen generates a <tt>TargetRegisterDesc</tt>
581 object for each register. <tt>TargetRegisterDesc</tt> is defined in
582 <tt>include/llvm/Target/TargetRegisterInfo.h</tt> with the following fields:
585 <div class="doc_code">
587 struct TargetRegisterDesc {
588 const char *AsmName; // Assembly language name for the register
589 const char *Name; // Printable name for the reg (for debugging)
590 const unsigned *AliasSet; // Register Alias Set
591 const unsigned *SubRegs; // Sub-register set
592 const unsigned *ImmSubRegs; // Immediate sub-register set
593 const unsigned *SuperRegs; // Super-register set
598 TableGen uses the entire target description file (<tt>.td</tt>) to determine
599 text names for the register (in the <tt>AsmName</tt> and <tt>Name</tt> fields of
600 <tt>TargetRegisterDesc</tt>) and the relationships of other registers to the
601 defined register (in the other <tt>TargetRegisterDesc</tt> fields). In this
602 example, other definitions establish the registers "<tt>AX</tt>",
603 "<tt>EAX</tt>", and "<tt>RAX</tt>" as aliases for one another, so TableGen
604 generates a null-terminated array (<tt>AL_AliasSet</tt>) for this register alias
609 The <tt>Register</tt> class is commonly used as a base class for more complex
610 classes. In <tt>Target.td</tt>, the <tt>Register</tt> class is the base for the
611 <tt>RegisterWithSubRegs</tt> class that is used to define registers that need to
612 specify subregisters in the <tt>SubRegs</tt> list, as shown here:
615 <div class="doc_code">
617 class RegisterWithSubRegs<string n,
618 list<Register> subregs> : Register<n> {
619 let SubRegs = subregs;
625 In <tt>SparcRegisterInfo.td</tt>, additional register classes are defined for
626 SPARC: a Register subclass, SparcReg, and further subclasses: <tt>Ri</tt>,
627 <tt>Rf</tt>, and <tt>Rd</tt>. SPARC registers are identified by 5-bit ID
628 numbers, which is a feature common to these subclasses. Note the use of
629 '<tt>let</tt>' expressions to override values that are initially defined in a
630 superclass (such as <tt>SubRegs</tt> field in the <tt>Rd</tt> class).
633 <div class="doc_code">
635 class SparcReg<string n> : Register<n> {
636 field bits<5> Num;
637 let Namespace = "SP";
639 // Ri - 32-bit integer registers
640 class Ri<bits<5> num, string n> :
644 // Rf - 32-bit floating-point registers
645 class Rf<bits<5> num, string n> :
649 // Rd - Slots in the FP register file for 64-bit
650 floating-point values.
651 class Rd<bits<5> num, string n,
652 list<Register> subregs> : SparcReg<n> {
654 let SubRegs = subregs;
660 In the <tt>SparcRegisterInfo.td</tt> file, there are register definitions that
661 utilize these subclasses of <tt>Register</tt>, such as:
664 <div class="doc_code">
666 def G0 : Ri< 0, "G0">,
667 DwarfRegNum<[0]>;
668 def G1 : Ri< 1, "G1">, DwarfRegNum<[1]>;
670 def F0 : Rf< 0, "F0">,
671 DwarfRegNum<[32]>;
672 def F1 : Rf< 1, "F1">,
673 DwarfRegNum<[33]>;
675 def D0 : Rd< 0, "F0", [F0, F1]>,
676 DwarfRegNum<[32]>;
677 def D1 : Rd< 2, "F2", [F2, F3]>,
678 DwarfRegNum<[34]>;
683 The last two registers shown above (<tt>D0</tt> and <tt>D1</tt>) are
684 double-precision floating-point registers that are aliases for pairs of
685 single-precision floating-point sub-registers. In addition to aliases, the
686 sub-register and super-register relationships of the defined register are in
687 fields of a register's TargetRegisterDesc.
692 <!-- ======================================================================= -->
694 <a name="RegisterClassDef">Defining a Register Class</a>
700 The <tt>RegisterClass</tt> class (specified in <tt>Target.td</tt>) is used to
701 define an object that represents a group of related registers and also defines
702 the default allocation order of the registers. A target description file
703 <tt>XXXRegisterInfo.td</tt> that uses <tt>Target.td</tt> can construct register
704 classes using the following class:
707 <div class="doc_code">
709 class RegisterClass<string namespace,
710 list<ValueType> regTypes, int alignment, dag regList> {
711 string Namespace = namespace;
712 list<ValueType> RegTypes = regTypes;
713 int Size = 0; // spill size, in bits; zero lets tblgen pick the size
714 int Alignment = alignment;
716 // CopyCost is the cost of copying a value between two registers
717 // default value 1 means a single instruction
718 // A negative value means copying is extremely expensive or impossible
720 dag MemberList = regList;
722 // for register classes that are subregisters of this class
723 list<RegisterClass> SubRegClassList = [];
725 code MethodProtos = [{}]; // to insert arbitrary code
726 code MethodBodies = [{}];
731 <p>To define a RegisterClass, use the following 4 arguments:</p>
734 <li>The first argument of the definition is the name of the namespace.</li>
736 <li>The second argument is a list of <tt>ValueType</tt> register type values
737 that are defined in <tt>include/llvm/CodeGen/ValueTypes.td</tt>. Defined
738 values include integer types (such as <tt>i16</tt>, <tt>i32</tt>,
739 and <tt>i1</tt> for Boolean), floating-point types
740 (<tt>f32</tt>, <tt>f64</tt>), and vector types (for example, <tt>v8i16</tt>
741 for an <tt>8 x i16</tt> vector). All registers in a <tt>RegisterClass</tt>
742 must have the same <tt>ValueType</tt>, but some registers may store vector
743 data in different configurations. For example a register that can process a
744 128-bit vector may be able to handle 16 8-bit integer elements, 8 16-bit
745 integers, 4 32-bit integers, and so on. </li>
747 <li>The third argument of the <tt>RegisterClass</tt> definition specifies the
748 alignment required of the registers when they are stored or loaded to
751 <li>The final argument, <tt>regList</tt>, specifies which registers are in this
752 class. If an alternative allocation order method is not specified, then
753 <tt>regList</tt> also defines the order of allocation used by the register
754 allocator. Besides simply listing registers with <tt>(add R0, R1, ...)</tt>,
755 more advanced set operators are available. See
756 <tt>include/llvm/Target/Target.td</tt> for more information.</li>
760 In <tt>SparcRegisterInfo.td</tt>, three RegisterClass objects are defined:
761 <tt>FPRegs</tt>, <tt>DFPRegs</tt>, and <tt>IntRegs</tt>. For all three register
762 classes, the first argument defines the namespace with the string
763 '<tt>SP</tt>'. <tt>FPRegs</tt> defines a group of 32 single-precision
764 floating-point registers (<tt>F0</tt> to <tt>F31</tt>); <tt>DFPRegs</tt> defines
765 a group of 16 double-precision registers
769 <div class="doc_code">
771 // F0, F1, F2, ..., F31
772 def FPRegs : RegisterClass<"SP", [f32], 32, (sequence "F%u", 0, 31)>;
774 def DFPRegs : RegisterClass<"SP", [f64], 64,
775 (add D0, D1, D2, D3, D4, D5, D6, D7, D8,
776 D9, D10, D11, D12, D13, D14, D15)>;
778 def IntRegs : RegisterClass<"SP", [i32], 32,
779 (add L0, L1, L2, L3, L4, L5, L6, L7,
780 I0, I1, I2, I3, I4, I5,
781 O0, O1, O2, O3, O4, O5, O7,
783 // Non-allocatable regs:
787 I7, // return address
789 G5, G6, G7 // reserved for kernel
795 Using <tt>SparcRegisterInfo.td</tt> with TableGen generates several output files
796 that are intended for inclusion in other source code that you write.
797 <tt>SparcRegisterInfo.td</tt> generates <tt>SparcGenRegisterInfo.h.inc</tt>,
798 which should be included in the header file for the implementation of the SPARC
799 register implementation that you write (<tt>SparcRegisterInfo.h</tt>). In
800 <tt>SparcGenRegisterInfo.h.inc</tt> a new structure is defined called
801 <tt>SparcGenRegisterInfo</tt> that uses <tt>TargetRegisterInfo</tt> as its
802 base. It also specifies types, based upon the defined register
803 classes: <tt>DFPRegsClass</tt>, <tt>FPRegsClass</tt>, and <tt>IntRegsClass</tt>.
807 <tt>SparcRegisterInfo.td</tt> also generates <tt>SparcGenRegisterInfo.inc</tt>,
808 which is included at the bottom of <tt>SparcRegisterInfo.cpp</tt>, the SPARC
809 register implementation. The code below shows only the generated integer
810 registers and associated register classes. The order of registers
811 in <tt>IntRegs</tt> reflects the order in the definition of <tt>IntRegs</tt> in
812 the target description file.
815 <div class="doc_code">
816 <pre> // IntRegs Register Class...
817 static const unsigned IntRegs[] = {
818 SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5,
819 SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3,
820 SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3,
821 SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3,
822 SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5,
826 // IntRegsVTs Register Class Value Types...
827 static const MVT::ValueType IntRegsVTs[] = {
831 namespace SP { // Register class instances
832 DFPRegsClass DFPRegsRegClass;
833 FPRegsClass FPRegsRegClass;
834 IntRegsClass IntRegsRegClass;
836 // IntRegs Sub-register Classess...
837 static const TargetRegisterClass* const IntRegsSubRegClasses [] = {
841 // IntRegs Super-register Classess...
842 static const TargetRegisterClass* const IntRegsSuperRegClasses [] = {
846 // IntRegs Register Class sub-classes...
847 static const TargetRegisterClass* const IntRegsSubclasses [] = {
851 // IntRegs Register Class super-classes...
852 static const TargetRegisterClass* const IntRegsSuperclasses [] = {
856 IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID,
857 IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses,
858 IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {}
864 The register allocators will avoid using reserved registers, and callee saved
865 registers are not used until all the volatile registers have been used. That
866 is usually good enough, but in some cases it may be necessary to provide custom
872 <!-- ======================================================================= -->
874 <a name="implementRegister">Implement a subclass of</a>
875 <a href="CodeGenerator.html#targetregisterinfo">TargetRegisterInfo</a>
881 The final step is to hand code portions of <tt>XXXRegisterInfo</tt>, which
882 implements the interface described in <tt>TargetRegisterInfo.h</tt>. These
883 functions return <tt>0</tt>, <tt>NULL</tt>, or <tt>false</tt>, unless
884 overridden. Here is a list of functions that are overridden for the SPARC
885 implementation in <tt>SparcRegisterInfo.cpp</tt>:
889 <li><tt>getCalleeSavedRegs</tt> — Returns a list of callee-saved registers
890 in the order of the desired callee-save stack frame offset.</li>
892 <li><tt>getReservedRegs</tt> — Returns a bitset indexed by physical
893 register numbers, indicating if a particular register is unavailable.</li>
895 <li><tt>hasFP</tt> — Return a Boolean indicating if a function should have
896 a dedicated frame pointer register.</li>
898 <li><tt>eliminateCallFramePseudoInstr</tt> — If call frame setup or
899 destroy pseudo instructions are used, this can be called to eliminate
902 <li><tt>eliminateFrameIndex</tt> — Eliminate abstract frame indices from
903 instructions that may use them.</li>
905 <li><tt>emitPrologue</tt> — Insert prologue code into the function.</li>
907 <li><tt>emitEpilogue</tt> — Insert epilogue code into the function.</li>
914 <!-- *********************************************************************** -->
916 <a name="InstructionSet">Instruction Set</a>
919 <!-- *********************************************************************** -->
923 During the early stages of code generation, the LLVM IR code is converted to a
924 <tt>SelectionDAG</tt> with nodes that are instances of the <tt>SDNode</tt> class
925 containing target instructions. An <tt>SDNode</tt> has an opcode, operands, type
926 requirements, and operation properties. For example, is an operation
927 commutative, does an operation load from memory. The various operation node
928 types are described in the <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>
929 file (values of the <tt>NodeType</tt> enum in the <tt>ISD</tt> namespace).
933 TableGen uses the following target description (<tt>.td</tt>) input files to
934 generate much of the code for instruction definition:
938 <li><tt>Target.td</tt> — Where the <tt>Instruction</tt>, <tt>Operand</tt>,
939 <tt>InstrInfo</tt>, and other fundamental classes are defined.</li>
941 <li><tt>TargetSelectionDAG.td</tt>— Used by <tt>SelectionDAG</tt>
942 instruction selection generators, contains <tt>SDTC*</tt> classes (selection
943 DAG type constraint), definitions of <tt>SelectionDAG</tt> nodes (such as
944 <tt>imm</tt>, <tt>cond</tt>, <tt>bb</tt>, <tt>add</tt>, <tt>fadd</tt>,
945 <tt>sub</tt>), and pattern support (<tt>Pattern</tt>, <tt>Pat</tt>,
946 <tt>PatFrag</tt>, <tt>PatLeaf</tt>, <tt>ComplexPattern</tt>.</li>
948 <li><tt>XXXInstrFormats.td</tt> — Patterns for definitions of
949 target-specific instructions.</li>
951 <li><tt>XXXInstrInfo.td</tt> — Target-specific definitions of instruction
952 templates, condition codes, and instructions of an instruction set. For
953 architecture modifications, a different file name may be used. For example,
954 for Pentium with SSE instruction, this file is <tt>X86InstrSSE.td</tt>, and
955 for Pentium with MMX, this file is <tt>X86InstrMMX.td</tt>.</li>
959 There is also a target-specific <tt>XXX.td</tt> file, where <tt>XXX</tt> is the
960 name of the target. The <tt>XXX.td</tt> file includes the other <tt>.td</tt>
961 input files, but its contents are only directly important for subtargets.
965 You should describe a concrete target-specific class <tt>XXXInstrInfo</tt> that
966 represents machine instructions supported by a target machine.
967 <tt>XXXInstrInfo</tt> contains an array of <tt>XXXInstrDescriptor</tt> objects,
968 each of which describes one instruction. An instruction descriptor defines:</p>
971 <li>Opcode mnemonic</li>
973 <li>Number of operands</li>
975 <li>List of implicit register definitions and uses</li>
977 <li>Target-independent properties (such as memory access, is commutable)</li>
979 <li>Target-specific flags </li>
983 The Instruction class (defined in <tt>Target.td</tt>) is mostly used as a base
984 for more complex instruction classes.
987 <div class="doc_code">
988 <pre>class Instruction {
989 string Namespace = "";
990 dag OutOperandList; // An dag containing the MI def operand list.
991 dag InOperandList; // An dag containing the MI use operand list.
992 string AsmString = ""; // The .s format to print the instruction with.
993 list<dag> Pattern; // Set to the DAG pattern for this instruction
994 list<Register> Uses = [];
995 list<Register> Defs = [];
996 list<Predicate> Predicates = []; // predicates turned into isel match code
997 ... remainder not shown for space ...
1003 A <tt>SelectionDAG</tt> node (<tt>SDNode</tt>) should contain an object
1004 representing a target-specific instruction that is defined
1005 in <tt>XXXInstrInfo.td</tt>. The instruction objects should represent
1006 instructions from the architecture manual of the target machine (such as the
1007 SPARC Architecture Manual for the SPARC target).
1011 A single instruction from the architecture manual is often modeled as multiple
1012 target instructions, depending upon its operands. For example, a manual might
1013 describe an add instruction that takes a register or an immediate operand. An
1014 LLVM target could model this with two instructions named <tt>ADDri</tt> and
1019 You should define a class for each instruction category and define each opcode
1020 as a subclass of the category with appropriate parameters such as the fixed
1021 binary encoding of opcodes and extended opcodes. You should map the register
1022 bits to the bits of the instruction in which they are encoded (for the
1023 JIT). Also you should specify how the instruction should be printed when the
1024 automatic assembly printer is used.
1028 As is described in the SPARC Architecture Manual, Version 8, there are three
1029 major 32-bit formats for instructions. Format 1 is only for the <tt>CALL</tt>
1030 instruction. Format 2 is for branch on condition codes and <tt>SETHI</tt> (set
1031 high bits of a register) instructions. Format 3 is for other instructions.
1035 Each of these formats has corresponding classes in <tt>SparcInstrFormat.td</tt>.
1036 <tt>InstSP</tt> is a base class for other instruction classes. Additional base
1037 classes are specified for more precise formats: for example
1038 in <tt>SparcInstrFormat.td</tt>, <tt>F2_1</tt> is for <tt>SETHI</tt>,
1039 and <tt>F2_2</tt> is for branches. There are three other base
1040 classes: <tt>F3_1</tt> for register/register operations, <tt>F3_2</tt> for
1041 register/immediate operations, and <tt>F3_3</tt> for floating-point
1042 operations. <tt>SparcInstrInfo.td</tt> also adds the base class Pseudo for
1043 synthetic SPARC instructions.
1047 <tt>SparcInstrInfo.td</tt> largely consists of operand and instruction
1048 definitions for the SPARC target. In <tt>SparcInstrInfo.td</tt>, the following
1049 target description file entry, <tt>LDrr</tt>, defines the Load Integer
1050 instruction for a Word (the <tt>LD</tt> SPARC opcode) from a memory address to a
1051 register. The first parameter, the value 3 (<tt>11<sub>2</sub></tt>), is the
1052 operation value for this category of operation. The second parameter
1053 (<tt>000000<sub>2</sub></tt>) is the specific operation value
1054 for <tt>LD</tt>/Load Word. The third parameter is the output destination, which
1055 is a register operand and defined in the <tt>Register</tt> target description
1056 file (<tt>IntRegs</tt>).
1059 <div class="doc_code">
1060 <pre>def LDrr : F3_1 <3, 0b000000, (outs IntRegs:$dst), (ins MEMrr:$addr),
1062 [(set IntRegs:$dst, (load ADDRrr:$addr))]>;
1067 The fourth parameter is the input source, which uses the address
1068 operand <tt>MEMrr</tt> that is defined earlier in <tt>SparcInstrInfo.td</tt>:
1071 <div class="doc_code">
1072 <pre>def MEMrr : Operand<i32> {
1073 let PrintMethod = "printMemOperand";
1074 let MIOperandInfo = (ops IntRegs, IntRegs);
1080 The fifth parameter is a string that is used by the assembly printer and can be
1081 left as an empty string until the assembly printer interface is implemented. The
1082 sixth and final parameter is the pattern used to match the instruction during
1083 the SelectionDAG Select Phase described in
1084 (<a href="CodeGenerator.html">The LLVM
1085 Target-Independent Code Generator</a>). This parameter is detailed in the next
1086 section, <a href="#InstructionSelector">Instruction Selector</a>.
1090 Instruction class definitions are not overloaded for different operand types, so
1091 separate versions of instructions are needed for register, memory, or immediate
1092 value operands. For example, to perform a Load Integer instruction for a Word
1093 from an immediate operand to a register, the following instruction class is
1097 <div class="doc_code">
1098 <pre>def LDri : F3_2 <3, 0b000000, (outs IntRegs:$dst), (ins MEMri:$addr),
1100 [(set IntRegs:$dst, (load ADDRri:$addr))]>;
1105 Writing these definitions for so many similar instructions can involve a lot of
1106 cut and paste. In td files, the <tt>multiclass</tt> directive enables the
1107 creation of templates to define several instruction classes at once (using
1108 the <tt>defm</tt> directive). For example in <tt>SparcInstrInfo.td</tt>, the
1109 <tt>multiclass</tt> pattern <tt>F3_12</tt> is defined to create 2 instruction
1110 classes each time <tt>F3_12</tt> is invoked:
1113 <div class="doc_code">
1114 <pre>multiclass F3_12 <string OpcStr, bits<6> Op3Val, SDNode OpNode> {
1115 def rr : F3_1 <2, Op3Val,
1116 (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
1117 !strconcat(OpcStr, " $b, $c, $dst"),
1118 [(set IntRegs:$dst, (OpNode IntRegs:$b, IntRegs:$c))]>;
1119 def ri : F3_2 <2, Op3Val,
1120 (outs IntRegs:$dst), (ins IntRegs:$b, i32imm:$c),
1121 !strconcat(OpcStr, " $b, $c, $dst"),
1122 [(set IntRegs:$dst, (OpNode IntRegs:$b, simm13:$c))]>;
1128 So when the <tt>defm</tt> directive is used for the <tt>XOR</tt>
1129 and <tt>ADD</tt> instructions, as seen below, it creates four instruction
1130 objects: <tt>XORrr</tt>, <tt>XORri</tt>, <tt>ADDrr</tt>, and <tt>ADDri</tt>.
1133 <div class="doc_code">
1135 defm XOR : F3_12<"xor", 0b000011, xor>;
1136 defm ADD : F3_12<"add", 0b000000, add>;
1141 <tt>SparcInstrInfo.td</tt> also includes definitions for condition codes that
1142 are referenced by branch instructions. The following definitions
1143 in <tt>SparcInstrInfo.td</tt> indicate the bit location of the SPARC condition
1144 code. For example, the 10<sup>th</sup> bit represents the 'greater than'
1145 condition for integers, and the 22<sup>nd</sup> bit represents the 'greater
1146 than' condition for floats.
1149 <div class="doc_code">
1151 def ICC_NE : ICC_VAL< 9>; // Not Equal
1152 def ICC_E : ICC_VAL< 1>; // Equal
1153 def ICC_G : ICC_VAL<10>; // Greater
1155 def FCC_U : FCC_VAL<23>; // Unordered
1156 def FCC_G : FCC_VAL<22>; // Greater
1157 def FCC_UG : FCC_VAL<21>; // Unordered or Greater
1163 (Note that <tt>Sparc.h</tt> also defines enums that correspond to the same SPARC
1164 condition codes. Care must be taken to ensure the values in <tt>Sparc.h</tt>
1165 correspond to the values in <tt>SparcInstrInfo.td</tt>. I.e.,
1166 <tt>SPCC::ICC_NE = 9</tt>, <tt>SPCC::FCC_U = 23</tt> and so on.)
1169 <!-- ======================================================================= -->
1171 <a name="operandMapping">Instruction Operand Mapping</a>
1177 The code generator backend maps instruction operands to fields in the
1178 instruction. Operands are assigned to unbound fields in the instruction in the
1179 order they are defined. Fields are bound when they are assigned a value. For
1180 example, the Sparc target defines the <tt>XNORrr</tt> instruction as
1181 a <tt>F3_1</tt> format instruction having three operands.
1184 <div class="doc_code">
1186 def XNORrr : F3_1<2, 0b000111,
1187 (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
1188 "xnor $b, $c, $dst",
1189 [(set IntRegs:$dst, (not (xor IntRegs:$b, IntRegs:$c)))]>;
1194 The instruction templates in <tt>SparcInstrFormats.td</tt> show the base class
1195 for <tt>F3_1</tt> is <tt>InstSP</tt>.
1198 <div class="doc_code">
1200 class InstSP<dag outs, dag ins, string asmstr, list<dag> pattern> : Instruction {
1201 field bits<32> Inst;
1202 let Namespace = "SP";
1204 let Inst{31-30} = op;
1205 dag OutOperandList = outs;
1206 dag InOperandList = ins;
1207 let AsmString = asmstr;
1208 let Pattern = pattern;
1213 <p><tt>InstSP</tt> leaves the <tt>op</tt> field unbound.</p>
1215 <div class="doc_code">
1217 class F3<dag outs, dag ins, string asmstr, list<dag> pattern>
1218 : InstSP<outs, ins, asmstr, pattern> {
1222 let op{1} = 1; // Op = 2 or 3
1223 let Inst{29-25} = rd;
1224 let Inst{24-19} = op3;
1225 let Inst{18-14} = rs1;
1231 <tt>F3</tt> binds the <tt>op</tt> field and defines the <tt>rd</tt>,
1232 <tt>op3</tt>, and <tt>rs1</tt> fields. <tt>F3</tt> format instructions will
1233 bind the operands <tt>rd</tt>, <tt>op3</tt>, and <tt>rs1</tt> fields.
1236 <div class="doc_code">
1238 class F3_1<bits<2> opVal, bits<6> op3val, dag outs, dag ins,
1239 string asmstr, list<dag> pattern> : F3<outs, ins, asmstr, pattern> {
1240 bits<8> asi = 0; // asi not currently used
1244 let Inst{13} = 0; // i field = 0
1245 let Inst{12-5} = asi; // address space identifier
1246 let Inst{4-0} = rs2;
1252 <tt>F3_1</tt> binds the <tt>op3</tt> field and defines the <tt>rs2</tt>
1253 fields. <tt>F3_1</tt> format instructions will bind the operands to the <tt>rd</tt>,
1254 <tt>rs1</tt>, and <tt>rs2</tt> fields. This results in the <tt>XNORrr</tt>
1255 instruction binding <tt>$dst</tt>, <tt>$b</tt>, and <tt>$c</tt> operands to
1256 the <tt>rd</tt>, <tt>rs1</tt>, and <tt>rs2</tt> fields respectively.
1261 <!-- ======================================================================= -->
1263 <a name="relationMapping">Instruction Relation Mapping</a>
1269 This TableGen feature is used to relate instructions with each other. It is
1270 particularly useful when you have multiple instruction formats and need to
1271 switch between them after instruction selection. This entire feature is driven
1272 by relation models which can be defined in <tt>XXXInstrInfo.td</tt> files
1273 according to the target-specific instruction set. Relation models are defined
1274 using <tt>InstrMapping</tt> class as a base. TableGen parses all the models
1275 and generates instruction relation maps using the specified information.
1276 Relation maps are emitted as tables in the <tt>XXXGenInstrInfo.inc</tt> file
1277 along with the functions to query them. For the detailed information on how to
1278 use this feature, please refer to
1279 <a href="HowToUseInstrMappings.html">How to add Instruction Mappings</a>
1284 <!-- ======================================================================= -->
1286 <a name="implementInstr">Implement a subclass of </a>
1287 <a href="CodeGenerator.html#targetinstrinfo">TargetInstrInfo</a>
1293 The final step is to hand code portions of <tt>XXXInstrInfo</tt>, which
1294 implements the interface described in <tt>TargetInstrInfo.h</tt>. These
1295 functions return <tt>0</tt> or a Boolean or they assert, unless
1296 overridden. Here's a list of functions that are overridden for the SPARC
1297 implementation in <tt>SparcInstrInfo.cpp</tt>:
1301 <li><tt>isLoadFromStackSlot</tt> — If the specified machine instruction is
1302 a direct load from a stack slot, return the register number of the
1303 destination and the <tt>FrameIndex</tt> of the stack slot.</li>
1305 <li><tt>isStoreToStackSlot</tt> — If the specified machine instruction is
1306 a direct store to a stack slot, return the register number of the
1307 destination and the <tt>FrameIndex</tt> of the stack slot.</li>
1309 <li><tt>copyPhysReg</tt> — Copy values between a pair of physical
1312 <li><tt>storeRegToStackSlot</tt> — Store a register value to a stack
1315 <li><tt>loadRegFromStackSlot</tt> — Load a register value from a stack
1318 <li><tt>storeRegToAddr</tt> — Store a register value to memory.</li>
1320 <li><tt>loadRegFromAddr</tt> — Load a register value from memory.</li>
1322 <li><tt>foldMemoryOperand</tt> — Attempt to combine instructions of any
1323 load or store instruction for the specified operand(s).</li>
1328 <!-- ======================================================================= -->
1330 <a name="branchFolding">Branch Folding and If Conversion</a>
1335 Performance can be improved by combining instructions or by eliminating
1336 instructions that are never reached. The <tt>AnalyzeBranch</tt> method
1337 in <tt>XXXInstrInfo</tt> may be implemented to examine conditional instructions
1338 and remove unnecessary instructions. <tt>AnalyzeBranch</tt> looks at the end of
1339 a machine basic block (MBB) for opportunities for improvement, such as branch
1340 folding and if conversion. The <tt>BranchFolder</tt> and <tt>IfConverter</tt>
1341 machine function passes (see the source files <tt>BranchFolding.cpp</tt> and
1342 <tt>IfConversion.cpp</tt> in the <tt>lib/CodeGen</tt> directory) call
1343 <tt>AnalyzeBranch</tt> to improve the control flow graph that represents the
1348 Several implementations of <tt>AnalyzeBranch</tt> (for ARM, Alpha, and X86) can
1349 be examined as models for your own <tt>AnalyzeBranch</tt> implementation. Since
1350 SPARC does not implement a useful <tt>AnalyzeBranch</tt>, the ARM target
1351 implementation is shown below.
1354 <p><tt>AnalyzeBranch</tt> returns a Boolean value and takes four parameters:</p>
1357 <li><tt>MachineBasicBlock &MBB</tt> — The incoming block to be
1360 <li><tt>MachineBasicBlock *&TBB</tt> — A destination block that is
1361 returned. For a conditional branch that evaluates to true, <tt>TBB</tt> is
1362 the destination.</li>
1364 <li><tt>MachineBasicBlock *&FBB</tt> — For a conditional branch that
1365 evaluates to false, <tt>FBB</tt> is returned as the destination.</li>
1367 <li><tt>std::vector<MachineOperand> &Cond</tt> — List of
1368 operands to evaluate a condition for a conditional branch.</li>
1372 In the simplest case, if a block ends without a branch, then it falls through to
1373 the successor block. No destination blocks are specified for either <tt>TBB</tt>
1374 or <tt>FBB</tt>, so both parameters return <tt>NULL</tt>. The start of
1375 the <tt>AnalyzeBranch</tt> (see code below for the ARM target) shows the
1376 function parameters and the code for the simplest case.
1379 <div class="doc_code">
1380 <pre>bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
1381 MachineBasicBlock *&TBB, MachineBasicBlock *&FBB,
1382 std::vector<MachineOperand> &Cond) const
1384 MachineBasicBlock::iterator I = MBB.end();
1385 if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
1391 If a block ends with a single unconditional branch instruction, then
1392 <tt>AnalyzeBranch</tt> (shown below) should return the destination of that
1393 branch in the <tt>TBB</tt> parameter.
1396 <div class="doc_code">
1398 if (LastOpc == ARM::B || LastOpc == ARM::tB) {
1399 TBB = LastInst->getOperand(0).getMBB();
1406 If a block ends with two unconditional branches, then the second branch is never
1407 reached. In that situation, as shown below, remove the last branch instruction
1408 and return the penultimate branch in the <tt>TBB</tt> parameter.
1411 <div class="doc_code">
1413 if ((SecondLastOpc == ARM::B || SecondLastOpc==ARM::tB) &&
1414 (LastOpc == ARM::B || LastOpc == ARM::tB)) {
1415 TBB = SecondLastInst->getOperand(0).getMBB();
1417 I->eraseFromParent();
1424 A block may end with a single conditional branch instruction that falls through
1425 to successor block if the condition evaluates to false. In that case,
1426 <tt>AnalyzeBranch</tt> (shown below) should return the destination of that
1427 conditional branch in the <tt>TBB</tt> parameter and a list of operands in
1428 the <tt>Cond</tt> parameter to evaluate the condition.
1431 <div class="doc_code">
1433 if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
1434 // Block ends with fall-through condbranch.
1435 TBB = LastInst->getOperand(0).getMBB();
1436 Cond.push_back(LastInst->getOperand(1));
1437 Cond.push_back(LastInst->getOperand(2));
1444 If a block ends with both a conditional branch and an ensuing unconditional
1445 branch, then <tt>AnalyzeBranch</tt> (shown below) should return the conditional
1446 branch destination (assuming it corresponds to a conditional evaluation of
1447 '<tt>true</tt>') in the <tt>TBB</tt> parameter and the unconditional branch
1448 destination in the <tt>FBB</tt> (corresponding to a conditional evaluation of
1449 '<tt>false</tt>'). A list of operands to evaluate the condition should be
1450 returned in the <tt>Cond</tt> parameter.
1453 <div class="doc_code">
1455 unsigned SecondLastOpc = SecondLastInst->getOpcode();
1457 if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) ||
1458 (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) {
1459 TBB = SecondLastInst->getOperand(0).getMBB();
1460 Cond.push_back(SecondLastInst->getOperand(1));
1461 Cond.push_back(SecondLastInst->getOperand(2));
1462 FBB = LastInst->getOperand(0).getMBB();
1469 For the last two cases (ending with a single conditional branch or ending with
1470 one conditional and one unconditional branch), the operands returned in
1471 the <tt>Cond</tt> parameter can be passed to methods of other instructions to
1472 create new branches or perform other operations. An implementation
1473 of <tt>AnalyzeBranch</tt> requires the helper methods <tt>RemoveBranch</tt>
1474 and <tt>InsertBranch</tt> to manage subsequent operations.
1478 <tt>AnalyzeBranch</tt> should return false indicating success in most circumstances.
1479 <tt>AnalyzeBranch</tt> should only return true when the method is stumped about what to
1480 do, for example, if a block has three terminating branches. <tt>AnalyzeBranch</tt> may
1481 return true if it encounters a terminator it cannot handle, such as an indirect
1489 <!-- *********************************************************************** -->
1491 <a name="InstructionSelector">Instruction Selector</a>
1493 <!-- *********************************************************************** -->
1498 LLVM uses a <tt>SelectionDAG</tt> to represent LLVM IR instructions, and nodes
1499 of the <tt>SelectionDAG</tt> ideally represent native target
1500 instructions. During code generation, instruction selection passes are performed
1501 to convert non-native DAG instructions into native target-specific
1502 instructions. The pass described in <tt>XXXISelDAGToDAG.cpp</tt> is used to
1503 match patterns and perform DAG-to-DAG instruction selection. Optionally, a pass
1504 may be defined (in <tt>XXXBranchSelector.cpp</tt>) to perform similar DAG-to-DAG
1505 operations for branch instructions. Later, the code in
1506 <tt>XXXISelLowering.cpp</tt> replaces or removes operations and data types not
1507 supported natively (legalizes) in a <tt>SelectionDAG</tt>.
1511 TableGen generates code for instruction selection using the following target
1512 description input files:
1516 <li><tt>XXXInstrInfo.td</tt> — Contains definitions of instructions in a
1517 target-specific instruction set, generates <tt>XXXGenDAGISel.inc</tt>, which
1518 is included in <tt>XXXISelDAGToDAG.cpp</tt>.</li>
1520 <li><tt>XXXCallingConv.td</tt> — Contains the calling and return value
1521 conventions for the target architecture, and it generates
1522 <tt>XXXGenCallingConv.inc</tt>, which is included in
1523 <tt>XXXISelLowering.cpp</tt>.</li>
1527 The implementation of an instruction selection pass must include a header that
1528 declares the <tt>FunctionPass</tt> class or a subclass of <tt>FunctionPass</tt>. In
1529 <tt>XXXTargetMachine.cpp</tt>, a Pass Manager (PM) should add each instruction
1530 selection pass into the queue of passes to run.
1534 The LLVM static compiler (<tt>llc</tt>) is an excellent tool for visualizing the
1535 contents of DAGs. To display the <tt>SelectionDAG</tt> before or after specific
1536 processing phases, use the command line options for <tt>llc</tt>, described
1537 at <a href="CodeGenerator.html#selectiondag_process">
1538 SelectionDAG Instruction Selection Process</a>.
1542 To describe instruction selector behavior, you should add patterns for lowering
1543 LLVM code into a <tt>SelectionDAG</tt> as the last parameter of the instruction
1544 definitions in <tt>XXXInstrInfo.td</tt>. For example, in
1545 <tt>SparcInstrInfo.td</tt>, this entry defines a register store operation, and
1546 the last parameter describes a pattern with the store DAG operator.
1549 <div class="doc_code">
1551 def STrr : F3_1< 3, 0b000100, (outs), (ins MEMrr:$addr, IntRegs:$src),
1552 "st $src, [$addr]", [(store IntRegs:$src, ADDRrr:$addr)]>;
1557 <tt>ADDRrr</tt> is a memory mode that is also defined in
1558 <tt>SparcInstrInfo.td</tt>:
1561 <div class="doc_code">
1563 def ADDRrr : ComplexPattern<i32, 2, "SelectADDRrr", [], []>;
1568 The definition of <tt>ADDRrr</tt> refers to <tt>SelectADDRrr</tt>, which is a
1569 function defined in an implementation of the Instructor Selector (such
1570 as <tt>SparcISelDAGToDAG.cpp</tt>).
1574 In <tt>lib/Target/TargetSelectionDAG.td</tt>, the DAG operator for store is
1578 <div class="doc_code">
1580 def store : PatFrag<(ops node:$val, node:$ptr),
1581 (st node:$val, node:$ptr), [{
1582 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N))
1583 return !ST->isTruncatingStore() &&
1584 ST->getAddressingMode() == ISD::UNINDEXED;
1591 <tt>XXXInstrInfo.td</tt> also generates (in <tt>XXXGenDAGISel.inc</tt>) the
1592 <tt>SelectCode</tt> method that is used to call the appropriate processing
1593 method for an instruction. In this example, <tt>SelectCode</tt>
1594 calls <tt>Select_ISD_STORE</tt> for the <tt>ISD::STORE</tt> opcode.
1597 <div class="doc_code">
1599 SDNode *SelectCode(SDValue N) {
1601 MVT::ValueType NVT = N.getNode()->getValueType(0);
1602 switch (N.getOpcode()) {
1606 return Select_ISD_STORE(N);
1616 The pattern for <tt>STrr</tt> is matched, so elsewhere in
1617 <tt>XXXGenDAGISel.inc</tt>, code for <tt>STrr</tt> is created for
1618 <tt>Select_ISD_STORE</tt>. The <tt>Emit_22</tt> method is also generated
1619 in <tt>XXXGenDAGISel.inc</tt> to complete the processing of this
1623 <div class="doc_code">
1625 SDNode *Select_ISD_STORE(const SDValue &N) {
1626 SDValue Chain = N.getOperand(0);
1627 if (Predicate_store(N.getNode())) {
1628 SDValue N1 = N.getOperand(1);
1629 SDValue N2 = N.getOperand(2);
1633 // Pattern: (st:void IntRegs:i32:$src,
1634 // ADDRrr:i32:$addr)<<P:Predicate_store>>
1635 // Emits: (STrr:void ADDRrr:i32:$addr, IntRegs:i32:$src)
1636 // Pattern complexity = 13 cost = 1 size = 0
1637 if (SelectADDRrr(N, N2, CPTmp0, CPTmp1) &&
1638 N1.getNode()->getValueType(0) == MVT::i32 &&
1639 N2.getNode()->getValueType(0) == MVT::i32) {
1640 return Emit_22(N, SP::STrr, CPTmp0, CPTmp1);
1646 <!-- ======================================================================= -->
1648 <a name="LegalizePhase">The SelectionDAG Legalize Phase</a>
1654 The Legalize phase converts a DAG to use types and operations that are natively
1655 supported by the target. For natively unsupported types and operations, you need
1656 to add code to the target-specific XXXTargetLowering implementation to convert
1657 unsupported types and operations to supported ones.
1661 In the constructor for the <tt>XXXTargetLowering</tt> class, first use the
1662 <tt>addRegisterClass</tt> method to specify which types are supports and which
1663 register classes are associated with them. The code for the register classes are
1664 generated by TableGen from <tt>XXXRegisterInfo.td</tt> and placed
1665 in <tt>XXXGenRegisterInfo.h.inc</tt>. For example, the implementation of the
1666 constructor for the SparcTargetLowering class (in
1667 <tt>SparcISelLowering.cpp</tt>) starts with the following code:
1670 <div class="doc_code">
1672 addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
1673 addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
1674 addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
1679 You should examine the node types in the <tt>ISD</tt> namespace
1680 (<tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>) and determine which
1681 operations the target natively supports. For operations that do <b>not</b> have
1682 native support, add a callback to the constructor for the XXXTargetLowering
1683 class, so the instruction selection process knows what to do. The TargetLowering
1684 class callback methods (declared in <tt>llvm/Target/TargetLowering.h</tt>) are:
1688 <li><tt>setOperationAction</tt> — General operation.</li>
1690 <li><tt>setLoadExtAction</tt> — Load with extension.</li>
1692 <li><tt>setTruncStoreAction</tt> — Truncating store.</li>
1694 <li><tt>setIndexedLoadAction</tt> — Indexed load.</li>
1696 <li><tt>setIndexedStoreAction</tt> — Indexed store.</li>
1698 <li><tt>setConvertAction</tt> — Type conversion.</li>
1700 <li><tt>setCondCodeAction</tt> — Support for a given condition code.</li>
1704 Note: on older releases, <tt>setLoadXAction</tt> is used instead
1705 of <tt>setLoadExtAction</tt>. Also, on older releases,
1706 <tt>setCondCodeAction</tt> may not be supported. Examine your release
1707 to see what methods are specifically supported.
1711 These callbacks are used to determine that an operation does or does not work
1712 with a specified type (or types). And in all cases, the third parameter is
1713 a <tt>LegalAction</tt> type enum value: <tt>Promote</tt>, <tt>Expand</tt>,
1714 <tt>Custom</tt>, or <tt>Legal</tt>. <tt>SparcISelLowering.cpp</tt>
1715 contains examples of all four <tt>LegalAction</tt> values.
1718 <!-- _______________________________________________________________________ -->
1720 <a name="promote">Promote</a>
1726 For an operation without native support for a given type, the specified type may
1727 be promoted to a larger type that is supported. For example, SPARC does not
1728 support a sign-extending load for Boolean values (<tt>i1</tt> type), so
1729 in <tt>SparcISelLowering.cpp</tt> the third parameter below, <tt>Promote</tt>,
1730 changes <tt>i1</tt> type values to a large type before loading.
1733 <div class="doc_code">
1735 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
1741 <!-- _______________________________________________________________________ -->
1743 <a name="expand">Expand</a>
1749 For a type without native support, a value may need to be broken down further,
1750 rather than promoted. For an operation without native support, a combination of
1751 other operations may be used to similar effect. In SPARC, the floating-point
1752 sine and cosine trig operations are supported by expansion to other operations,
1753 as indicated by the third parameter, <tt>Expand</tt>, to
1754 <tt>setOperationAction</tt>:
1757 <div class="doc_code">
1759 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1760 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1766 <!-- _______________________________________________________________________ -->
1768 <a name="custom">Custom</a>
1774 For some operations, simple type promotion or operation expansion may be
1775 insufficient. In some cases, a special intrinsic function must be implemented.
1779 For example, a constant value may require special treatment, or an operation may
1780 require spilling and restoring registers in the stack and working with register
1785 As seen in <tt>SparcISelLowering.cpp</tt> code below, to perform a type
1786 conversion from a floating point value to a signed integer, first the
1787 <tt>setOperationAction</tt> should be called with <tt>Custom</tt> as the third
1791 <div class="doc_code">
1793 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1798 In the <tt>LowerOperation</tt> method, for each <tt>Custom</tt> operation, a
1799 case statement should be added to indicate what function to call. In the
1800 following code, an <tt>FP_TO_SINT</tt> opcode will call
1801 the <tt>LowerFP_TO_SINT</tt> method:
1804 <div class="doc_code">
1806 SDValue SparcTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
1807 switch (Op.getOpcode()) {
1808 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
1816 Finally, the <tt>LowerFP_TO_SINT</tt> method is implemented, using an FP
1817 register to convert the floating-point value to an integer.
1820 <div class="doc_code">
1822 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
1823 assert(Op.getValueType() == MVT::i32);
1824 Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
1825 return DAG.getNode(ISD::BITCAST, MVT::i32, Op);
1832 <!-- _______________________________________________________________________ -->
1834 <a name="legal">Legal</a>
1840 The <tt>Legal</tt> LegalizeAction enum value simply indicates that an
1841 operation <b>is</b> natively supported. <tt>Legal</tt> represents the default
1842 condition, so it is rarely used. In <tt>SparcISelLowering.cpp</tt>, the action
1843 for <tt>CTPOP</tt> (an operation to count the bits set in an integer) is
1844 natively supported only for SPARC v9. The following code enables
1845 the <tt>Expand</tt> conversion technique for non-v9 SPARC implementations.
1848 <div class="doc_code">
1850 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1852 if (TM.getSubtarget<SparcSubtarget>().isV9())
1853 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
1854 case ISD::SETULT: return SPCC::ICC_CS;
1855 case ISD::SETULE: return SPCC::ICC_LEU;
1856 case ISD::SETUGT: return SPCC::ICC_GU;
1857 case ISD::SETUGE: return SPCC::ICC_CC;
1867 <!-- ======================================================================= -->
1869 <a name="callingConventions">Calling Conventions</a>
1875 To support target-specific calling conventions, <tt>XXXGenCallingConv.td</tt>
1876 uses interfaces (such as CCIfType and CCAssignToReg) that are defined in
1877 <tt>lib/Target/TargetCallingConv.td</tt>. TableGen can take the target
1878 descriptor file <tt>XXXGenCallingConv.td</tt> and generate the header
1879 file <tt>XXXGenCallingConv.inc</tt>, which is typically included
1880 in <tt>XXXISelLowering.cpp</tt>. You can use the interfaces in
1881 <tt>TargetCallingConv.td</tt> to specify:
1885 <li>The order of parameter allocation.</li>
1887 <li>Where parameters and return values are placed (that is, on the stack or in
1890 <li>Which registers may be used.</li>
1892 <li>Whether the caller or callee unwinds the stack.</li>
1896 The following example demonstrates the use of the <tt>CCIfType</tt> and
1897 <tt>CCAssignToReg</tt> interfaces. If the <tt>CCIfType</tt> predicate is true
1898 (that is, if the current argument is of type <tt>f32</tt> or <tt>f64</tt>), then
1899 the action is performed. In this case, the <tt>CCAssignToReg</tt> action assigns
1900 the argument value to the first available register: either <tt>R0</tt>
1904 <div class="doc_code">
1906 CCIfType<[f32,f64], CCAssignToReg<[R0, R1]>>
1911 <tt>SparcCallingConv.td</tt> contains definitions for a target-specific
1912 return-value calling convention (RetCC_Sparc32) and a basic 32-bit C calling
1913 convention (<tt>CC_Sparc32</tt>). The definition of <tt>RetCC_Sparc32</tt>
1914 (shown below) indicates which registers are used for specified scalar return
1915 types. A single-precision float is returned to register <tt>F0</tt>, and a
1916 double-precision float goes to register <tt>D0</tt>. A 32-bit integer is
1917 returned in register <tt>I0</tt> or <tt>I1</tt>.
1920 <div class="doc_code">
1922 def RetCC_Sparc32 : CallingConv<[
1923 CCIfType<[i32], CCAssignToReg<[I0, I1]>>,
1924 CCIfType<[f32], CCAssignToReg<[F0]>>,
1925 CCIfType<[f64], CCAssignToReg<[D0]>>
1931 The definition of <tt>CC_Sparc32</tt> in <tt>SparcCallingConv.td</tt> introduces
1932 <tt>CCAssignToStack</tt>, which assigns the value to a stack slot with the
1933 specified size and alignment. In the example below, the first parameter, 4,
1934 indicates the size of the slot, and the second parameter, also 4, indicates the
1935 stack alignment along 4-byte units. (Special cases: if size is zero, then the
1936 ABI size is used; if alignment is zero, then the ABI alignment is used.)
1939 <div class="doc_code">
1941 def CC_Sparc32 : CallingConv<[
1942 // All arguments get passed in integer registers if there is space.
1943 CCIfType<[i32, f32, f64], CCAssignToReg<[I0, I1, I2, I3, I4, I5]>>,
1944 CCAssignToStack<4, 4>
1950 <tt>CCDelegateTo</tt> is another commonly used interface, which tries to find a
1951 specified sub-calling convention, and, if a match is found, it is invoked. In
1952 the following example (in <tt>X86CallingConv.td</tt>), the definition of
1953 <tt>RetCC_X86_32_C</tt> ends with <tt>CCDelegateTo</tt>. After the current value
1954 is assigned to the register <tt>ST0</tt> or <tt>ST1</tt>,
1955 the <tt>RetCC_X86Common</tt> is invoked.
1958 <div class="doc_code">
1960 def RetCC_X86_32_C : CallingConv<[
1961 CCIfType<[f32], CCAssignToReg<[ST0, ST1]>>,
1962 CCIfType<[f64], CCAssignToReg<[ST0, ST1]>>,
1963 CCDelegateTo<RetCC_X86Common>
1969 <tt>CCIfCC</tt> is an interface that attempts to match the given name to the
1970 current calling convention. If the name identifies the current calling
1971 convention, then a specified action is invoked. In the following example (in
1972 <tt>X86CallingConv.td</tt>), if the <tt>Fast</tt> calling convention is in use,
1973 then <tt>RetCC_X86_32_Fast</tt> is invoked. If the <tt>SSECall</tt> calling
1974 convention is in use, then <tt>RetCC_X86_32_SSE</tt> is invoked.
1977 <div class="doc_code">
1979 def RetCC_X86_32 : CallingConv<[
1980 CCIfCC<"CallingConv::Fast", CCDelegateTo<RetCC_X86_32_Fast>>,
1981 CCIfCC<"CallingConv::X86_SSECall", CCDelegateTo<RetCC_X86_32_SSE>>,
1982 CCDelegateTo<RetCC_X86_32_C>
1987 <p>Other calling convention interfaces include:</p>
1990 <li><tt>CCIf <predicate, action></tt> — If the predicate matches,
1991 apply the action.</li>
1993 <li><tt>CCIfInReg <action></tt> — If the argument is marked with the
1994 '<tt>inreg</tt>' attribute, then apply the action.</li>
1996 <li><tt>CCIfNest <action></tt> — Inf the argument is marked with the
1997 '<tt>nest</tt>' attribute, then apply the action.</li>
1999 <li><tt>CCIfNotVarArg <action></tt> — If the current function does
2000 not take a variable number of arguments, apply the action.</li>
2002 <li><tt>CCAssignToRegWithShadow <registerList, shadowList></tt> —
2003 similar to <tt>CCAssignToReg</tt>, but with a shadow list of registers.</li>
2005 <li><tt>CCPassByVal <size, align></tt> — Assign value to a stack
2006 slot with the minimum specified size and alignment.</li>
2008 <li><tt>CCPromoteToType <type></tt> — Promote the current value to
2009 the specified type.</li>
2011 <li><tt>CallingConv <[actions]></tt> — Define each calling
2012 convention that is supported.</li>
2019 <!-- *********************************************************************** -->
2021 <a name="assemblyPrinter">Assembly Printer</a>
2023 <!-- *********************************************************************** -->
2028 During the code emission stage, the code generator may utilize an LLVM pass to
2029 produce assembly output. To do this, you want to implement the code for a
2030 printer that converts LLVM IR to a GAS-format assembly language for your target
2031 machine, using the following steps:
2035 <li>Define all the assembly strings for your target, adding them to the
2036 instructions defined in the <tt>XXXInstrInfo.td</tt> file.
2037 (See <a href="#InstructionSet">Instruction Set</a>.) TableGen will produce
2038 an output file (<tt>XXXGenAsmWriter.inc</tt>) with an implementation of
2039 the <tt>printInstruction</tt> method for the XXXAsmPrinter class.</li>
2041 <li>Write <tt>XXXTargetAsmInfo.h</tt>, which contains the bare-bones declaration
2042 of the <tt>XXXTargetAsmInfo</tt> class (a subclass
2043 of <tt>TargetAsmInfo</tt>).</li>
2045 <li>Write <tt>XXXTargetAsmInfo.cpp</tt>, which contains target-specific values
2046 for <tt>TargetAsmInfo</tt> properties and sometimes new implementations for
2049 <li>Write <tt>XXXAsmPrinter.cpp</tt>, which implements the <tt>AsmPrinter</tt>
2050 class that performs the LLVM-to-assembly conversion.</li>
2054 The code in <tt>XXXTargetAsmInfo.h</tt> is usually a trivial declaration of the
2055 <tt>XXXTargetAsmInfo</tt> class for use in <tt>XXXTargetAsmInfo.cpp</tt>.
2056 Similarly, <tt>XXXTargetAsmInfo.cpp</tt> usually has a few declarations of
2057 <tt>XXXTargetAsmInfo</tt> replacement values that override the default values
2058 in <tt>TargetAsmInfo.cpp</tt>. For example in <tt>SparcTargetAsmInfo.cpp</tt>:
2061 <div class="doc_code">
2063 SparcTargetAsmInfo::SparcTargetAsmInfo(const SparcTargetMachine &TM) {
2064 Data16bitsDirective = "\t.half\t";
2065 Data32bitsDirective = "\t.word\t";
2066 Data64bitsDirective = 0; // .xword is only supported by V9.
2067 ZeroDirective = "\t.skip\t";
2068 CommentString = "!";
2069 ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
2075 The X86 assembly printer implementation (<tt>X86TargetAsmInfo</tt>) is an
2076 example where the target specific <tt>TargetAsmInfo</tt> class uses an
2077 overridden methods: <tt>ExpandInlineAsm</tt>.
2081 A target-specific implementation of AsmPrinter is written in
2082 <tt>XXXAsmPrinter.cpp</tt>, which implements the <tt>AsmPrinter</tt> class that
2083 converts the LLVM to printable assembly. The implementation must include the
2084 following headers that have declarations for the <tt>AsmPrinter</tt> and
2085 <tt>MachineFunctionPass</tt> classes. The <tt>MachineFunctionPass</tt> is a
2086 subclass of <tt>FunctionPass</tt>.
2089 <div class="doc_code">
2091 #include "llvm/CodeGen/AsmPrinter.h"
2092 #include "llvm/CodeGen/MachineFunctionPass.h"
2097 As a <tt>FunctionPass</tt>, <tt>AsmPrinter</tt> first
2098 calls <tt>doInitialization</tt> to set up the <tt>AsmPrinter</tt>. In
2099 <tt>SparcAsmPrinter</tt>, a <tt>Mangler</tt> object is instantiated to process
2104 In <tt>XXXAsmPrinter.cpp</tt>, the <tt>runOnMachineFunction</tt> method
2105 (declared in <tt>MachineFunctionPass</tt>) must be implemented
2106 for <tt>XXXAsmPrinter</tt>. In <tt>MachineFunctionPass</tt>,
2107 the <tt>runOnFunction</tt> method invokes <tt>runOnMachineFunction</tt>.
2108 Target-specific implementations of <tt>runOnMachineFunction</tt> differ, but
2109 generally do the following to process each machine function:
2113 <li>Call <tt>SetupMachineFunction</tt> to perform initialization.</li>
2115 <li>Call <tt>EmitConstantPool</tt> to print out (to the output stream) constants
2116 which have been spilled to memory.</li>
2118 <li>Call <tt>EmitJumpTableInfo</tt> to print out jump tables used by the current
2121 <li>Print out the label for the current function.</li>
2123 <li>Print out the code for the function, including basic block labels and the
2124 assembly for the instruction (using <tt>printInstruction</tt>)</li>
2128 The <tt>XXXAsmPrinter</tt> implementation must also include the code generated
2129 by TableGen that is output in the <tt>XXXGenAsmWriter.inc</tt> file. The code
2130 in <tt>XXXGenAsmWriter.inc</tt> contains an implementation of the
2131 <tt>printInstruction</tt> method that may call these methods:
2135 <li><tt>printOperand</tt></li>
2137 <li><tt>printMemOperand</tt></li>
2139 <li><tt>printCCOperand (for conditional statements)</tt></li>
2141 <li><tt>printDataDirective</tt></li>
2143 <li><tt>printDeclare</tt></li>
2145 <li><tt>printImplicitDef</tt></li>
2147 <li><tt>printInlineAsm</tt></li>
2151 The implementations of <tt>printDeclare</tt>, <tt>printImplicitDef</tt>,
2152 <tt>printInlineAsm</tt>, and <tt>printLabel</tt> in <tt>AsmPrinter.cpp</tt> are
2153 generally adequate for printing assembly and do not need to be
2158 The <tt>printOperand</tt> method is implemented with a long switch/case
2159 statement for the type of operand: register, immediate, basic block, external
2160 symbol, global address, constant pool index, or jump table index. For an
2161 instruction with a memory address operand, the <tt>printMemOperand</tt> method
2162 should be implemented to generate the proper output. Similarly,
2163 <tt>printCCOperand</tt> should be used to print a conditional operand.
2166 <p><tt>doFinalization</tt> should be overridden in <tt>XXXAsmPrinter</tt>, and
2167 it should be called to shut down the assembly printer. During
2168 <tt>doFinalization</tt>, global variables and constants are printed to
2174 <!-- *********************************************************************** -->
2176 <a name="subtargetSupport">Subtarget Support</a>
2178 <!-- *********************************************************************** -->
2183 Subtarget support is used to inform the code generation process of instruction
2184 set variations for a given chip set. For example, the LLVM SPARC implementation
2185 provided covers three major versions of the SPARC microprocessor architecture:
2186 Version 8 (V8, which is a 32-bit architecture), Version 9 (V9, a 64-bit
2187 architecture), and the UltraSPARC architecture. V8 has 16 double-precision
2188 floating-point registers that are also usable as either 32 single-precision or 8
2189 quad-precision registers. V8 is also purely big-endian. V9 has 32
2190 double-precision floating-point registers that are also usable as 16
2191 quad-precision registers, but cannot be used as single-precision registers. The
2192 UltraSPARC architecture combines V9 with UltraSPARC Visual Instruction Set
2197 If subtarget support is needed, you should implement a target-specific
2198 XXXSubtarget class for your architecture. This class should process the
2199 command-line options <tt>-mcpu=</tt> and <tt>-mattr=</tt>.
2203 TableGen uses definitions in the <tt>Target.td</tt> and <tt>Sparc.td</tt> files
2204 to generate code in <tt>SparcGenSubtarget.inc</tt>. In <tt>Target.td</tt>, shown
2205 below, the <tt>SubtargetFeature</tt> interface is defined. The first 4 string
2206 parameters of the <tt>SubtargetFeature</tt> interface are a feature name, an
2207 attribute set by the feature, the value of the attribute, and a description of
2208 the feature. (The fifth parameter is a list of features whose presence is
2209 implied, and its default value is an empty array.)
2212 <div class="doc_code">
2214 class SubtargetFeature<string n, string a, string v, string d,
2215 list<SubtargetFeature> i = []> {
2217 string Attribute = a;
2220 list<SubtargetFeature> Implies = i;
2226 In the <tt>Sparc.td</tt> file, the SubtargetFeature is used to define the
2230 <div class="doc_code">
2232 def FeatureV9 : SubtargetFeature<"v9", "IsV9", "true",
2233 "Enable SPARC-V9 instructions">;
2234 def FeatureV8Deprecated : SubtargetFeature<"deprecated-v8",
2235 "V8DeprecatedInsts", "true",
2236 "Enable deprecated V8 instructions in V9 mode">;
2237 def FeatureVIS : SubtargetFeature<"vis", "IsVIS", "true",
2238 "Enable UltraSPARC Visual Instruction Set extensions">;
2243 Elsewhere in <tt>Sparc.td</tt>, the Proc class is defined and then is used to
2244 define particular SPARC processor subtypes that may have the previously
2248 <div class="doc_code">
2250 class Proc<string Name, list<SubtargetFeature> Features>
2251 : Processor<Name, NoItineraries, Features>;
2253 def : Proc<"generic", []>;
2254 def : Proc<"v8", []>;
2255 def : Proc<"supersparc", []>;
2256 def : Proc<"sparclite", []>;
2257 def : Proc<"f934", []>;
2258 def : Proc<"hypersparc", []>;
2259 def : Proc<"sparclite86x", []>;
2260 def : Proc<"sparclet", []>;
2261 def : Proc<"tsc701", []>;
2262 def : Proc<"v9", [FeatureV9]>;
2263 def : Proc<"ultrasparc", [FeatureV9, FeatureV8Deprecated]>;
2264 def : Proc<"ultrasparc3", [FeatureV9, FeatureV8Deprecated]>;
2265 def : Proc<"ultrasparc3-vis", [FeatureV9, FeatureV8Deprecated, FeatureVIS]>;
2270 From <tt>Target.td</tt> and <tt>Sparc.td</tt> files, the resulting
2271 SparcGenSubtarget.inc specifies enum values to identify the features, arrays of
2272 constants to represent the CPU features and CPU subtypes, and the
2273 ParseSubtargetFeatures method that parses the features string that sets
2274 specified subtarget options. The generated <tt>SparcGenSubtarget.inc</tt> file
2275 should be included in the <tt>SparcSubtarget.cpp</tt>. The target-specific
2276 implementation of the XXXSubtarget method should follow this pseudocode:
2279 <div class="doc_code">
2281 XXXSubtarget::XXXSubtarget(const Module &M, const std::string &FS) {
2282 // Set the default features
2283 // Determine default and user specified characteristics of the CPU
2284 // Call ParseSubtargetFeatures(FS, CPU) to parse the features string
2285 // Perform any additional operations
2292 <!-- *********************************************************************** -->
2294 <a name="jitSupport">JIT Support</a>
2296 <!-- *********************************************************************** -->
2301 The implementation of a target machine optionally includes a Just-In-Time (JIT)
2302 code generator that emits machine code and auxiliary structures as binary output
2303 that can be written directly to memory. To do this, implement JIT code
2304 generation by performing the following steps:
2308 <li>Write an <tt>XXXCodeEmitter.cpp</tt> file that contains a machine function
2309 pass that transforms target-machine instructions into relocatable machine
2312 <li>Write an <tt>XXXJITInfo.cpp</tt> file that implements the JIT interfaces for
2313 target-specific code-generation activities, such as emitting machine code
2316 <li>Modify <tt>XXXTargetMachine</tt> so that it provides a
2317 <tt>TargetJITInfo</tt> object through its <tt>getJITInfo</tt> method.</li>
2321 There are several different approaches to writing the JIT support code. For
2322 instance, TableGen and target descriptor files may be used for creating a JIT
2323 code generator, but are not mandatory. For the Alpha and PowerPC target
2324 machines, TableGen is used to generate <tt>XXXGenCodeEmitter.inc</tt>, which
2325 contains the binary coding of machine instructions and the
2326 <tt>getBinaryCodeForInstr</tt> method to access those codes. Other JIT
2327 implementations do not.
2331 Both <tt>XXXJITInfo.cpp</tt> and <tt>XXXCodeEmitter.cpp</tt> must include the
2332 <tt>llvm/CodeGen/MachineCodeEmitter.h</tt> header file that defines the
2333 <tt>MachineCodeEmitter</tt> class containing code for several callback functions
2334 that write data (in bytes, words, strings, etc.) to the output stream.
2337 <!-- ======================================================================= -->
2339 <a name="mce">Machine Code Emitter</a>
2345 In <tt>XXXCodeEmitter.cpp</tt>, a target-specific of the <tt>Emitter</tt> class
2346 is implemented as a function pass (subclass
2347 of <tt>MachineFunctionPass</tt>). The target-specific implementation
2348 of <tt>runOnMachineFunction</tt> (invoked by
2349 <tt>runOnFunction</tt> in <tt>MachineFunctionPass</tt>) iterates through the
2350 <tt>MachineBasicBlock</tt> calls <tt>emitInstruction</tt> to process each
2351 instruction and emit binary code. <tt>emitInstruction</tt> is largely
2352 implemented with case statements on the instruction types defined in
2353 <tt>XXXInstrInfo.h</tt>. For example, in <tt>X86CodeEmitter.cpp</tt>,
2354 the <tt>emitInstruction</tt> method is built around the following switch/case
2358 <div class="doc_code">
2360 switch (Desc->TSFlags & X86::FormMask) {
2361 case X86II::Pseudo: // for not yet implemented instructions
2362 ... // or pseudo-instructions
2364 case X86II::RawFrm: // for instructions with a fixed opcode value
2367 case X86II::AddRegFrm: // for instructions that have one register operand
2368 ... // added to their opcode
2370 case X86II::MRMDestReg:// for instructions that use the Mod/RM byte
2371 ... // to specify a destination (register)
2373 case X86II::MRMDestMem:// for instructions that use the Mod/RM byte
2374 ... // to specify a destination (memory)
2376 case X86II::MRMSrcReg: // for instructions that use the Mod/RM byte
2377 ... // to specify a source (register)
2379 case X86II::MRMSrcMem: // for instructions that use the Mod/RM byte
2380 ... // to specify a source (memory)
2382 case X86II::MRM0r: case X86II::MRM1r: // for instructions that operate on
2383 case X86II::MRM2r: case X86II::MRM3r: // a REGISTER r/m operand and
2384 case X86II::MRM4r: case X86II::MRM5r: // use the Mod/RM byte and a field
2385 case X86II::MRM6r: case X86II::MRM7r: // to hold extended opcode data
2388 case X86II::MRM0m: case X86II::MRM1m: // for instructions that operate on
2389 case X86II::MRM2m: case X86II::MRM3m: // a MEMORY r/m operand and
2390 case X86II::MRM4m: case X86II::MRM5m: // use the Mod/RM byte and a field
2391 case X86II::MRM6m: case X86II::MRM7m: // to hold extended opcode data
2394 case X86II::MRMInitReg: // for instructions whose source and
2395 ... // destination are the same register
2402 The implementations of these case statements often first emit the opcode and
2403 then get the operand(s). Then depending upon the operand, helper methods may be
2404 called to process the operand(s). For example, in <tt>X86CodeEmitter.cpp</tt>,
2405 for the <tt>X86II::AddRegFrm</tt> case, the first data emitted
2406 (by <tt>emitByte</tt>) is the opcode added to the register operand. Then an
2407 object representing the machine operand, <tt>MO1</tt>, is extracted. The helper
2408 methods such as <tt>isImmediate</tt>,
2409 <tt>isGlobalAddress</tt>, <tt>isExternalSymbol</tt>, <tt>isConstantPoolIndex</tt>, and
2410 <tt>isJumpTableIndex</tt> determine the operand
2411 type. (<tt>X86CodeEmitter.cpp</tt> also has private methods such
2412 as <tt>emitConstant</tt>, <tt>emitGlobalAddress</tt>,
2413 <tt>emitExternalSymbolAddress</tt>, <tt>emitConstPoolAddress</tt>,
2414 and <tt>emitJumpTableAddress</tt> that emit the data into the output stream.)
2417 <div class="doc_code">
2419 case X86II::AddRegFrm:
2420 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
2422 if (CurOp != NumOps) {
2423 const MachineOperand &MO1 = MI.getOperand(CurOp++);
2424 unsigned Size = X86InstrInfo::sizeOfImm(Desc);
2425 if (MO1.isImmediate())
2426 emitConstant(MO1.getImm(), Size);
2428 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
2429 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
2430 if (Opcode == X86::MOV64ri)
2431 rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?
2432 if (MO1.isGlobalAddress()) {
2433 bool NeedStub = isa<Function>(MO1.getGlobal());
2434 bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());
2435 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
2437 } else if (MO1.isExternalSymbol())
2438 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
2439 else if (MO1.isConstantPoolIndex())
2440 emitConstPoolAddress(MO1.getIndex(), rt);
2441 else if (MO1.isJumpTableIndex())
2442 emitJumpTableAddress(MO1.getIndex(), rt);
2450 In the previous example, <tt>XXXCodeEmitter.cpp</tt> uses the
2451 variable <tt>rt</tt>, which is a RelocationType enum that may be used to
2452 relocate addresses (for example, a global address with a PIC base offset). The
2453 <tt>RelocationType</tt> enum for that target is defined in the short
2454 target-specific <tt>XXXRelocations.h</tt> file. The <tt>RelocationType</tt> is used by
2455 the <tt>relocate</tt> method defined in <tt>XXXJITInfo.cpp</tt> to rewrite
2456 addresses for referenced global symbols.
2460 For example, <tt>X86Relocations.h</tt> specifies the following relocation types
2461 for the X86 addresses. In all four cases, the relocated value is added to the
2462 value already in memory. For <tt>reloc_pcrel_word</tt>
2463 and <tt>reloc_picrel_word</tt>, there is an additional initial adjustment.
2466 <div class="doc_code">
2468 enum RelocationType {
2469 reloc_pcrel_word = 0, // add reloc value after adjusting for the PC loc
2470 reloc_picrel_word = 1, // add reloc value after adjusting for the PIC base
2471 reloc_absolute_word = 2, // absolute relocation; no additional adjustment
2472 reloc_absolute_dword = 3 // absolute relocation; no additional adjustment
2479 <!-- ======================================================================= -->
2481 <a name="targetJITInfo">Target JIT Info</a>
2487 <tt>XXXJITInfo.cpp</tt> implements the JIT interfaces for target-specific
2488 code-generation activities, such as emitting machine code and stubs. At minimum,
2489 a target-specific version of <tt>XXXJITInfo</tt> implements the following:
2493 <li><tt>getLazyResolverFunction</tt> — Initializes the JIT, gives the
2494 target a function that is used for compilation.</li>
2496 <li><tt>emitFunctionStub</tt> — Returns a native function with a specified
2497 address for a callback function.</li>
2499 <li><tt>relocate</tt> — Changes the addresses of referenced globals, based
2500 on relocation types.</li>
2502 <li>Callback function that are wrappers to a function stub that is used when the
2503 real target is not initially known.</li>
2507 <tt>getLazyResolverFunction</tt> is generally trivial to implement. It makes the
2508 incoming parameter as the global <tt>JITCompilerFunction</tt> and returns the
2509 callback function that will be used a function wrapper. For the Alpha target
2510 (in <tt>AlphaJITInfo.cpp</tt>), the <tt>getLazyResolverFunction</tt>
2511 implementation is simply:
2514 <div class="doc_code">
2516 TargetJITInfo::LazyResolverFn AlphaJITInfo::getLazyResolverFunction(
2518 JITCompilerFunction = F;
2519 return AlphaCompilationCallback;
2525 For the X86 target, the <tt>getLazyResolverFunction</tt> implementation is a
2526 little more complication, because it returns a different callback function for
2527 processors with SSE instructions and XMM registers.
2531 The callback function initially saves and later restores the callee register
2532 values, incoming arguments, and frame and return address. The callback function
2533 needs low-level access to the registers or stack, so it is typically implemented
2541 <!-- *********************************************************************** -->
2545 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
2546 src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
2547 <a href="http://validator.w3.org/check/referer"><img
2548 src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
2550 <a href="http://www.woo.com">Mason Woo</a> and <a href="http://misha.brukman.net">Misha Brukman</a><br>
2551 <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a>
2553 Last modified: $Date$