forked from llvm-mirror/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WritingAnLLVMBackend.html
2557 lines (2161 loc) · 90.7 KB
/
WritingAnLLVMBackend.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Writing an LLVM Compiler Backend</title>
<link rel="stylesheet" href="_static/llvm.css" type="text/css">
</head>
<body>
<h1>
Writing an LLVM Compiler Backend
</h1>
<ol>
<li><a href="#intro">Introduction</a>
<ul>
<li><a href="#Audience">Audience</a></li>
<li><a href="#Prerequisite">Prerequisite Reading</a></li>
<li><a href="#Basic">Basic Steps</a></li>
<li><a href="#Preliminaries">Preliminaries</a></li>
</ul>
<li><a href="#TargetMachine">Target Machine</a></li>
<li><a href="#TargetRegistration">Target Registration</a></li>
<li><a href="#RegisterSet">Register Set and Register Classes</a>
<ul>
<li><a href="#RegisterDef">Defining a Register</a></li>
<li><a href="#RegisterClassDef">Defining a Register Class</a></li>
<li><a href="#implementRegister">Implement a subclass of TargetRegisterInfo</a></li>
</ul></li>
<li><a href="#InstructionSet">Instruction Set</a>
<ul>
<li><a href="#operandMapping">Instruction Operand Mapping</a></li>
<li><a href="#relationMapping">Instruction Relation Mapping</a></li>
<li><a href="#implementInstr">Implement a subclass of TargetInstrInfo</a></li>
<li><a href="#branchFolding">Branch Folding and If Conversion</a></li>
</ul></li>
<li><a href="#InstructionSelector">Instruction Selector</a>
<ul>
<li><a href="#LegalizePhase">The SelectionDAG Legalize Phase</a>
<ul>
<li><a href="#promote">Promote</a></li>
<li><a href="#expand">Expand</a></li>
<li><a href="#custom">Custom</a></li>
<li><a href="#legal">Legal</a></li>
</ul></li>
<li><a href="#callingConventions">Calling Conventions</a></li>
</ul></li>
<li><a href="#assemblyPrinter">Assembly Printer</a></li>
<li><a href="#subtargetSupport">Subtarget Support</a></li>
<li><a href="#jitSupport">JIT Support</a>
<ul>
<li><a href="#mce">Machine Code Emitter</a></li>
<li><a href="#targetJITInfo">Target JIT Info</a></li>
</ul></li>
</ol>
<div class="doc_author">
<p>Written by <a href="http://www.woo.com">Mason Woo</a> and
<a href="http://misha.brukman.net">Misha Brukman</a></p>
</div>
<!-- *********************************************************************** -->
<h2>
<a name="intro">Introduction</a>
</h2>
<!-- *********************************************************************** -->
<div>
<p>
This document describes techniques for writing compiler backends that convert
the LLVM Intermediate Representation (IR) to code for a specified machine or
other languages. Code intended for a specific machine can take the form of
either assembly code or binary code (usable for a JIT compiler).
</p>
<p>
The backend of LLVM features a target-independent code generator that may create
output for several types of target CPUs — including X86, PowerPC, ARM,
and SPARC. The backend may also be used to generate code targeted at SPUs of the
Cell processor or GPUs to support the execution of compute kernels.
</p>
<p>
The document focuses on existing examples found in subdirectories
of <tt>llvm/lib/Target</tt> in a downloaded LLVM release. In particular, this
document focuses on the example of creating a static compiler (one that emits
text assembly) for a SPARC target, because SPARC has fairly standard
characteristics, such as a RISC instruction set and straightforward calling
conventions.
</p>
<h3>
<a name="Audience">Audience</a>
</h3>
<div>
<p>
The audience for this document is anyone who needs to write an LLVM backend to
generate code for a specific hardware or software target.
</p>
</div>
<h3>
<a name="Prerequisite">Prerequisite Reading</a>
</h3>
<div>
<p>
These essential documents must be read before reading this document:
</p>
<ul>
<li><i><a href="LangRef.html">LLVM Language Reference
Manual</a></i> — a reference manual for the LLVM assembly language.</li>
<li><i><a href="CodeGenerator.html">The LLVM
Target-Independent Code Generator</a></i> — a guide to the components
(classes and code generation algorithms) for translating the LLVM internal
representation into machine code for a specified target. Pay particular
attention to the descriptions of code generation stages: Instruction
Selection, Scheduling and Formation, SSA-based Optimization, Register
Allocation, Prolog/Epilog Code Insertion, Late Machine Code Optimizations,
and Code Emission.</li>
<li><i><a href="TableGenFundamentals.html">TableGen
Fundamentals</a></i> —a document that describes the TableGen
(<tt>tblgen</tt>) application that manages domain-specific information to
support LLVM code generation. TableGen processes input from a target
description file (<tt>.td</tt> suffix) and generates C++ code that can be
used for code generation.</li>
<li><i><a href="WritingAnLLVMPass.html">Writing an LLVM
Pass</a></i> — The assembly printer is a <tt>FunctionPass</tt>, as are
several SelectionDAG processing steps.</li>
</ul>
<p>
To follow the SPARC examples in this document, have a copy of
<i><a href="http://www.sparc.org/standards/V8.pdf">The SPARC Architecture
Manual, Version 8</a></i> for reference. For details about the ARM instruction
set, refer to the <i><a href="http://infocenter.arm.com/">ARM Architecture
Reference Manual</a></i>. For more about the GNU Assembler format
(<tt>GAS</tt>), see
<i><a href="http://sourceware.org/binutils/docs/as/index.html">Using As</a></i>,
especially for the assembly printer. <i>Using As</i> contains a list of target
machine dependent features.
</p>
</div>
<h3>
<a name="Basic">Basic Steps</a>
</h3>
<div>
<p>
To write a compiler backend for LLVM that converts the LLVM IR to code for a
specified target (machine or other language), follow these steps:
</p>
<ul>
<li>Create a subclass of the TargetMachine class that describes characteristics
of your target machine. Copy existing examples of specific TargetMachine
class and header files; for example, start with
<tt>SparcTargetMachine.cpp</tt> and <tt>SparcTargetMachine.h</tt>, but
change the file names for your target. Similarly, change code that
references "Sparc" to reference your target. </li>
<li>Describe the register set of the target. Use TableGen to generate code for
register definition, register aliases, and register classes from a
target-specific <tt>RegisterInfo.td</tt> input file. You should also write
additional code for a subclass of the TargetRegisterInfo class that
represents the class register file data used for register allocation and
also describes the interactions between registers.</li>
<li>Describe the instruction set of the target. Use TableGen to generate code
for target-specific instructions from target-specific versions of
<tt>TargetInstrFormats.td</tt> and <tt>TargetInstrInfo.td</tt>. You should
write additional code for a subclass of the TargetInstrInfo class to
represent machine instructions supported by the target machine. </li>
<li>Describe the selection and conversion of the LLVM IR from a Directed Acyclic
Graph (DAG) representation of instructions to native target-specific
instructions. Use TableGen to generate code that matches patterns and
selects instructions based on additional information in a target-specific
version of <tt>TargetInstrInfo.td</tt>. Write code
for <tt>XXXISelDAGToDAG.cpp</tt>, where XXX identifies the specific target,
to perform pattern matching and DAG-to-DAG instruction selection. Also write
code in <tt>XXXISelLowering.cpp</tt> to replace or remove operations and
data types that are not supported natively in a SelectionDAG. </li>
<li>Write code for an assembly printer that converts LLVM IR to a GAS format for
your target machine. You should add assembly strings to the instructions
defined in your target-specific version of <tt>TargetInstrInfo.td</tt>. You
should also write code for a subclass of AsmPrinter that performs the
LLVM-to-assembly conversion and a trivial subclass of TargetAsmInfo.</li>
<li>Optionally, add support for subtargets (i.e., variants with different
capabilities). You should also write code for a subclass of the
TargetSubtarget class, which allows you to use the <tt>-mcpu=</tt>
and <tt>-mattr=</tt> command-line options.</li>
<li>Optionally, add JIT support and create a machine code emitter (subclass of
TargetJITInfo) that is used to emit binary code directly into memory. </li>
</ul>
<p>
In the <tt>.cpp</tt> and <tt>.h</tt>. files, initially stub up these methods and
then implement them later. Initially, you may not know which private members
that the class will need and which components will need to be subclassed.
</p>
</div>
<h3>
<a name="Preliminaries">Preliminaries</a>
</h3>
<div>
<p>
To actually create your compiler backend, you need to create and modify a few
files. The absolute minimum is discussed here. But to actually use the LLVM
target-independent code generator, you must perform the steps described in
the <a href="CodeGenerator.html">LLVM
Target-Independent Code Generator</a> document.
</p>
<p>
First, you should create a subdirectory under <tt>lib/Target</tt> to hold all
the files related to your target. If your target is called "Dummy," create the
directory <tt>lib/Target/Dummy</tt>.
</p>
<p>
In this new
directory, create a <tt>Makefile</tt>. It is easiest to copy a
<tt>Makefile</tt> of another target and modify it. It should at least contain
the <tt>LEVEL</tt>, <tt>LIBRARYNAME</tt> and <tt>TARGET</tt> variables, and then
include <tt>$(LEVEL)/Makefile.common</tt>. The library can be
named <tt>LLVMDummy</tt> (for example, see the MIPS target). Alternatively, you
can split the library into <tt>LLVMDummyCodeGen</tt>
and <tt>LLVMDummyAsmPrinter</tt>, the latter of which should be implemented in a
subdirectory below <tt>lib/Target/Dummy</tt> (for example, see the PowerPC
target).
</p>
<p>
Note that these two naming schemes are hardcoded into <tt>llvm-config</tt>.
Using any other naming scheme will confuse <tt>llvm-config</tt> and produce a
lot of (seemingly unrelated) linker errors when linking <tt>llc</tt>.
</p>
<p>
To make your target actually do something, you need to implement a subclass of
<tt>TargetMachine</tt>. This implementation should typically be in the file
<tt>lib/Target/DummyTargetMachine.cpp</tt>, but any file in
the <tt>lib/Target</tt> directory will be built and should work. To use LLVM's
target independent code generator, you should do what all current machine
backends do: create a subclass of <tt>LLVMTargetMachine</tt>. (To create a
target from scratch, create a subclass of <tt>TargetMachine</tt>.)
</p>
<p>
To get LLVM to actually build and link your target, you need to add it to
the <tt>TARGETS_TO_BUILD</tt> variable. To do this, you modify the configure
script to know about your target when parsing the <tt>--enable-targets</tt>
option. Search the configure script for <tt>TARGETS_TO_BUILD</tt>, add your
target to the lists there (some creativity required), and then
reconfigure. Alternatively, you can change <tt>autotools/configure.ac</tt> and
regenerate configure by running <tt>./autoconf/AutoRegen.sh</tt>.
</p>
</div>
</div>
<!-- *********************************************************************** -->
<h2>
<a name="TargetMachine">Target Machine</a>
</h2>
<!-- *********************************************************************** -->
<div>
<p>
<tt>LLVMTargetMachine</tt> is designed as a base class for targets implemented
with the LLVM target-independent code generator. The <tt>LLVMTargetMachine</tt>
class should be specialized by a concrete target class that implements the
various virtual methods. <tt>LLVMTargetMachine</tt> is defined as a subclass of
<tt>TargetMachine</tt> in <tt>include/llvm/Target/TargetMachine.h</tt>. The
<tt>TargetMachine</tt> class implementation (<tt>TargetMachine.cpp</tt>) also
processes numerous command-line options.
</p>
<p>
To create a concrete target-specific subclass of <tt>LLVMTargetMachine</tt>,
start by copying an existing <tt>TargetMachine</tt> class and header. You
should name the files that you create to reflect your specific target. For
instance, for the SPARC target, name the files <tt>SparcTargetMachine.h</tt> and
<tt>SparcTargetMachine.cpp</tt>.
</p>
<p>
For a target machine <tt>XXX</tt>, the implementation of
<tt>XXXTargetMachine</tt> must have access methods to obtain objects that
represent target components. These methods are named <tt>get*Info</tt>, and are
intended to obtain the instruction set (<tt>getInstrInfo</tt>), register set
(<tt>getRegisterInfo</tt>), stack frame layout (<tt>getFrameInfo</tt>), and
similar information. <tt>XXXTargetMachine</tt> must also implement the
<tt>getDataLayout</tt> method to access an object with target-specific data
characteristics, such as data type size and alignment requirements.
</p>
<p>
For instance, for the SPARC target, the header file
<tt>SparcTargetMachine.h</tt> declares prototypes for several <tt>get*Info</tt>
and <tt>getDataLayout</tt> methods that simply return a class member.
</p>
<div class="doc_code">
<pre>
namespace llvm {
class Module;
class SparcTargetMachine : public LLVMTargetMachine {
const DataLayout DataLayout; // Calculates type size & alignment
SparcSubtarget Subtarget;
SparcInstrInfo InstrInfo;
TargetFrameInfo FrameInfo;
protected:
virtual const TargetAsmInfo *createTargetAsmInfo() const;
public:
SparcTargetMachine(const Module &M, const std::string &FS);
virtual const SparcInstrInfo *getInstrInfo() const {return &InstrInfo; }
virtual const TargetFrameInfo *getFrameInfo() const {return &FrameInfo; }
virtual const TargetSubtarget *getSubtargetImpl() const{return &Subtarget; }
virtual const TargetRegisterInfo *getRegisterInfo() const {
return &InstrInfo.getRegisterInfo();
}
virtual const DataLayout *getDataLayout() const { return &DataLayout; }
static unsigned getModuleMatchQuality(const Module &M);
// Pass Pipeline Configuration
virtual bool addInstSelector(PassManagerBase &PM, bool Fast);
virtual bool addPreEmitPass(PassManagerBase &PM, bool Fast);
};
} // end namespace llvm
</pre>
</div>
<ul>
<li><tt>getInstrInfo()</tt></li>
<li><tt>getRegisterInfo()</tt></li>
<li><tt>getFrameInfo()</tt></li>
<li><tt>getDataLayout()</tt></li>
<li><tt>getSubtargetImpl()</tt></li>
</ul>
<p>For some targets, you also need to support the following methods:</p>
<ul>
<li><tt>getTargetLowering()</tt></li>
<li><tt>getJITInfo()</tt></li>
</ul>
<p>
In addition, the <tt>XXXTargetMachine</tt> constructor should specify a
<tt>TargetDescription</tt> string that determines the data layout for the target
machine, including characteristics such as pointer size, alignment, and
endianness. For example, the constructor for SparcTargetMachine contains the
following:
</p>
<div class="doc_code">
<pre>
SparcTargetMachine::SparcTargetMachine(const Module &M, const std::string &FS)
: DataLayout("E-p:32:32-f128:128:128"),
Subtarget(M, FS), InstrInfo(Subtarget),
FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
}
</pre>
</div>
<p>Hyphens separate portions of the <tt>TargetDescription</tt> string.</p>
<ul>
<li>An upper-case "<tt>E</tt>" in the string indicates a big-endian target data
model. a lower-case "<tt>e</tt>" indicates little-endian.</li>
<li>"<tt>p:</tt>" is followed by pointer information: size, ABI alignment, and
preferred alignment. If only two figures follow "<tt>p:</tt>", then the
first value is pointer size, and the second value is both ABI and preferred
alignment.</li>
<li>Then a letter for numeric type alignment: "<tt>i</tt>", "<tt>f</tt>",
"<tt>v</tt>", or "<tt>a</tt>" (corresponding to integer, floating point,
vector, or aggregate). "<tt>i</tt>", "<tt>v</tt>", or "<tt>a</tt>" are
followed by ABI alignment and preferred alignment. "<tt>f</tt>" is followed
by three values: the first indicates the size of a long double, then ABI
alignment, and then ABI preferred alignment.</li>
</ul>
</div>
<!-- *********************************************************************** -->
<h2>
<a name="TargetRegistration">Target Registration</a>
</h2>
<!-- *********************************************************************** -->
<div>
<p>
You must also register your target with the <tt>TargetRegistry</tt>, which is
what other LLVM tools use to be able to lookup and use your target at
runtime. The <tt>TargetRegistry</tt> can be used directly, but for most targets
there are helper templates which should take care of the work for you.</p>
<p>
All targets should declare a global <tt>Target</tt> object which is used to
represent the target during registration. Then, in the target's TargetInfo
library, the target should define that object and use
the <tt>RegisterTarget</tt> template to register the target. For example, the Sparc registration code looks like this:
</p>
<div class="doc_code">
<pre>
Target llvm::TheSparcTarget;
extern "C" void LLVMInitializeSparcTargetInfo() {
RegisterTarget<Triple::sparc, /*HasJIT=*/false>
X(TheSparcTarget, "sparc", "Sparc");
}
</pre>
</div>
<p>
This allows the <tt>TargetRegistry</tt> to look up the target by name or by
target triple. In addition, most targets will also register additional features
which are available in separate libraries. These registration steps are
separate, because some clients may wish to only link in some parts of the target
-- the JIT code generator does not require the use of the assembler printer, for
example. Here is an example of registering the Sparc assembly printer:
</p>
<div class="doc_code">
<pre>
extern "C" void LLVMInitializeSparcAsmPrinter() {
RegisterAsmPrinter<SparcAsmPrinter> X(TheSparcTarget);
}
</pre>
</div>
<p>
For more information, see
"<a href="/doxygen/TargetRegistry_8h-source.html">llvm/Target/TargetRegistry.h</a>".
</p>
</div>
<!-- *********************************************************************** -->
<h2>
<a name="RegisterSet">Register Set and Register Classes</a>
</h2>
<!-- *********************************************************************** -->
<div>
<p>
You should describe a concrete target-specific class that represents the
register file of a target machine. This class is called <tt>XXXRegisterInfo</tt>
(where <tt>XXX</tt> identifies the target) and represents the class register
file data that is used for register allocation. It also describes the
interactions between registers.
</p>
<p>
You also need to define register classes to categorize related registers. A
register class should be added for groups of registers that are all treated the
same way for some instruction. Typical examples are register classes for
integer, floating-point, or vector registers. A register allocator allows an
instruction to use any register in a specified register class to perform the
instruction in a similar manner. Register classes allocate virtual registers to
instructions from these sets, and register classes let the target-independent
register allocator automatically choose the actual registers.
</p>
<p>
Much of the code for registers, including register definition, register aliases,
and register classes, is generated by TableGen from <tt>XXXRegisterInfo.td</tt>
input files and placed in <tt>XXXGenRegisterInfo.h.inc</tt> and
<tt>XXXGenRegisterInfo.inc</tt> output files. Some of the code in the
implementation of <tt>XXXRegisterInfo</tt> requires hand-coding.
</p>
<!-- ======================================================================= -->
<h3>
<a name="RegisterDef">Defining a Register</a>
</h3>
<div>
<p>
The <tt>XXXRegisterInfo.td</tt> file typically starts with register definitions
for a target machine. The <tt>Register</tt> class (specified
in <tt>Target.td</tt>) is used to define an object for each register. The
specified string <tt>n</tt> becomes the <tt>Name</tt> of the register. The
basic <tt>Register</tt> object does not have any subregisters and does not
specify any aliases.
</p>
<div class="doc_code">
<pre>
class Register<string n> {
string Namespace = "";
string AsmName = n;
string Name = n;
int SpillSize = 0;
int SpillAlignment = 0;
list<Register> Aliases = [];
list<Register> SubRegs = [];
list<int> DwarfNumbers = [];
}
</pre>
</div>
<p>
For example, in the <tt>X86RegisterInfo.td</tt> file, there are register
definitions that utilize the Register class, such as:
</p>
<div class="doc_code">
<pre>
def AL : Register<"AL">, DwarfRegNum<[0, 0, 0]>;
</pre>
</div>
<p>
This defines the register <tt>AL</tt> and assigns it values (with
<tt>DwarfRegNum</tt>) that are used by <tt>gcc</tt>, <tt>gdb</tt>, or a debug
information writer to identify a register. For register
<tt>AL</tt>, <tt>DwarfRegNum</tt> takes an array of 3 values representing 3
different modes: the first element is for X86-64, the second for exception
handling (EH) on X86-32, and the third is generic. -1 is a special Dwarf number
that indicates the gcc number is undefined, and -2 indicates the register number
is invalid for this mode.
</p>
<p>
From the previously described line in the <tt>X86RegisterInfo.td</tt> file,
TableGen generates this code in the <tt>X86GenRegisterInfo.inc</tt> file:
</p>
<div class="doc_code">
<pre>
static const unsigned GR8[] = { X86::AL, ... };
const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 };
const TargetRegisterDesc RegisterDescriptors[] = {
...
{ "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ...
</pre>
</div>
<p>
From the register info file, TableGen generates a <tt>TargetRegisterDesc</tt>
object for each register. <tt>TargetRegisterDesc</tt> is defined in
<tt>include/llvm/Target/TargetRegisterInfo.h</tt> with the following fields:
</p>
<div class="doc_code">
<pre>
struct TargetRegisterDesc {
const char *AsmName; // Assembly language name for the register
const char *Name; // Printable name for the reg (for debugging)
const unsigned *AliasSet; // Register Alias Set
const unsigned *SubRegs; // Sub-register set
const unsigned *ImmSubRegs; // Immediate sub-register set
const unsigned *SuperRegs; // Super-register set
};</pre>
</div>
<p>
TableGen uses the entire target description file (<tt>.td</tt>) to determine
text names for the register (in the <tt>AsmName</tt> and <tt>Name</tt> fields of
<tt>TargetRegisterDesc</tt>) and the relationships of other registers to the
defined register (in the other <tt>TargetRegisterDesc</tt> fields). In this
example, other definitions establish the registers "<tt>AX</tt>",
"<tt>EAX</tt>", and "<tt>RAX</tt>" as aliases for one another, so TableGen
generates a null-terminated array (<tt>AL_AliasSet</tt>) for this register alias
set.
</p>
<p>
The <tt>Register</tt> class is commonly used as a base class for more complex
classes. In <tt>Target.td</tt>, the <tt>Register</tt> class is the base for the
<tt>RegisterWithSubRegs</tt> class that is used to define registers that need to
specify subregisters in the <tt>SubRegs</tt> list, as shown here:
</p>
<div class="doc_code">
<pre>
class RegisterWithSubRegs<string n,
list<Register> subregs> : Register<n> {
let SubRegs = subregs;
}
</pre>
</div>
<p>
In <tt>SparcRegisterInfo.td</tt>, additional register classes are defined for
SPARC: a Register subclass, SparcReg, and further subclasses: <tt>Ri</tt>,
<tt>Rf</tt>, and <tt>Rd</tt>. SPARC registers are identified by 5-bit ID
numbers, which is a feature common to these subclasses. Note the use of
'<tt>let</tt>' expressions to override values that are initially defined in a
superclass (such as <tt>SubRegs</tt> field in the <tt>Rd</tt> class).
</p>
<div class="doc_code">
<pre>
class SparcReg<string n> : Register<n> {
field bits<5> Num;
let Namespace = "SP";
}
// Ri - 32-bit integer registers
class Ri<bits<5> num, string n> :
SparcReg<n> {
let Num = num;
}
// Rf - 32-bit floating-point registers
class Rf<bits<5> num, string n> :
SparcReg<n> {
let Num = num;
}
// Rd - Slots in the FP register file for 64-bit
floating-point values.
class Rd<bits<5> num, string n,
list<Register> subregs> : SparcReg<n> {
let Num = num;
let SubRegs = subregs;
}
</pre>
</div>
<p>
In the <tt>SparcRegisterInfo.td</tt> file, there are register definitions that
utilize these subclasses of <tt>Register</tt>, such as:
</p>
<div class="doc_code">
<pre>
def G0 : Ri< 0, "G0">,
DwarfRegNum<[0]>;
def G1 : Ri< 1, "G1">, DwarfRegNum<[1]>;
...
def F0 : Rf< 0, "F0">,
DwarfRegNum<[32]>;
def F1 : Rf< 1, "F1">,
DwarfRegNum<[33]>;
...
def D0 : Rd< 0, "F0", [F0, F1]>,
DwarfRegNum<[32]>;
def D1 : Rd< 2, "F2", [F2, F3]>,
DwarfRegNum<[34]>;
</pre>
</div>
<p>
The last two registers shown above (<tt>D0</tt> and <tt>D1</tt>) are
double-precision floating-point registers that are aliases for pairs of
single-precision floating-point sub-registers. In addition to aliases, the
sub-register and super-register relationships of the defined register are in
fields of a register's TargetRegisterDesc.
</p>
</div>
<!-- ======================================================================= -->
<h3>
<a name="RegisterClassDef">Defining a Register Class</a>
</h3>
<div>
<p>
The <tt>RegisterClass</tt> class (specified in <tt>Target.td</tt>) is used to
define an object that represents a group of related registers and also defines
the default allocation order of the registers. A target description file
<tt>XXXRegisterInfo.td</tt> that uses <tt>Target.td</tt> can construct register
classes using the following class:
</p>
<div class="doc_code">
<pre>
class RegisterClass<string namespace,
list<ValueType> regTypes, int alignment, dag regList> {
string Namespace = namespace;
list<ValueType> RegTypes = regTypes;
int Size = 0; // spill size, in bits; zero lets tblgen pick the size
int Alignment = alignment;
// CopyCost is the cost of copying a value between two registers
// default value 1 means a single instruction
// A negative value means copying is extremely expensive or impossible
int CopyCost = 1;
dag MemberList = regList;
// for register classes that are subregisters of this class
list<RegisterClass> SubRegClassList = [];
code MethodProtos = [{}]; // to insert arbitrary code
code MethodBodies = [{}];
}
</pre>
</div>
<p>To define a RegisterClass, use the following 4 arguments:</p>
<ul>
<li>The first argument of the definition is the name of the namespace.</li>
<li>The second argument is a list of <tt>ValueType</tt> register type values
that are defined in <tt>include/llvm/CodeGen/ValueTypes.td</tt>. Defined
values include integer types (such as <tt>i16</tt>, <tt>i32</tt>,
and <tt>i1</tt> for Boolean), floating-point types
(<tt>f32</tt>, <tt>f64</tt>), and vector types (for example, <tt>v8i16</tt>
for an <tt>8 x i16</tt> vector). All registers in a <tt>RegisterClass</tt>
must have the same <tt>ValueType</tt>, but some registers may store vector
data in different configurations. For example a register that can process a
128-bit vector may be able to handle 16 8-bit integer elements, 8 16-bit
integers, 4 32-bit integers, and so on. </li>
<li>The third argument of the <tt>RegisterClass</tt> definition specifies the
alignment required of the registers when they are stored or loaded to
memory.</li>
<li>The final argument, <tt>regList</tt>, specifies which registers are in this
class. If an alternative allocation order method is not specified, then
<tt>regList</tt> also defines the order of allocation used by the register
allocator. Besides simply listing registers with <tt>(add R0, R1, ...)</tt>,
more advanced set operators are available. See
<tt>include/llvm/Target/Target.td</tt> for more information.</li>
</ul>
<p>
In <tt>SparcRegisterInfo.td</tt>, three RegisterClass objects are defined:
<tt>FPRegs</tt>, <tt>DFPRegs</tt>, and <tt>IntRegs</tt>. For all three register
classes, the first argument defines the namespace with the string
'<tt>SP</tt>'. <tt>FPRegs</tt> defines a group of 32 single-precision
floating-point registers (<tt>F0</tt> to <tt>F31</tt>); <tt>DFPRegs</tt> defines
a group of 16 double-precision registers
(<tt>D0-D15</tt>).
</p>
<div class="doc_code">
<pre>
// F0, F1, F2, ..., F31
def FPRegs : RegisterClass<"SP", [f32], 32, (sequence "F%u", 0, 31)>;
def DFPRegs : RegisterClass<"SP", [f64], 64,
(add D0, D1, D2, D3, D4, D5, D6, D7, D8,
D9, D10, D11, D12, D13, D14, D15)>;
def IntRegs : RegisterClass<"SP", [i32], 32,
(add L0, L1, L2, L3, L4, L5, L6, L7,
I0, I1, I2, I3, I4, I5,
O0, O1, O2, O3, O4, O5, O7,
G1,
// Non-allocatable regs:
G2, G3, G4,
O6, // stack ptr
I6, // frame ptr
I7, // return address
G0, // constant zero
G5, G6, G7 // reserved for kernel
)>;
</pre>
</div>
<p>
Using <tt>SparcRegisterInfo.td</tt> with TableGen generates several output files
that are intended for inclusion in other source code that you write.
<tt>SparcRegisterInfo.td</tt> generates <tt>SparcGenRegisterInfo.h.inc</tt>,
which should be included in the header file for the implementation of the SPARC
register implementation that you write (<tt>SparcRegisterInfo.h</tt>). In
<tt>SparcGenRegisterInfo.h.inc</tt> a new structure is defined called
<tt>SparcGenRegisterInfo</tt> that uses <tt>TargetRegisterInfo</tt> as its
base. It also specifies types, based upon the defined register
classes: <tt>DFPRegsClass</tt>, <tt>FPRegsClass</tt>, and <tt>IntRegsClass</tt>.
</p>
<p>
<tt>SparcRegisterInfo.td</tt> also generates <tt>SparcGenRegisterInfo.inc</tt>,
which is included at the bottom of <tt>SparcRegisterInfo.cpp</tt>, the SPARC
register implementation. The code below shows only the generated integer
registers and associated register classes. The order of registers
in <tt>IntRegs</tt> reflects the order in the definition of <tt>IntRegs</tt> in
the target description file.
</p>
<div class="doc_code">
<pre> // IntRegs Register Class...
static const unsigned IntRegs[] = {
SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5,
SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3,
SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3,
SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3,
SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5,
SP::G6, SP::G7,
};
// IntRegsVTs Register Class Value Types...
static const MVT::ValueType IntRegsVTs[] = {
MVT::i32, MVT::Other
};
namespace SP { // Register class instances
DFPRegsClass DFPRegsRegClass;
FPRegsClass FPRegsRegClass;
IntRegsClass IntRegsRegClass;
...
// IntRegs Sub-register Classess...
static const TargetRegisterClass* const IntRegsSubRegClasses [] = {
NULL
};
...
// IntRegs Super-register Classess...
static const TargetRegisterClass* const IntRegsSuperRegClasses [] = {
NULL
};
...
// IntRegs Register Class sub-classes...
static const TargetRegisterClass* const IntRegsSubclasses [] = {
NULL
};
...
// IntRegs Register Class super-classes...
static const TargetRegisterClass* const IntRegsSuperclasses [] = {
NULL
};
IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID,
IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses,
IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {}
}
</pre>
</div>
<p>
The register allocators will avoid using reserved registers, and callee saved
registers are not used until all the volatile registers have been used. That
is usually good enough, but in some cases it may be necessary to provide custom
allocation orders.
</p>
</div>
<!-- ======================================================================= -->
<h3>
<a name="implementRegister">Implement a subclass of</a>
<a href="CodeGenerator.html#targetregisterinfo">TargetRegisterInfo</a>
</h3>
<div>
<p>
The final step is to hand code portions of <tt>XXXRegisterInfo</tt>, which
implements the interface described in <tt>TargetRegisterInfo.h</tt>. These
functions return <tt>0</tt>, <tt>NULL</tt>, or <tt>false</tt>, unless
overridden. Here is a list of functions that are overridden for the SPARC
implementation in <tt>SparcRegisterInfo.cpp</tt>:
</p>
<ul>
<li><tt>getCalleeSavedRegs</tt> — Returns a list of callee-saved registers
in the order of the desired callee-save stack frame offset.</li>
<li><tt>getReservedRegs</tt> — Returns a bitset indexed by physical
register numbers, indicating if a particular register is unavailable.</li>
<li><tt>hasFP</tt> — Return a Boolean indicating if a function should have
a dedicated frame pointer register.</li>
<li><tt>eliminateCallFramePseudoInstr</tt> — If call frame setup or
destroy pseudo instructions are used, this can be called to eliminate
them.</li>
<li><tt>eliminateFrameIndex</tt> — Eliminate abstract frame indices from
instructions that may use them.</li>
<li><tt>emitPrologue</tt> — Insert prologue code into the function.</li>
<li><tt>emitEpilogue</tt> — Insert epilogue code into the function.</li>
</ul>
</div>
</div>
<!-- *********************************************************************** -->
<h2>
<a name="InstructionSet">Instruction Set</a>
</h2>
<!-- *********************************************************************** -->
<div>
<p>
During the early stages of code generation, the LLVM IR code is converted to a
<tt>SelectionDAG</tt> with nodes that are instances of the <tt>SDNode</tt> class
containing target instructions. An <tt>SDNode</tt> has an opcode, operands, type
requirements, and operation properties. For example, is an operation
commutative, does an operation load from memory. The various operation node
types are described in the <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>
file (values of the <tt>NodeType</tt> enum in the <tt>ISD</tt> namespace).
</p>
<p>
TableGen uses the following target description (<tt>.td</tt>) input files to
generate much of the code for instruction definition:
</p>
<ul>
<li><tt>Target.td</tt> — Where the <tt>Instruction</tt>, <tt>Operand</tt>,
<tt>InstrInfo</tt>, and other fundamental classes are defined.</li>
<li><tt>TargetSelectionDAG.td</tt>— Used by <tt>SelectionDAG</tt>
instruction selection generators, contains <tt>SDTC*</tt> classes (selection
DAG type constraint), definitions of <tt>SelectionDAG</tt> nodes (such as
<tt>imm</tt>, <tt>cond</tt>, <tt>bb</tt>, <tt>add</tt>, <tt>fadd</tt>,
<tt>sub</tt>), and pattern support (<tt>Pattern</tt>, <tt>Pat</tt>,
<tt>PatFrag</tt>, <tt>PatLeaf</tt>, <tt>ComplexPattern</tt>.</li>
<li><tt>XXXInstrFormats.td</tt> — Patterns for definitions of
target-specific instructions.</li>
<li><tt>XXXInstrInfo.td</tt> — Target-specific definitions of instruction
templates, condition codes, and instructions of an instruction set. For
architecture modifications, a different file name may be used. For example,
for Pentium with SSE instruction, this file is <tt>X86InstrSSE.td</tt>, and
for Pentium with MMX, this file is <tt>X86InstrMMX.td</tt>.</li>
</ul>
<p>
There is also a target-specific <tt>XXX.td</tt> file, where <tt>XXX</tt> is the
name of the target. The <tt>XXX.td</tt> file includes the other <tt>.td</tt>
input files, but its contents are only directly important for subtargets.
</p>
<p>
You should describe a concrete target-specific class <tt>XXXInstrInfo</tt> that
represents machine instructions supported by a target machine.
<tt>XXXInstrInfo</tt> contains an array of <tt>XXXInstrDescriptor</tt> objects,
each of which describes one instruction. An instruction descriptor defines:</p>
<ul>
<li>Opcode mnemonic</li>
<li>Number of operands</li>
<li>List of implicit register definitions and uses</li>
<li>Target-independent properties (such as memory access, is commutable)</li>
<li>Target-specific flags </li>
</ul>
<p>
The Instruction class (defined in <tt>Target.td</tt>) is mostly used as a base
for more complex instruction classes.
</p>
<div class="doc_code">
<pre>class Instruction {
string Namespace = "";
dag OutOperandList; // An dag containing the MI def operand list.
dag InOperandList; // An dag containing the MI use operand list.
string AsmString = ""; // The .s format to print the instruction with.
list<dag> Pattern; // Set to the DAG pattern for this instruction
list<Register> Uses = [];
list<Register> Defs = [];
list<Predicate> Predicates = []; // predicates turned into isel match code
... remainder not shown for space ...
}
</pre>
</div>