WritingAnLLVMBackend.rst 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  1. =======================
  2. Writing an LLVM Backend
  3. =======================
  4. .. toctree::
  5. :hidden:
  6. HowToUseInstrMappings
  7. .. contents::
  8. :local:
  9. Introduction
  10. ============
  11. This document describes techniques for writing compiler backends that convert
  12. the LLVM Intermediate Representation (IR) to code for a specified machine or
  13. other languages. Code intended for a specific machine can take the form of
  14. either assembly code or binary code (usable for a JIT compiler).
  15. The backend of LLVM features a target-independent code generator that may
  16. create output for several types of target CPUs --- including X86, PowerPC,
  17. ARM, and SPARC. The backend may also be used to generate code targeted at SPUs
  18. of the Cell processor or GPUs to support the execution of compute kernels.
  19. The document focuses on existing examples found in subdirectories of
  20. ``llvm/lib/Target`` in a downloaded LLVM release. In particular, this document
  21. focuses on the example of creating a static compiler (one that emits text
  22. assembly) for a SPARC target, because SPARC has fairly standard
  23. characteristics, such as a RISC instruction set and straightforward calling
  24. conventions.
  25. Audience
  26. --------
  27. The audience for this document is anyone who needs to write an LLVM backend to
  28. generate code for a specific hardware or software target.
  29. Prerequisite Reading
  30. --------------------
  31. These essential documents must be read before reading this document:
  32. * `LLVM Language Reference Manual <LangRef.html>`_ --- a reference manual for
  33. the LLVM assembly language.
  34. * :doc:`CodeGenerator` --- a guide to the components (classes and code
  35. generation algorithms) for translating the LLVM internal representation into
  36. machine code for a specified target. Pay particular attention to the
  37. descriptions of code generation stages: Instruction Selection, Scheduling and
  38. Formation, SSA-based Optimization, Register Allocation, Prolog/Epilog Code
  39. Insertion, Late Machine Code Optimizations, and Code Emission.
  40. * :doc:`TableGen/index` --- a document that describes the TableGen
  41. (``tblgen``) application that manages domain-specific information to support
  42. LLVM code generation. TableGen processes input from a target description
  43. file (``.td`` suffix) and generates C++ code that can be used for code
  44. generation.
  45. * :doc:`WritingAnLLVMPass` --- The assembly printer is a ``FunctionPass``, as
  46. are several ``SelectionDAG`` processing steps.
  47. To follow the SPARC examples in this document, have a copy of `The SPARC
  48. Architecture Manual, Version 8 <http://www.sparc.org/standards/V8.pdf>`_ for
  49. reference. For details about the ARM instruction set, refer to the `ARM
  50. Architecture Reference Manual <http://infocenter.arm.com/>`_. For more about
  51. the GNU Assembler format (``GAS``), see `Using As
  52. <http://sourceware.org/binutils/docs/as/index.html>`_, especially for the
  53. assembly printer. "Using As" contains a list of target machine dependent
  54. features.
  55. Basic Steps
  56. -----------
  57. To write a compiler backend for LLVM that converts the LLVM IR to code for a
  58. specified target (machine or other language), follow these steps:
  59. * Create a subclass of the ``TargetMachine`` class that describes
  60. characteristics of your target machine. Copy existing examples of specific
  61. ``TargetMachine`` class and header files; for example, start with
  62. ``SparcTargetMachine.cpp`` and ``SparcTargetMachine.h``, but change the file
  63. names for your target. Similarly, change code that references "``Sparc``" to
  64. reference your target.
  65. * Describe the register set of the target. Use TableGen to generate code for
  66. register definition, register aliases, and register classes from a
  67. target-specific ``RegisterInfo.td`` input file. You should also write
  68. additional code for a subclass of the ``TargetRegisterInfo`` class that
  69. represents the class register file data used for register allocation and also
  70. describes the interactions between registers.
  71. * Describe the instruction set of the target. Use TableGen to generate code
  72. for target-specific instructions from target-specific versions of
  73. ``TargetInstrFormats.td`` and ``TargetInstrInfo.td``. You should write
  74. additional code for a subclass of the ``TargetInstrInfo`` class to represent
  75. machine instructions supported by the target machine.
  76. * Describe the selection and conversion of the LLVM IR from a Directed Acyclic
  77. Graph (DAG) representation of instructions to native target-specific
  78. instructions. Use TableGen to generate code that matches patterns and
  79. selects instructions based on additional information in a target-specific
  80. version of ``TargetInstrInfo.td``. Write code for ``XXXISelDAGToDAG.cpp``,
  81. where ``XXX`` identifies the specific target, to perform pattern matching and
  82. DAG-to-DAG instruction selection. Also write code in ``XXXISelLowering.cpp``
  83. to replace or remove operations and data types that are not supported
  84. natively in a SelectionDAG.
  85. * Write code for an assembly printer that converts LLVM IR to a GAS format for
  86. your target machine. You should add assembly strings to the instructions
  87. defined in your target-specific version of ``TargetInstrInfo.td``. You
  88. should also write code for a subclass of ``AsmPrinter`` that performs the
  89. LLVM-to-assembly conversion and a trivial subclass of ``TargetAsmInfo``.
  90. * Optionally, add support for subtargets (i.e., variants with different
  91. capabilities). You should also write code for a subclass of the
  92. ``TargetSubtarget`` class, which allows you to use the ``-mcpu=`` and
  93. ``-mattr=`` command-line options.
  94. * Optionally, add JIT support and create a machine code emitter (subclass of
  95. ``TargetJITInfo``) that is used to emit binary code directly into memory.
  96. In the ``.cpp`` and ``.h``. files, initially stub up these methods and then
  97. implement them later. Initially, you may not know which private members that
  98. the class will need and which components will need to be subclassed.
  99. Preliminaries
  100. -------------
  101. To actually create your compiler backend, you need to create and modify a few
  102. files. The absolute minimum is discussed here. But to actually use the LLVM
  103. target-independent code generator, you must perform the steps described in the
  104. :doc:`LLVM Target-Independent Code Generator <CodeGenerator>` document.
  105. First, you should create a subdirectory under ``lib/Target`` to hold all the
  106. files related to your target. If your target is called "Dummy", create the
  107. directory ``lib/Target/Dummy``.
  108. In this new directory, create a ``CMakeLists.txt``. It is easiest to copy a
  109. ``CMakeLists.txt`` of another target and modify it. It should at least contain
  110. the ``LLVM_TARGET_DEFINITIONS`` variable. The library can be named ``LLVMDummy``
  111. (for example, see the MIPS target). Alternatively, you can split the library
  112. into ``LLVMDummyCodeGen`` and ``LLVMDummyAsmPrinter``, the latter of which
  113. should be implemented in a subdirectory below ``lib/Target/Dummy`` (for example,
  114. see the PowerPC target).
  115. Note that these two naming schemes are hardcoded into ``llvm-config``. Using
  116. any other naming scheme will confuse ``llvm-config`` and produce a lot of
  117. (seemingly unrelated) linker errors when linking ``llc``.
  118. To make your target actually do something, you need to implement a subclass of
  119. ``TargetMachine``. This implementation should typically be in the file
  120. ``lib/Target/DummyTargetMachine.cpp``, but any file in the ``lib/Target``
  121. directory will be built and should work. To use LLVM's target independent code
  122. generator, you should do what all current machine backends do: create a
  123. subclass of ``LLVMTargetMachine``. (To create a target from scratch, create a
  124. subclass of ``TargetMachine``.)
  125. To get LLVM to actually build and link your target, you need to run ``cmake``
  126. with ``-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=Dummy``. This will build your
  127. target without needing to add it to the list of all the targets.
  128. Once your target is stable, you can add it to the ``LLVM_ALL_TARGETS`` variable
  129. located in the main ``CMakeLists.txt``.
  130. Target Machine
  131. ==============
  132. ``LLVMTargetMachine`` is designed as a base class for targets implemented with
  133. the LLVM target-independent code generator. The ``LLVMTargetMachine`` class
  134. should be specialized by a concrete target class that implements the various
  135. virtual methods. ``LLVMTargetMachine`` is defined as a subclass of
  136. ``TargetMachine`` in ``include/llvm/Target/TargetMachine.h``. The
  137. ``TargetMachine`` class implementation (``TargetMachine.cpp``) also processes
  138. numerous command-line options.
  139. To create a concrete target-specific subclass of ``LLVMTargetMachine``, start
  140. by copying an existing ``TargetMachine`` class and header. You should name the
  141. files that you create to reflect your specific target. For instance, for the
  142. SPARC target, name the files ``SparcTargetMachine.h`` and
  143. ``SparcTargetMachine.cpp``.
  144. For a target machine ``XXX``, the implementation of ``XXXTargetMachine`` must
  145. have access methods to obtain objects that represent target components. These
  146. methods are named ``get*Info``, and are intended to obtain the instruction set
  147. (``getInstrInfo``), register set (``getRegisterInfo``), stack frame layout
  148. (``getFrameInfo``), and similar information. ``XXXTargetMachine`` must also
  149. implement the ``getDataLayout`` method to access an object with target-specific
  150. data characteristics, such as data type size and alignment requirements.
  151. For instance, for the SPARC target, the header file ``SparcTargetMachine.h``
  152. declares prototypes for several ``get*Info`` and ``getDataLayout`` methods that
  153. simply return a class member.
  154. .. code-block:: c++
  155. namespace llvm {
  156. class Module;
  157. class SparcTargetMachine : public LLVMTargetMachine {
  158. const DataLayout DataLayout; // Calculates type size & alignment
  159. SparcSubtarget Subtarget;
  160. SparcInstrInfo InstrInfo;
  161. TargetFrameInfo FrameInfo;
  162. protected:
  163. virtual const TargetAsmInfo *createTargetAsmInfo() const;
  164. public:
  165. SparcTargetMachine(const Module &M, const std::string &FS);
  166. virtual const SparcInstrInfo *getInstrInfo() const {return &InstrInfo; }
  167. virtual const TargetFrameInfo *getFrameInfo() const {return &FrameInfo; }
  168. virtual const TargetSubtarget *getSubtargetImpl() const{return &Subtarget; }
  169. virtual const TargetRegisterInfo *getRegisterInfo() const {
  170. return &InstrInfo.getRegisterInfo();
  171. }
  172. virtual const DataLayout *getDataLayout() const { return &DataLayout; }
  173. static unsigned getModuleMatchQuality(const Module &M);
  174. // Pass Pipeline Configuration
  175. virtual bool addInstSelector(PassManagerBase &PM, bool Fast);
  176. virtual bool addPreEmitPass(PassManagerBase &PM, bool Fast);
  177. };
  178. } // end namespace llvm
  179. * ``getInstrInfo()``
  180. * ``getRegisterInfo()``
  181. * ``getFrameInfo()``
  182. * ``getDataLayout()``
  183. * ``getSubtargetImpl()``
  184. For some targets, you also need to support the following methods:
  185. * ``getTargetLowering()``
  186. * ``getJITInfo()``
  187. Some architectures, such as GPUs, do not support jumping to an arbitrary
  188. program location and implement branching using masked execution and loop using
  189. special instructions around the loop body. In order to avoid CFG modifications
  190. that introduce irreducible control flow not handled by such hardware, a target
  191. must call `setRequiresStructuredCFG(true)` when being initialized.
  192. In addition, the ``XXXTargetMachine`` constructor should specify a
  193. ``TargetDescription`` string that determines the data layout for the target
  194. machine, including characteristics such as pointer size, alignment, and
  195. endianness. For example, the constructor for ``SparcTargetMachine`` contains
  196. the following:
  197. .. code-block:: c++
  198. SparcTargetMachine::SparcTargetMachine(const Module &M, const std::string &FS)
  199. : DataLayout("E-p:32:32-f128:128:128"),
  200. Subtarget(M, FS), InstrInfo(Subtarget),
  201. FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
  202. }
  203. Hyphens separate portions of the ``TargetDescription`` string.
  204. * An upper-case "``E``" in the string indicates a big-endian target data model.
  205. A lower-case "``e``" indicates little-endian.
  206. * "``p:``" is followed by pointer information: size, ABI alignment, and
  207. preferred alignment. If only two figures follow "``p:``", then the first
  208. value is pointer size, and the second value is both ABI and preferred
  209. alignment.
  210. * Then a letter for numeric type alignment: "``i``", "``f``", "``v``", or
  211. "``a``" (corresponding to integer, floating point, vector, or aggregate).
  212. "``i``", "``v``", or "``a``" are followed by ABI alignment and preferred
  213. alignment. "``f``" is followed by three values: the first indicates the size
  214. of a long double, then ABI alignment, and then ABI preferred alignment.
  215. Target Registration
  216. ===================
  217. You must also register your target with the ``TargetRegistry``, which is what
  218. other LLVM tools use to be able to lookup and use your target at runtime. The
  219. ``TargetRegistry`` can be used directly, but for most targets there are helper
  220. templates which should take care of the work for you.
  221. All targets should declare a global ``Target`` object which is used to
  222. represent the target during registration. Then, in the target's ``TargetInfo``
  223. library, the target should define that object and use the ``RegisterTarget``
  224. template to register the target. For example, the Sparc registration code
  225. looks like this:
  226. .. code-block:: c++
  227. Target llvm::getTheSparcTarget();
  228. extern "C" void LLVMInitializeSparcTargetInfo() {
  229. RegisterTarget<Triple::sparc, /*HasJIT=*/false>
  230. X(getTheSparcTarget(), "sparc", "Sparc");
  231. }
  232. This allows the ``TargetRegistry`` to look up the target by name or by target
  233. triple. In addition, most targets will also register additional features which
  234. are available in separate libraries. These registration steps are separate,
  235. because some clients may wish to only link in some parts of the target --- the
  236. JIT code generator does not require the use of the assembler printer, for
  237. example. Here is an example of registering the Sparc assembly printer:
  238. .. code-block:: c++
  239. extern "C" void LLVMInitializeSparcAsmPrinter() {
  240. RegisterAsmPrinter<SparcAsmPrinter> X(getTheSparcTarget());
  241. }
  242. For more information, see "`llvm/Target/TargetRegistry.h
  243. </doxygen/TargetRegistry_8h-source.html>`_".
  244. Register Set and Register Classes
  245. =================================
  246. You should describe a concrete target-specific class that represents the
  247. register file of a target machine. This class is called ``XXXRegisterInfo``
  248. (where ``XXX`` identifies the target) and represents the class register file
  249. data that is used for register allocation. It also describes the interactions
  250. between registers.
  251. You also need to define register classes to categorize related registers. A
  252. register class should be added for groups of registers that are all treated the
  253. same way for some instruction. Typical examples are register classes for
  254. integer, floating-point, or vector registers. A register allocator allows an
  255. instruction to use any register in a specified register class to perform the
  256. instruction in a similar manner. Register classes allocate virtual registers
  257. to instructions from these sets, and register classes let the
  258. target-independent register allocator automatically choose the actual
  259. registers.
  260. Much of the code for registers, including register definition, register
  261. aliases, and register classes, is generated by TableGen from
  262. ``XXXRegisterInfo.td`` input files and placed in ``XXXGenRegisterInfo.h.inc``
  263. and ``XXXGenRegisterInfo.inc`` output files. Some of the code in the
  264. implementation of ``XXXRegisterInfo`` requires hand-coding.
  265. Defining a Register
  266. -------------------
  267. The ``XXXRegisterInfo.td`` file typically starts with register definitions for
  268. a target machine. The ``Register`` class (specified in ``Target.td``) is used
  269. to define an object for each register. The specified string ``n`` becomes the
  270. ``Name`` of the register. The basic ``Register`` object does not have any
  271. subregisters and does not specify any aliases.
  272. .. code-block:: text
  273. class Register<string n> {
  274. string Namespace = "";
  275. string AsmName = n;
  276. string Name = n;
  277. int SpillSize = 0;
  278. int SpillAlignment = 0;
  279. list<Register> Aliases = [];
  280. list<Register> SubRegs = [];
  281. list<int> DwarfNumbers = [];
  282. }
  283. For example, in the ``X86RegisterInfo.td`` file, there are register definitions
  284. that utilize the ``Register`` class, such as:
  285. .. code-block:: text
  286. def AL : Register<"AL">, DwarfRegNum<[0, 0, 0]>;
  287. This defines the register ``AL`` and assigns it values (with ``DwarfRegNum``)
  288. that are used by ``gcc``, ``gdb``, or a debug information writer to identify a
  289. register. For register ``AL``, ``DwarfRegNum`` takes an array of 3 values
  290. representing 3 different modes: the first element is for X86-64, the second for
  291. exception handling (EH) on X86-32, and the third is generic. -1 is a special
  292. Dwarf number that indicates the gcc number is undefined, and -2 indicates the
  293. register number is invalid for this mode.
  294. From the previously described line in the ``X86RegisterInfo.td`` file, TableGen
  295. generates this code in the ``X86GenRegisterInfo.inc`` file:
  296. .. code-block:: c++
  297. static const unsigned GR8[] = { X86::AL, ... };
  298. const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 };
  299. const TargetRegisterDesc RegisterDescriptors[] = {
  300. ...
  301. { "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ...
  302. From the register info file, TableGen generates a ``TargetRegisterDesc`` object
  303. for each register. ``TargetRegisterDesc`` is defined in
  304. ``include/llvm/Target/TargetRegisterInfo.h`` with the following fields:
  305. .. code-block:: c++
  306. struct TargetRegisterDesc {
  307. const char *AsmName; // Assembly language name for the register
  308. const char *Name; // Printable name for the reg (for debugging)
  309. const unsigned *AliasSet; // Register Alias Set
  310. const unsigned *SubRegs; // Sub-register set
  311. const unsigned *ImmSubRegs; // Immediate sub-register set
  312. const unsigned *SuperRegs; // Super-register set
  313. };
  314. TableGen uses the entire target description file (``.td``) to determine text
  315. names for the register (in the ``AsmName`` and ``Name`` fields of
  316. ``TargetRegisterDesc``) and the relationships of other registers to the defined
  317. register (in the other ``TargetRegisterDesc`` fields). In this example, other
  318. definitions establish the registers "``AX``", "``EAX``", and "``RAX``" as
  319. aliases for one another, so TableGen generates a null-terminated array
  320. (``AL_AliasSet``) for this register alias set.
  321. The ``Register`` class is commonly used as a base class for more complex
  322. classes. In ``Target.td``, the ``Register`` class is the base for the
  323. ``RegisterWithSubRegs`` class that is used to define registers that need to
  324. specify subregisters in the ``SubRegs`` list, as shown here:
  325. .. code-block:: text
  326. class RegisterWithSubRegs<string n, list<Register> subregs> : Register<n> {
  327. let SubRegs = subregs;
  328. }
  329. In ``SparcRegisterInfo.td``, additional register classes are defined for SPARC:
  330. a ``Register`` subclass, ``SparcReg``, and further subclasses: ``Ri``, ``Rf``,
  331. and ``Rd``. SPARC registers are identified by 5-bit ID numbers, which is a
  332. feature common to these subclasses. Note the use of "``let``" expressions to
  333. override values that are initially defined in a superclass (such as ``SubRegs``
  334. field in the ``Rd`` class).
  335. .. code-block:: text
  336. class SparcReg<string n> : Register<n> {
  337. field bits<5> Num;
  338. let Namespace = "SP";
  339. }
  340. // Ri - 32-bit integer registers
  341. class Ri<bits<5> num, string n> :
  342. SparcReg<n> {
  343. let Num = num;
  344. }
  345. // Rf - 32-bit floating-point registers
  346. class Rf<bits<5> num, string n> :
  347. SparcReg<n> {
  348. let Num = num;
  349. }
  350. // Rd - Slots in the FP register file for 64-bit floating-point values.
  351. class Rd<bits<5> num, string n, list<Register> subregs> : SparcReg<n> {
  352. let Num = num;
  353. let SubRegs = subregs;
  354. }
  355. In the ``SparcRegisterInfo.td`` file, there are register definitions that
  356. utilize these subclasses of ``Register``, such as:
  357. .. code-block:: text
  358. def G0 : Ri< 0, "G0">, DwarfRegNum<[0]>;
  359. def G1 : Ri< 1, "G1">, DwarfRegNum<[1]>;
  360. ...
  361. def F0 : Rf< 0, "F0">, DwarfRegNum<[32]>;
  362. def F1 : Rf< 1, "F1">, DwarfRegNum<[33]>;
  363. ...
  364. def D0 : Rd< 0, "F0", [F0, F1]>, DwarfRegNum<[32]>;
  365. def D1 : Rd< 2, "F2", [F2, F3]>, DwarfRegNum<[34]>;
  366. The last two registers shown above (``D0`` and ``D1``) are double-precision
  367. floating-point registers that are aliases for pairs of single-precision
  368. floating-point sub-registers. In addition to aliases, the sub-register and
  369. super-register relationships of the defined register are in fields of a
  370. register's ``TargetRegisterDesc``.
  371. Defining a Register Class
  372. -------------------------
  373. The ``RegisterClass`` class (specified in ``Target.td``) is used to define an
  374. object that represents a group of related registers and also defines the
  375. default allocation order of the registers. A target description file
  376. ``XXXRegisterInfo.td`` that uses ``Target.td`` can construct register classes
  377. using the following class:
  378. .. code-block:: text
  379. class RegisterClass<string namespace,
  380. list<ValueType> regTypes, int alignment, dag regList> {
  381. string Namespace = namespace;
  382. list<ValueType> RegTypes = regTypes;
  383. int Size = 0; // spill size, in bits; zero lets tblgen pick the size
  384. int Alignment = alignment;
  385. // CopyCost is the cost of copying a value between two registers
  386. // default value 1 means a single instruction
  387. // A negative value means copying is extremely expensive or impossible
  388. int CopyCost = 1;
  389. dag MemberList = regList;
  390. // for register classes that are subregisters of this class
  391. list<RegisterClass> SubRegClassList = [];
  392. code MethodProtos = [{}]; // to insert arbitrary code
  393. code MethodBodies = [{}];
  394. }
  395. To define a ``RegisterClass``, use the following 4 arguments:
  396. * The first argument of the definition is the name of the namespace.
  397. * The second argument is a list of ``ValueType`` register type values that are
  398. defined in ``include/llvm/CodeGen/ValueTypes.td``. Defined values include
  399. integer types (such as ``i16``, ``i32``, and ``i1`` for Boolean),
  400. floating-point types (``f32``, ``f64``), and vector types (for example,
  401. ``v8i16`` for an ``8 x i16`` vector). All registers in a ``RegisterClass``
  402. must have the same ``ValueType``, but some registers may store vector data in
  403. different configurations. For example a register that can process a 128-bit
  404. vector may be able to handle 16 8-bit integer elements, 8 16-bit integers, 4
  405. 32-bit integers, and so on.
  406. * The third argument of the ``RegisterClass`` definition specifies the
  407. alignment required of the registers when they are stored or loaded to
  408. memory.
  409. * The final argument, ``regList``, specifies which registers are in this class.
  410. If an alternative allocation order method is not specified, then ``regList``
  411. also defines the order of allocation used by the register allocator. Besides
  412. simply listing registers with ``(add R0, R1, ...)``, more advanced set
  413. operators are available. See ``include/llvm/Target/Target.td`` for more
  414. information.
  415. In ``SparcRegisterInfo.td``, three ``RegisterClass`` objects are defined:
  416. ``FPRegs``, ``DFPRegs``, and ``IntRegs``. For all three register classes, the
  417. first argument defines the namespace with the string "``SP``". ``FPRegs``
  418. defines a group of 32 single-precision floating-point registers (``F0`` to
  419. ``F31``); ``DFPRegs`` defines a group of 16 double-precision registers
  420. (``D0-D15``).
  421. .. code-block:: text
  422. // F0, F1, F2, ..., F31
  423. def FPRegs : RegisterClass<"SP", [f32], 32, (sequence "F%u", 0, 31)>;
  424. def DFPRegs : RegisterClass<"SP", [f64], 64,
  425. (add D0, D1, D2, D3, D4, D5, D6, D7, D8,
  426. D9, D10, D11, D12, D13, D14, D15)>;
  427. def IntRegs : RegisterClass<"SP", [i32], 32,
  428. (add L0, L1, L2, L3, L4, L5, L6, L7,
  429. I0, I1, I2, I3, I4, I5,
  430. O0, O1, O2, O3, O4, O5, O7,
  431. G1,
  432. // Non-allocatable regs:
  433. G2, G3, G4,
  434. O6, // stack ptr
  435. I6, // frame ptr
  436. I7, // return address
  437. G0, // constant zero
  438. G5, G6, G7 // reserved for kernel
  439. )>;
  440. Using ``SparcRegisterInfo.td`` with TableGen generates several output files
  441. that are intended for inclusion in other source code that you write.
  442. ``SparcRegisterInfo.td`` generates ``SparcGenRegisterInfo.h.inc``, which should
  443. be included in the header file for the implementation of the SPARC register
  444. implementation that you write (``SparcRegisterInfo.h``). In
  445. ``SparcGenRegisterInfo.h.inc`` a new structure is defined called
  446. ``SparcGenRegisterInfo`` that uses ``TargetRegisterInfo`` as its base. It also
  447. specifies types, based upon the defined register classes: ``DFPRegsClass``,
  448. ``FPRegsClass``, and ``IntRegsClass``.
  449. ``SparcRegisterInfo.td`` also generates ``SparcGenRegisterInfo.inc``, which is
  450. included at the bottom of ``SparcRegisterInfo.cpp``, the SPARC register
  451. implementation. The code below shows only the generated integer registers and
  452. associated register classes. The order of registers in ``IntRegs`` reflects
  453. the order in the definition of ``IntRegs`` in the target description file.
  454. .. code-block:: c++
  455. // IntRegs Register Class...
  456. static const unsigned IntRegs[] = {
  457. SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5,
  458. SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3,
  459. SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3,
  460. SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3,
  461. SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5,
  462. SP::G6, SP::G7,
  463. };
  464. // IntRegsVTs Register Class Value Types...
  465. static const MVT::ValueType IntRegsVTs[] = {
  466. MVT::i32, MVT::Other
  467. };
  468. namespace SP { // Register class instances
  469. DFPRegsClass DFPRegsRegClass;
  470. FPRegsClass FPRegsRegClass;
  471. IntRegsClass IntRegsRegClass;
  472. ...
  473. // IntRegs Sub-register Classes...
  474. static const TargetRegisterClass* const IntRegsSubRegClasses [] = {
  475. NULL
  476. };
  477. ...
  478. // IntRegs Super-register Classes..
  479. static const TargetRegisterClass* const IntRegsSuperRegClasses [] = {
  480. NULL
  481. };
  482. ...
  483. // IntRegs Register Class sub-classes...
  484. static const TargetRegisterClass* const IntRegsSubclasses [] = {
  485. NULL
  486. };
  487. ...
  488. // IntRegs Register Class super-classes...
  489. static const TargetRegisterClass* const IntRegsSuperclasses [] = {
  490. NULL
  491. };
  492. IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID,
  493. IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses,
  494. IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {}
  495. }
  496. The register allocators will avoid using reserved registers, and callee saved
  497. registers are not used until all the volatile registers have been used. That
  498. is usually good enough, but in some cases it may be necessary to provide custom
  499. allocation orders.
  500. Implement a subclass of ``TargetRegisterInfo``
  501. ----------------------------------------------
  502. The final step is to hand code portions of ``XXXRegisterInfo``, which
  503. implements the interface described in ``TargetRegisterInfo.h`` (see
  504. :ref:`TargetRegisterInfo`). These functions return ``0``, ``NULL``, or
  505. ``false``, unless overridden. Here is a list of functions that are overridden
  506. for the SPARC implementation in ``SparcRegisterInfo.cpp``:
  507. * ``getCalleeSavedRegs`` --- Returns a list of callee-saved registers in the
  508. order of the desired callee-save stack frame offset.
  509. * ``getReservedRegs`` --- Returns a bitset indexed by physical register
  510. numbers, indicating if a particular register is unavailable.
  511. * ``hasFP`` --- Return a Boolean indicating if a function should have a
  512. dedicated frame pointer register.
  513. * ``eliminateCallFramePseudoInstr`` --- If call frame setup or destroy pseudo
  514. instructions are used, this can be called to eliminate them.
  515. * ``eliminateFrameIndex`` --- Eliminate abstract frame indices from
  516. instructions that may use them.
  517. * ``emitPrologue`` --- Insert prologue code into the function.
  518. * ``emitEpilogue`` --- Insert epilogue code into the function.
  519. .. _instruction-set:
  520. Instruction Set
  521. ===============
  522. During the early stages of code generation, the LLVM IR code is converted to a
  523. ``SelectionDAG`` with nodes that are instances of the ``SDNode`` class
  524. containing target instructions. An ``SDNode`` has an opcode, operands, type
  525. requirements, and operation properties. For example, is an operation
  526. commutative, does an operation load from memory. The various operation node
  527. types are described in the ``include/llvm/CodeGen/SelectionDAGNodes.h`` file
  528. (values of the ``NodeType`` enum in the ``ISD`` namespace).
  529. TableGen uses the following target description (``.td``) input files to
  530. generate much of the code for instruction definition:
  531. * ``Target.td`` --- Where the ``Instruction``, ``Operand``, ``InstrInfo``, and
  532. other fundamental classes are defined.
  533. * ``TargetSelectionDAG.td`` --- Used by ``SelectionDAG`` instruction selection
  534. generators, contains ``SDTC*`` classes (selection DAG type constraint),
  535. definitions of ``SelectionDAG`` nodes (such as ``imm``, ``cond``, ``bb``,
  536. ``add``, ``fadd``, ``sub``), and pattern support (``Pattern``, ``Pat``,
  537. ``PatFrag``, ``PatLeaf``, ``ComplexPattern``.
  538. * ``XXXInstrFormats.td`` --- Patterns for definitions of target-specific
  539. instructions.
  540. * ``XXXInstrInfo.td`` --- Target-specific definitions of instruction templates,
  541. condition codes, and instructions of an instruction set. For architecture
  542. modifications, a different file name may be used. For example, for Pentium
  543. with SSE instruction, this file is ``X86InstrSSE.td``, and for Pentium with
  544. MMX, this file is ``X86InstrMMX.td``.
  545. There is also a target-specific ``XXX.td`` file, where ``XXX`` is the name of
  546. the target. The ``XXX.td`` file includes the other ``.td`` input files, but
  547. its contents are only directly important for subtargets.
  548. You should describe a concrete target-specific class ``XXXInstrInfo`` that
  549. represents machine instructions supported by a target machine.
  550. ``XXXInstrInfo`` contains an array of ``XXXInstrDescriptor`` objects, each of
  551. which describes one instruction. An instruction descriptor defines:
  552. * Opcode mnemonic
  553. * Number of operands
  554. * List of implicit register definitions and uses
  555. * Target-independent properties (such as memory access, is commutable)
  556. * Target-specific flags
  557. The Instruction class (defined in ``Target.td``) is mostly used as a base for
  558. more complex instruction classes.
  559. .. code-block:: text
  560. class Instruction {
  561. string Namespace = "";
  562. dag OutOperandList; // A dag containing the MI def operand list.
  563. dag InOperandList; // A dag containing the MI use operand list.
  564. string AsmString = ""; // The .s format to print the instruction with.
  565. list<dag> Pattern; // Set to the DAG pattern for this instruction.
  566. list<Register> Uses = [];
  567. list<Register> Defs = [];
  568. list<Predicate> Predicates = []; // predicates turned into isel match code
  569. ... remainder not shown for space ...
  570. }
  571. A ``SelectionDAG`` node (``SDNode``) should contain an object representing a
  572. target-specific instruction that is defined in ``XXXInstrInfo.td``. The
  573. instruction objects should represent instructions from the architecture manual
  574. of the target machine (such as the SPARC Architecture Manual for the SPARC
  575. target).
  576. A single instruction from the architecture manual is often modeled as multiple
  577. target instructions, depending upon its operands. For example, a manual might
  578. describe an add instruction that takes a register or an immediate operand. An
  579. LLVM target could model this with two instructions named ``ADDri`` and
  580. ``ADDrr``.
  581. You should define a class for each instruction category and define each opcode
  582. as a subclass of the category with appropriate parameters such as the fixed
  583. binary encoding of opcodes and extended opcodes. You should map the register
  584. bits to the bits of the instruction in which they are encoded (for the JIT).
  585. Also you should specify how the instruction should be printed when the
  586. automatic assembly printer is used.
  587. As is described in the SPARC Architecture Manual, Version 8, there are three
  588. major 32-bit formats for instructions. Format 1 is only for the ``CALL``
  589. instruction. Format 2 is for branch on condition codes and ``SETHI`` (set high
  590. bits of a register) instructions. Format 3 is for other instructions.
  591. Each of these formats has corresponding classes in ``SparcInstrFormat.td``.
  592. ``InstSP`` is a base class for other instruction classes. Additional base
  593. classes are specified for more precise formats: for example in
  594. ``SparcInstrFormat.td``, ``F2_1`` is for ``SETHI``, and ``F2_2`` is for
  595. branches. There are three other base classes: ``F3_1`` for register/register
  596. operations, ``F3_2`` for register/immediate operations, and ``F3_3`` for
  597. floating-point operations. ``SparcInstrInfo.td`` also adds the base class
  598. ``Pseudo`` for synthetic SPARC instructions.
  599. ``SparcInstrInfo.td`` largely consists of operand and instruction definitions
  600. for the SPARC target. In ``SparcInstrInfo.td``, the following target
  601. description file entry, ``LDrr``, defines the Load Integer instruction for a
  602. Word (the ``LD`` SPARC opcode) from a memory address to a register. The first
  603. parameter, the value 3 (``11``\ :sub:`2`), is the operation value for this
  604. category of operation. The second parameter (``000000``\ :sub:`2`) is the
  605. specific operation value for ``LD``/Load Word. The third parameter is the
  606. output destination, which is a register operand and defined in the ``Register``
  607. target description file (``IntRegs``).
  608. .. code-block:: text
  609. def LDrr : F3_1 <3, 0b000000, (outs IntRegs:$dst), (ins MEMrr:$addr),
  610. "ld [$addr], $dst",
  611. [(set i32:$dst, (load ADDRrr:$addr))]>;
  612. The fourth parameter is the input source, which uses the address operand
  613. ``MEMrr`` that is defined earlier in ``SparcInstrInfo.td``:
  614. .. code-block:: text
  615. def MEMrr : Operand<i32> {
  616. let PrintMethod = "printMemOperand";
  617. let MIOperandInfo = (ops IntRegs, IntRegs);
  618. }
  619. The fifth parameter is a string that is used by the assembly printer and can be
  620. left as an empty string until the assembly printer interface is implemented.
  621. The sixth and final parameter is the pattern used to match the instruction
  622. during the SelectionDAG Select Phase described in :doc:`CodeGenerator`.
  623. This parameter is detailed in the next section, :ref:`instruction-selector`.
  624. Instruction class definitions are not overloaded for different operand types,
  625. so separate versions of instructions are needed for register, memory, or
  626. immediate value operands. For example, to perform a Load Integer instruction
  627. for a Word from an immediate operand to a register, the following instruction
  628. class is defined:
  629. .. code-block:: text
  630. def LDri : F3_2 <3, 0b000000, (outs IntRegs:$dst), (ins MEMri:$addr),
  631. "ld [$addr], $dst",
  632. [(set i32:$dst, (load ADDRri:$addr))]>;
  633. Writing these definitions for so many similar instructions can involve a lot of
  634. cut and paste. In ``.td`` files, the ``multiclass`` directive enables the
  635. creation of templates to define several instruction classes at once (using the
  636. ``defm`` directive). For example in ``SparcInstrInfo.td``, the ``multiclass``
  637. pattern ``F3_12`` is defined to create 2 instruction classes each time
  638. ``F3_12`` is invoked:
  639. .. code-block:: text
  640. multiclass F3_12 <string OpcStr, bits<6> Op3Val, SDNode OpNode> {
  641. def rr : F3_1 <2, Op3Val,
  642. (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
  643. !strconcat(OpcStr, " $b, $c, $dst"),
  644. [(set i32:$dst, (OpNode i32:$b, i32:$c))]>;
  645. def ri : F3_2 <2, Op3Val,
  646. (outs IntRegs:$dst), (ins IntRegs:$b, i32imm:$c),
  647. !strconcat(OpcStr, " $b, $c, $dst"),
  648. [(set i32:$dst, (OpNode i32:$b, simm13:$c))]>;
  649. }
  650. So when the ``defm`` directive is used for the ``XOR`` and ``ADD``
  651. instructions, as seen below, it creates four instruction objects: ``XORrr``,
  652. ``XORri``, ``ADDrr``, and ``ADDri``.
  653. .. code-block:: text
  654. defm XOR : F3_12<"xor", 0b000011, xor>;
  655. defm ADD : F3_12<"add", 0b000000, add>;
  656. ``SparcInstrInfo.td`` also includes definitions for condition codes that are
  657. referenced by branch instructions. The following definitions in
  658. ``SparcInstrInfo.td`` indicate the bit location of the SPARC condition code.
  659. For example, the 10\ :sup:`th` bit represents the "greater than" condition for
  660. integers, and the 22\ :sup:`nd` bit represents the "greater than" condition for
  661. floats.
  662. .. code-block:: text
  663. def ICC_NE : ICC_VAL< 9>; // Not Equal
  664. def ICC_E : ICC_VAL< 1>; // Equal
  665. def ICC_G : ICC_VAL<10>; // Greater
  666. ...
  667. def FCC_U : FCC_VAL<23>; // Unordered
  668. def FCC_G : FCC_VAL<22>; // Greater
  669. def FCC_UG : FCC_VAL<21>; // Unordered or Greater
  670. ...
  671. (Note that ``Sparc.h`` also defines enums that correspond to the same SPARC
  672. condition codes. Care must be taken to ensure the values in ``Sparc.h``
  673. correspond to the values in ``SparcInstrInfo.td``. I.e., ``SPCC::ICC_NE = 9``,
  674. ``SPCC::FCC_U = 23`` and so on.)
  675. Instruction Operand Mapping
  676. ---------------------------
  677. The code generator backend maps instruction operands to fields in the
  678. instruction. Operands are assigned to unbound fields in the instruction in the
  679. order they are defined. Fields are bound when they are assigned a value. For
  680. example, the Sparc target defines the ``XNORrr`` instruction as a ``F3_1``
  681. format instruction having three operands.
  682. .. code-block:: text
  683. def XNORrr : F3_1<2, 0b000111,
  684. (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
  685. "xnor $b, $c, $dst",
  686. [(set i32:$dst, (not (xor i32:$b, i32:$c)))]>;
  687. The instruction templates in ``SparcInstrFormats.td`` show the base class for
  688. ``F3_1`` is ``InstSP``.
  689. .. code-block:: text
  690. class InstSP<dag outs, dag ins, string asmstr, list<dag> pattern> : Instruction {
  691. field bits<32> Inst;
  692. let Namespace = "SP";
  693. bits<2> op;
  694. let Inst{31-30} = op;
  695. dag OutOperandList = outs;
  696. dag InOperandList = ins;
  697. let AsmString = asmstr;
  698. let Pattern = pattern;
  699. }
  700. ``InstSP`` leaves the ``op`` field unbound.
  701. .. code-block:: text
  702. class F3<dag outs, dag ins, string asmstr, list<dag> pattern>
  703. : InstSP<outs, ins, asmstr, pattern> {
  704. bits<5> rd;
  705. bits<6> op3;
  706. bits<5> rs1;
  707. let op{1} = 1; // Op = 2 or 3
  708. let Inst{29-25} = rd;
  709. let Inst{24-19} = op3;
  710. let Inst{18-14} = rs1;
  711. }
  712. ``F3`` binds the ``op`` field and defines the ``rd``, ``op3``, and ``rs1``
  713. fields. ``F3`` format instructions will bind the operands ``rd``, ``op3``, and
  714. ``rs1`` fields.
  715. .. code-block:: text
  716. class F3_1<bits<2> opVal, bits<6> op3val, dag outs, dag ins,
  717. string asmstr, list<dag> pattern> : F3<outs, ins, asmstr, pattern> {
  718. bits<8> asi = 0; // asi not currently used
  719. bits<5> rs2;
  720. let op = opVal;
  721. let op3 = op3val;
  722. let Inst{13} = 0; // i field = 0
  723. let Inst{12-5} = asi; // address space identifier
  724. let Inst{4-0} = rs2;
  725. }
  726. ``F3_1`` binds the ``op3`` field and defines the ``rs2`` fields. ``F3_1``
  727. format instructions will bind the operands to the ``rd``, ``rs1``, and ``rs2``
  728. fields. This results in the ``XNORrr`` instruction binding ``$dst``, ``$b``,
  729. and ``$c`` operands to the ``rd``, ``rs1``, and ``rs2`` fields respectively.
  730. Instruction Operand Name Mapping
  731. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  732. TableGen will also generate a function called getNamedOperandIdx() which
  733. can be used to look up an operand's index in a MachineInstr based on its
  734. TableGen name. Setting the UseNamedOperandTable bit in an instruction's
  735. TableGen definition will add all of its operands to an enumeration in the
  736. llvm::XXX:OpName namespace and also add an entry for it into the OperandMap
  737. table, which can be queried using getNamedOperandIdx()
  738. .. code-block:: text
  739. int DstIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::dst); // => 0
  740. int BIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::b); // => 1
  741. int CIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::c); // => 2
  742. int DIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::d); // => -1
  743. ...
  744. The entries in the OpName enum are taken verbatim from the TableGen definitions,
  745. so operands with lowercase names will have lower case entries in the enum.
  746. To include the getNamedOperandIdx() function in your backend, you will need
  747. to define a few preprocessor macros in XXXInstrInfo.cpp and XXXInstrInfo.h.
  748. For example:
  749. XXXInstrInfo.cpp:
  750. .. code-block:: c++
  751. #define GET_INSTRINFO_NAMED_OPS // For getNamedOperandIdx() function
  752. #include "XXXGenInstrInfo.inc"
  753. XXXInstrInfo.h:
  754. .. code-block:: c++
  755. #define GET_INSTRINFO_OPERAND_ENUM // For OpName enum
  756. #include "XXXGenInstrInfo.inc"
  757. namespace XXX {
  758. int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIndex);
  759. } // End namespace XXX
  760. Instruction Operand Types
  761. ^^^^^^^^^^^^^^^^^^^^^^^^^
  762. TableGen will also generate an enumeration consisting of all named Operand
  763. types defined in the backend, in the llvm::XXX::OpTypes namespace.
  764. Some common immediate Operand types (for instance i8, i32, i64, f32, f64)
  765. are defined for all targets in ``include/llvm/Target/Target.td``, and are
  766. available in each Target's OpTypes enum. Also, only named Operand types appear
  767. in the enumeration: anonymous types are ignored.
  768. For example, the X86 backend defines ``brtarget`` and ``brtarget8``, both
  769. instances of the TableGen ``Operand`` class, which represent branch target
  770. operands:
  771. .. code-block:: text
  772. def brtarget : Operand<OtherVT>;
  773. def brtarget8 : Operand<OtherVT>;
  774. This results in:
  775. .. code-block:: c++
  776. namespace X86 {
  777. namespace OpTypes {
  778. enum OperandType {
  779. ...
  780. brtarget,
  781. brtarget8,
  782. ...
  783. i32imm,
  784. i64imm,
  785. ...
  786. OPERAND_TYPE_LIST_END
  787. } // End namespace OpTypes
  788. } // End namespace X86
  789. In typical TableGen fashion, to use the enum, you will need to define a
  790. preprocessor macro:
  791. .. code-block:: c++
  792. #define GET_INSTRINFO_OPERAND_TYPES_ENUM // For OpTypes enum
  793. #include "XXXGenInstrInfo.inc"
  794. Instruction Scheduling
  795. ----------------------
  796. Instruction itineraries can be queried using MCDesc::getSchedClass(). The
  797. value can be named by an enumeration in llvm::XXX::Sched namespace generated
  798. by TableGen in XXXGenInstrInfo.inc. The name of the schedule classes are
  799. the same as provided in XXXSchedule.td plus a default NoItinerary class.
  800. The schedule models are generated by TableGen by the SubtargetEmitter,
  801. using the ``CodeGenSchedModels`` class. This is distinct from the itinerary
  802. method of specifying machine resource use. The tool ``utils/schedcover.py``
  803. can be used to determine which instructions have been covered by the
  804. schedule model description and which haven't. The first step is to use the
  805. instructions below to create an output file. Then run ``schedcover.py`` on the
  806. output file:
  807. .. code-block:: shell
  808. $ <src>/utils/schedcover.py <build>/lib/Target/AArch64/tblGenSubtarget.with
  809. instruction, default, CortexA53Model, CortexA57Model, CycloneModel, ExynosM1Model, FalkorModel, KryoModel, ThunderX2T99Model, ThunderXT8XModel
  810. ABSv16i8, WriteV, , , CyWriteV3, M1WriteNMISC1, FalkorWr_2VXVY_2cyc, KryoWrite_2cyc_XY_XY_150ln, ,
  811. ABSv1i64, WriteV, , , CyWriteV3, M1WriteNMISC1, FalkorWr_1VXVY_2cyc, KryoWrite_2cyc_XY_noRSV_67ln, ,
  812. ...
  813. To capture the debug output from generating a schedule model, change to the
  814. appropriate target directory and use the following command:
  815. command with the ``subtarget-emitter`` debug option:
  816. .. code-block:: shell
  817. $ <build>/bin/llvm-tblgen -debug-only=subtarget-emitter -gen-subtarget \
  818. -I <src>/lib/Target/<target> -I <src>/include \
  819. -I <src>/lib/Target <src>/lib/Target/<target>/<target>.td \
  820. -o <build>/lib/Target/<target>/<target>GenSubtargetInfo.inc.tmp \
  821. > tblGenSubtarget.dbg 2>&1
  822. Where ``<build>`` is the build directory, ``src`` is the source directory,
  823. and ``<target>`` is the name of the target.
  824. To double check that the above command is what is needed, one can capture the
  825. exact TableGen command from a build by using:
  826. .. code-block:: shell
  827. $ VERBOSE=1 make ...
  828. and search for ``llvm-tblgen`` commands in the output.
  829. Instruction Relation Mapping
  830. ----------------------------
  831. This TableGen feature is used to relate instructions with each other. It is
  832. particularly useful when you have multiple instruction formats and need to
  833. switch between them after instruction selection. This entire feature is driven
  834. by relation models which can be defined in ``XXXInstrInfo.td`` files
  835. according to the target-specific instruction set. Relation models are defined
  836. using ``InstrMapping`` class as a base. TableGen parses all the models
  837. and generates instruction relation maps using the specified information.
  838. Relation maps are emitted as tables in the ``XXXGenInstrInfo.inc`` file
  839. along with the functions to query them. For the detailed information on how to
  840. use this feature, please refer to :doc:`HowToUseInstrMappings`.
  841. Implement a subclass of ``TargetInstrInfo``
  842. -------------------------------------------
  843. The final step is to hand code portions of ``XXXInstrInfo``, which implements
  844. the interface described in ``TargetInstrInfo.h`` (see :ref:`TargetInstrInfo`).
  845. These functions return ``0`` or a Boolean or they assert, unless overridden.
  846. Here's a list of functions that are overridden for the SPARC implementation in
  847. ``SparcInstrInfo.cpp``:
  848. * ``isLoadFromStackSlot`` --- If the specified machine instruction is a direct
  849. load from a stack slot, return the register number of the destination and the
  850. ``FrameIndex`` of the stack slot.
  851. * ``isStoreToStackSlot`` --- If the specified machine instruction is a direct
  852. store to a stack slot, return the register number of the destination and the
  853. ``FrameIndex`` of the stack slot.
  854. * ``copyPhysReg`` --- Copy values between a pair of physical registers.
  855. * ``storeRegToStackSlot`` --- Store a register value to a stack slot.
  856. * ``loadRegFromStackSlot`` --- Load a register value from a stack slot.
  857. * ``storeRegToAddr`` --- Store a register value to memory.
  858. * ``loadRegFromAddr`` --- Load a register value from memory.
  859. * ``foldMemoryOperand`` --- Attempt to combine instructions of any load or
  860. store instruction for the specified operand(s).
  861. Branch Folding and If Conversion
  862. --------------------------------
  863. Performance can be improved by combining instructions or by eliminating
  864. instructions that are never reached. The ``AnalyzeBranch`` method in
  865. ``XXXInstrInfo`` may be implemented to examine conditional instructions and
  866. remove unnecessary instructions. ``AnalyzeBranch`` looks at the end of a
  867. machine basic block (MBB) for opportunities for improvement, such as branch
  868. folding and if conversion. The ``BranchFolder`` and ``IfConverter`` machine
  869. function passes (see the source files ``BranchFolding.cpp`` and
  870. ``IfConversion.cpp`` in the ``lib/CodeGen`` directory) call ``AnalyzeBranch``
  871. to improve the control flow graph that represents the instructions.
  872. Several implementations of ``AnalyzeBranch`` (for ARM, Alpha, and X86) can be
  873. examined as models for your own ``AnalyzeBranch`` implementation. Since SPARC
  874. does not implement a useful ``AnalyzeBranch``, the ARM target implementation is
  875. shown below.
  876. ``AnalyzeBranch`` returns a Boolean value and takes four parameters:
  877. * ``MachineBasicBlock &MBB`` --- The incoming block to be examined.
  878. * ``MachineBasicBlock *&TBB`` --- A destination block that is returned. For a
  879. conditional branch that evaluates to true, ``TBB`` is the destination.
  880. * ``MachineBasicBlock *&FBB`` --- For a conditional branch that evaluates to
  881. false, ``FBB`` is returned as the destination.
  882. * ``std::vector<MachineOperand> &Cond`` --- List of operands to evaluate a
  883. condition for a conditional branch.
  884. In the simplest case, if a block ends without a branch, then it falls through
  885. to the successor block. No destination blocks are specified for either ``TBB``
  886. or ``FBB``, so both parameters return ``NULL``. The start of the
  887. ``AnalyzeBranch`` (see code below for the ARM target) shows the function
  888. parameters and the code for the simplest case.
  889. .. code-block:: c++
  890. bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
  891. MachineBasicBlock *&TBB,
  892. MachineBasicBlock *&FBB,
  893. std::vector<MachineOperand> &Cond) const
  894. {
  895. MachineBasicBlock::iterator I = MBB.end();
  896. if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
  897. return false;
  898. If a block ends with a single unconditional branch instruction, then
  899. ``AnalyzeBranch`` (shown below) should return the destination of that branch in
  900. the ``TBB`` parameter.
  901. .. code-block:: c++
  902. if (LastOpc == ARM::B || LastOpc == ARM::tB) {
  903. TBB = LastInst->getOperand(0).getMBB();
  904. return false;
  905. }
  906. If a block ends with two unconditional branches, then the second branch is
  907. never reached. In that situation, as shown below, remove the last branch
  908. instruction and return the penultimate branch in the ``TBB`` parameter.
  909. .. code-block:: c++
  910. if ((SecondLastOpc == ARM::B || SecondLastOpc == ARM::tB) &&
  911. (LastOpc == ARM::B || LastOpc == ARM::tB)) {
  912. TBB = SecondLastInst->getOperand(0).getMBB();
  913. I = LastInst;
  914. I->eraseFromParent();
  915. return false;
  916. }
  917. A block may end with a single conditional branch instruction that falls through
  918. to successor block if the condition evaluates to false. In that case,
  919. ``AnalyzeBranch`` (shown below) should return the destination of that
  920. conditional branch in the ``TBB`` parameter and a list of operands in the
  921. ``Cond`` parameter to evaluate the condition.
  922. .. code-block:: c++
  923. if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
  924. // Block ends with fall-through condbranch.
  925. TBB = LastInst->getOperand(0).getMBB();
  926. Cond.push_back(LastInst->getOperand(1));
  927. Cond.push_back(LastInst->getOperand(2));
  928. return false;
  929. }
  930. If a block ends with both a conditional branch and an ensuing unconditional
  931. branch, then ``AnalyzeBranch`` (shown below) should return the conditional
  932. branch destination (assuming it corresponds to a conditional evaluation of
  933. "``true``") in the ``TBB`` parameter and the unconditional branch destination
  934. in the ``FBB`` (corresponding to a conditional evaluation of "``false``"). A
  935. list of operands to evaluate the condition should be returned in the ``Cond``
  936. parameter.
  937. .. code-block:: c++
  938. unsigned SecondLastOpc = SecondLastInst->getOpcode();
  939. if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) ||
  940. (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) {
  941. TBB = SecondLastInst->getOperand(0).getMBB();
  942. Cond.push_back(SecondLastInst->getOperand(1));
  943. Cond.push_back(SecondLastInst->getOperand(2));
  944. FBB = LastInst->getOperand(0).getMBB();
  945. return false;
  946. }
  947. For the last two cases (ending with a single conditional branch or ending with
  948. one conditional and one unconditional branch), the operands returned in the
  949. ``Cond`` parameter can be passed to methods of other instructions to create new
  950. branches or perform other operations. An implementation of ``AnalyzeBranch``
  951. requires the helper methods ``RemoveBranch`` and ``InsertBranch`` to manage
  952. subsequent operations.
  953. ``AnalyzeBranch`` should return false indicating success in most circumstances.
  954. ``AnalyzeBranch`` should only return true when the method is stumped about what
  955. to do, for example, if a block has three terminating branches.
  956. ``AnalyzeBranch`` may return true if it encounters a terminator it cannot
  957. handle, such as an indirect branch.
  958. .. _instruction-selector:
  959. Instruction Selector
  960. ====================
  961. LLVM uses a ``SelectionDAG`` to represent LLVM IR instructions, and nodes of
  962. the ``SelectionDAG`` ideally represent native target instructions. During code
  963. generation, instruction selection passes are performed to convert non-native
  964. DAG instructions into native target-specific instructions. The pass described
  965. in ``XXXISelDAGToDAG.cpp`` is used to match patterns and perform DAG-to-DAG
  966. instruction selection. Optionally, a pass may be defined (in
  967. ``XXXBranchSelector.cpp``) to perform similar DAG-to-DAG operations for branch
  968. instructions. Later, the code in ``XXXISelLowering.cpp`` replaces or removes
  969. operations and data types not supported natively (legalizes) in a
  970. ``SelectionDAG``.
  971. TableGen generates code for instruction selection using the following target
  972. description input files:
  973. * ``XXXInstrInfo.td`` --- Contains definitions of instructions in a
  974. target-specific instruction set, generates ``XXXGenDAGISel.inc``, which is
  975. included in ``XXXISelDAGToDAG.cpp``.
  976. * ``XXXCallingConv.td`` --- Contains the calling and return value conventions
  977. for the target architecture, and it generates ``XXXGenCallingConv.inc``,
  978. which is included in ``XXXISelLowering.cpp``.
  979. The implementation of an instruction selection pass must include a header that
  980. declares the ``FunctionPass`` class or a subclass of ``FunctionPass``. In
  981. ``XXXTargetMachine.cpp``, a Pass Manager (PM) should add each instruction
  982. selection pass into the queue of passes to run.
  983. The LLVM static compiler (``llc``) is an excellent tool for visualizing the
  984. contents of DAGs. To display the ``SelectionDAG`` before or after specific
  985. processing phases, use the command line options for ``llc``, described at
  986. :ref:`SelectionDAG-Process`.
  987. To describe instruction selector behavior, you should add patterns for lowering
  988. LLVM code into a ``SelectionDAG`` as the last parameter of the instruction
  989. definitions in ``XXXInstrInfo.td``. For example, in ``SparcInstrInfo.td``,
  990. this entry defines a register store operation, and the last parameter describes
  991. a pattern with the store DAG operator.
  992. .. code-block:: text
  993. def STrr : F3_1< 3, 0b000100, (outs), (ins MEMrr:$addr, IntRegs:$src),
  994. "st $src, [$addr]", [(store i32:$src, ADDRrr:$addr)]>;
  995. ``ADDRrr`` is a memory mode that is also defined in ``SparcInstrInfo.td``:
  996. .. code-block:: text
  997. def ADDRrr : ComplexPattern<i32, 2, "SelectADDRrr", [], []>;
  998. The definition of ``ADDRrr`` refers to ``SelectADDRrr``, which is a function
  999. defined in an implementation of the Instructor Selector (such as
  1000. ``SparcISelDAGToDAG.cpp``).
  1001. In ``lib/Target/TargetSelectionDAG.td``, the DAG operator for store is defined
  1002. below:
  1003. .. code-block:: text
  1004. def store : PatFrag<(ops node:$val, node:$ptr),
  1005. (st node:$val, node:$ptr), [{
  1006. if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N))
  1007. return !ST->isTruncatingStore() &&
  1008. ST->getAddressingMode() == ISD::UNINDEXED;
  1009. return false;
  1010. }]>;
  1011. ``XXXInstrInfo.td`` also generates (in ``XXXGenDAGISel.inc``) the
  1012. ``SelectCode`` method that is used to call the appropriate processing method
  1013. for an instruction. In this example, ``SelectCode`` calls ``Select_ISD_STORE``
  1014. for the ``ISD::STORE`` opcode.
  1015. .. code-block:: c++
  1016. SDNode *SelectCode(SDValue N) {
  1017. ...
  1018. MVT::ValueType NVT = N.getNode()->getValueType(0);
  1019. switch (N.getOpcode()) {
  1020. case ISD::STORE: {
  1021. switch (NVT) {
  1022. default:
  1023. return Select_ISD_STORE(N);
  1024. break;
  1025. }
  1026. break;
  1027. }
  1028. ...
  1029. The pattern for ``STrr`` is matched, so elsewhere in ``XXXGenDAGISel.inc``,
  1030. code for ``STrr`` is created for ``Select_ISD_STORE``. The ``Emit_22`` method
  1031. is also generated in ``XXXGenDAGISel.inc`` to complete the processing of this
  1032. instruction.
  1033. .. code-block:: c++
  1034. SDNode *Select_ISD_STORE(const SDValue &N) {
  1035. SDValue Chain = N.getOperand(0);
  1036. if (Predicate_store(N.getNode())) {
  1037. SDValue N1 = N.getOperand(1);
  1038. SDValue N2 = N.getOperand(2);
  1039. SDValue CPTmp0;
  1040. SDValue CPTmp1;
  1041. // Pattern: (st:void i32:i32:$src,
  1042. // ADDRrr:i32:$addr)<<P:Predicate_store>>
  1043. // Emits: (STrr:void ADDRrr:i32:$addr, IntRegs:i32:$src)
  1044. // Pattern complexity = 13 cost = 1 size = 0
  1045. if (SelectADDRrr(N, N2, CPTmp0, CPTmp1) &&
  1046. N1.getNode()->getValueType(0) == MVT::i32 &&
  1047. N2.getNode()->getValueType(0) == MVT::i32) {
  1048. return Emit_22(N, SP::STrr, CPTmp0, CPTmp1);
  1049. }
  1050. ...
  1051. The SelectionDAG Legalize Phase
  1052. -------------------------------
  1053. The Legalize phase converts a DAG to use types and operations that are natively
  1054. supported by the target. For natively unsupported types and operations, you
  1055. need to add code to the target-specific ``XXXTargetLowering`` implementation to
  1056. convert unsupported types and operations to supported ones.
  1057. In the constructor for the ``XXXTargetLowering`` class, first use the
  1058. ``addRegisterClass`` method to specify which types are supported and which
  1059. register classes are associated with them. The code for the register classes
  1060. are generated by TableGen from ``XXXRegisterInfo.td`` and placed in
  1061. ``XXXGenRegisterInfo.h.inc``. For example, the implementation of the
  1062. constructor for the SparcTargetLowering class (in ``SparcISelLowering.cpp``)
  1063. starts with the following code:
  1064. .. code-block:: c++
  1065. addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
  1066. addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
  1067. addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
  1068. You should examine the node types in the ``ISD`` namespace
  1069. (``include/llvm/CodeGen/SelectionDAGNodes.h``) and determine which operations
  1070. the target natively supports. For operations that do **not** have native
  1071. support, add a callback to the constructor for the ``XXXTargetLowering`` class,
  1072. so the instruction selection process knows what to do. The ``TargetLowering``
  1073. class callback methods (declared in ``llvm/Target/TargetLowering.h``) are:
  1074. * ``setOperationAction`` --- General operation.
  1075. * ``setLoadExtAction`` --- Load with extension.
  1076. * ``setTruncStoreAction`` --- Truncating store.
  1077. * ``setIndexedLoadAction`` --- Indexed load.
  1078. * ``setIndexedStoreAction`` --- Indexed store.
  1079. * ``setConvertAction`` --- Type conversion.
  1080. * ``setCondCodeAction`` --- Support for a given condition code.
  1081. Note: on older releases, ``setLoadXAction`` is used instead of
  1082. ``setLoadExtAction``. Also, on older releases, ``setCondCodeAction`` may not
  1083. be supported. Examine your release to see what methods are specifically
  1084. supported.
  1085. These callbacks are used to determine that an operation does or does not work
  1086. with a specified type (or types). And in all cases, the third parameter is a
  1087. ``LegalAction`` type enum value: ``Promote``, ``Expand``, ``Custom``, or
  1088. ``Legal``. ``SparcISelLowering.cpp`` contains examples of all four
  1089. ``LegalAction`` values.
  1090. Promote
  1091. ^^^^^^^
  1092. For an operation without native support for a given type, the specified type
  1093. may be promoted to a larger type that is supported. For example, SPARC does
  1094. not support a sign-extending load for Boolean values (``i1`` type), so in
  1095. ``SparcISelLowering.cpp`` the third parameter below, ``Promote``, changes
  1096. ``i1`` type values to a large type before loading.
  1097. .. code-block:: c++
  1098. setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
  1099. Expand
  1100. ^^^^^^
  1101. For a type without native support, a value may need to be broken down further,
  1102. rather than promoted. For an operation without native support, a combination
  1103. of other operations may be used to similar effect. In SPARC, the
  1104. floating-point sine and cosine trig operations are supported by expansion to
  1105. other operations, as indicated by the third parameter, ``Expand``, to
  1106. ``setOperationAction``:
  1107. .. code-block:: c++
  1108. setOperationAction(ISD::FSIN, MVT::f32, Expand);
  1109. setOperationAction(ISD::FCOS, MVT::f32, Expand);
  1110. Custom
  1111. ^^^^^^
  1112. For some operations, simple type promotion or operation expansion may be
  1113. insufficient. In some cases, a special intrinsic function must be implemented.
  1114. For example, a constant value may require special treatment, or an operation
  1115. may require spilling and restoring registers in the stack and working with
  1116. register allocators.
  1117. As seen in ``SparcISelLowering.cpp`` code below, to perform a type conversion
  1118. from a floating point value to a signed integer, first the
  1119. ``setOperationAction`` should be called with ``Custom`` as the third parameter:
  1120. .. code-block:: c++
  1121. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
  1122. In the ``LowerOperation`` method, for each ``Custom`` operation, a case
  1123. statement should be added to indicate what function to call. In the following
  1124. code, an ``FP_TO_SINT`` opcode will call the ``LowerFP_TO_SINT`` method:
  1125. .. code-block:: c++
  1126. SDValue SparcTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
  1127. switch (Op.getOpcode()) {
  1128. case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
  1129. ...
  1130. }
  1131. }
  1132. Finally, the ``LowerFP_TO_SINT`` method is implemented, using an FP register to
  1133. convert the floating-point value to an integer.
  1134. .. code-block:: c++
  1135. static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
  1136. assert(Op.getValueType() == MVT::i32);
  1137. Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
  1138. return DAG.getNode(ISD::BITCAST, MVT::i32, Op);
  1139. }
  1140. Legal
  1141. ^^^^^
  1142. The ``Legal`` ``LegalizeAction`` enum value simply indicates that an operation
  1143. **is** natively supported. ``Legal`` represents the default condition, so it
  1144. is rarely used. In ``SparcISelLowering.cpp``, the action for ``CTPOP`` (an
  1145. operation to count the bits set in an integer) is natively supported only for
  1146. SPARC v9. The following code enables the ``Expand`` conversion technique for
  1147. non-v9 SPARC implementations.
  1148. .. code-block:: c++
  1149. setOperationAction(ISD::CTPOP, MVT::i32, Expand);
  1150. ...
  1151. if (TM.getSubtarget<SparcSubtarget>().isV9())
  1152. setOperationAction(ISD::CTPOP, MVT::i32, Legal);
  1153. Calling Conventions
  1154. -------------------
  1155. To support target-specific calling conventions, ``XXXGenCallingConv.td`` uses
  1156. interfaces (such as ``CCIfType`` and ``CCAssignToReg``) that are defined in
  1157. ``lib/Target/TargetCallingConv.td``. TableGen can take the target descriptor
  1158. file ``XXXGenCallingConv.td`` and generate the header file
  1159. ``XXXGenCallingConv.inc``, which is typically included in
  1160. ``XXXISelLowering.cpp``. You can use the interfaces in
  1161. ``TargetCallingConv.td`` to specify:
  1162. * The order of parameter allocation.
  1163. * Where parameters and return values are placed (that is, on the stack or in
  1164. registers).
  1165. * Which registers may be used.
  1166. * Whether the caller or callee unwinds the stack.
  1167. The following example demonstrates the use of the ``CCIfType`` and
  1168. ``CCAssignToReg`` interfaces. If the ``CCIfType`` predicate is true (that is,
  1169. if the current argument is of type ``f32`` or ``f64``), then the action is
  1170. performed. In this case, the ``CCAssignToReg`` action assigns the argument
  1171. value to the first available register: either ``R0`` or ``R1``.
  1172. .. code-block:: text
  1173. CCIfType<[f32,f64], CCAssignToReg<[R0, R1]>>
  1174. ``SparcCallingConv.td`` contains definitions for a target-specific return-value
  1175. calling convention (``RetCC_Sparc32``) and a basic 32-bit C calling convention
  1176. (``CC_Sparc32``). The definition of ``RetCC_Sparc32`` (shown below) indicates
  1177. which registers are used for specified scalar return types. A single-precision
  1178. float is returned to register ``F0``, and a double-precision float goes to
  1179. register ``D0``. A 32-bit integer is returned in register ``I0`` or ``I1``.
  1180. .. code-block:: text
  1181. def RetCC_Sparc32 : CallingConv<[
  1182. CCIfType<[i32], CCAssignToReg<[I0, I1]>>,
  1183. CCIfType<[f32], CCAssignToReg<[F0]>>,
  1184. CCIfType<[f64], CCAssignToReg<[D0]>>
  1185. ]>;
  1186. The definition of ``CC_Sparc32`` in ``SparcCallingConv.td`` introduces
  1187. ``CCAssignToStack``, which assigns the value to a stack slot with the specified
  1188. size and alignment. In the example below, the first parameter, 4, indicates
  1189. the size of the slot, and the second parameter, also 4, indicates the stack
  1190. alignment along 4-byte units. (Special cases: if size is zero, then the ABI
  1191. size is used; if alignment is zero, then the ABI alignment is used.)
  1192. .. code-block:: text
  1193. def CC_Sparc32 : CallingConv<[
  1194. // All arguments get passed in integer registers if there is space.
  1195. CCIfType<[i32, f32, f64], CCAssignToReg<[I0, I1, I2, I3, I4, I5]>>,
  1196. CCAssignToStack<4, 4>
  1197. ]>;
  1198. ``CCDelegateTo`` is another commonly used interface, which tries to find a
  1199. specified sub-calling convention, and, if a match is found, it is invoked. In
  1200. the following example (in ``X86CallingConv.td``), the definition of
  1201. ``RetCC_X86_32_C`` ends with ``CCDelegateTo``. After the current value is
  1202. assigned to the register ``ST0`` or ``ST1``, the ``RetCC_X86Common`` is
  1203. invoked.
  1204. .. code-block:: text
  1205. def RetCC_X86_32_C : CallingConv<[
  1206. CCIfType<[f32], CCAssignToReg<[ST0, ST1]>>,
  1207. CCIfType<[f64], CCAssignToReg<[ST0, ST1]>>,
  1208. CCDelegateTo<RetCC_X86Common>
  1209. ]>;
  1210. ``CCIfCC`` is an interface that attempts to match the given name to the current
  1211. calling convention. If the name identifies the current calling convention,
  1212. then a specified action is invoked. In the following example (in
  1213. ``X86CallingConv.td``), if the ``Fast`` calling convention is in use, then
  1214. ``RetCC_X86_32_Fast`` is invoked. If the ``SSECall`` calling convention is in
  1215. use, then ``RetCC_X86_32_SSE`` is invoked.
  1216. .. code-block:: text
  1217. def RetCC_X86_32 : CallingConv<[
  1218. CCIfCC<"CallingConv::Fast", CCDelegateTo<RetCC_X86_32_Fast>>,
  1219. CCIfCC<"CallingConv::X86_SSECall", CCDelegateTo<RetCC_X86_32_SSE>>,
  1220. CCDelegateTo<RetCC_X86_32_C>
  1221. ]>;
  1222. Other calling convention interfaces include:
  1223. * ``CCIf <predicate, action>`` --- If the predicate matches, apply the action.
  1224. * ``CCIfInReg <action>`` --- If the argument is marked with the "``inreg``"
  1225. attribute, then apply the action.
  1226. * ``CCIfNest <action>`` --- If the argument is marked with the "``nest``"
  1227. attribute, then apply the action.
  1228. * ``CCIfNotVarArg <action>`` --- If the current function does not take a
  1229. variable number of arguments, apply the action.
  1230. * ``CCAssignToRegWithShadow <registerList, shadowList>`` --- similar to
  1231. ``CCAssignToReg``, but with a shadow list of registers.
  1232. * ``CCPassByVal <size, align>`` --- Assign value to a stack slot with the
  1233. minimum specified size and alignment.
  1234. * ``CCPromoteToType <type>`` --- Promote the current value to the specified
  1235. type.
  1236. * ``CallingConv <[actions]>`` --- Define each calling convention that is
  1237. supported.
  1238. Assembly Printer
  1239. ================
  1240. During the code emission stage, the code generator may utilize an LLVM pass to
  1241. produce assembly output. To do this, you want to implement the code for a
  1242. printer that converts LLVM IR to a GAS-format assembly language for your target
  1243. machine, using the following steps:
  1244. * Define all the assembly strings for your target, adding them to the
  1245. instructions defined in the ``XXXInstrInfo.td`` file. (See
  1246. :ref:`instruction-set`.) TableGen will produce an output file
  1247. (``XXXGenAsmWriter.inc``) with an implementation of the ``printInstruction``
  1248. method for the ``XXXAsmPrinter`` class.
  1249. * Write ``XXXTargetAsmInfo.h``, which contains the bare-bones declaration of
  1250. the ``XXXTargetAsmInfo`` class (a subclass of ``TargetAsmInfo``).
  1251. * Write ``XXXTargetAsmInfo.cpp``, which contains target-specific values for
  1252. ``TargetAsmInfo`` properties and sometimes new implementations for methods.
  1253. * Write ``XXXAsmPrinter.cpp``, which implements the ``AsmPrinter`` class that
  1254. performs the LLVM-to-assembly conversion.
  1255. The code in ``XXXTargetAsmInfo.h`` is usually a trivial declaration of the
  1256. ``XXXTargetAsmInfo`` class for use in ``XXXTargetAsmInfo.cpp``. Similarly,
  1257. ``XXXTargetAsmInfo.cpp`` usually has a few declarations of ``XXXTargetAsmInfo``
  1258. replacement values that override the default values in ``TargetAsmInfo.cpp``.
  1259. For example in ``SparcTargetAsmInfo.cpp``:
  1260. .. code-block:: c++
  1261. SparcTargetAsmInfo::SparcTargetAsmInfo(const SparcTargetMachine &TM) {
  1262. Data16bitsDirective = "\t.half\t";
  1263. Data32bitsDirective = "\t.word\t";
  1264. Data64bitsDirective = 0; // .xword is only supported by V9.
  1265. ZeroDirective = "\t.skip\t";
  1266. CommentString = "!";
  1267. ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
  1268. }
  1269. The X86 assembly printer implementation (``X86TargetAsmInfo``) is an example
  1270. where the target specific ``TargetAsmInfo`` class uses an overridden methods:
  1271. ``ExpandInlineAsm``.
  1272. A target-specific implementation of ``AsmPrinter`` is written in
  1273. ``XXXAsmPrinter.cpp``, which implements the ``AsmPrinter`` class that converts
  1274. the LLVM to printable assembly. The implementation must include the following
  1275. headers that have declarations for the ``AsmPrinter`` and
  1276. ``MachineFunctionPass`` classes. The ``MachineFunctionPass`` is a subclass of
  1277. ``FunctionPass``.
  1278. .. code-block:: c++
  1279. #include "llvm/CodeGen/AsmPrinter.h"
  1280. #include "llvm/CodeGen/MachineFunctionPass.h"
  1281. As a ``FunctionPass``, ``AsmPrinter`` first calls ``doInitialization`` to set
  1282. up the ``AsmPrinter``. In ``SparcAsmPrinter``, a ``Mangler`` object is
  1283. instantiated to process variable names.
  1284. In ``XXXAsmPrinter.cpp``, the ``runOnMachineFunction`` method (declared in
  1285. ``MachineFunctionPass``) must be implemented for ``XXXAsmPrinter``. In
  1286. ``MachineFunctionPass``, the ``runOnFunction`` method invokes
  1287. ``runOnMachineFunction``. Target-specific implementations of
  1288. ``runOnMachineFunction`` differ, but generally do the following to process each
  1289. machine function:
  1290. * Call ``SetupMachineFunction`` to perform initialization.
  1291. * Call ``EmitConstantPool`` to print out (to the output stream) constants which
  1292. have been spilled to memory.
  1293. * Call ``EmitJumpTableInfo`` to print out jump tables used by the current
  1294. function.
  1295. * Print out the label for the current function.
  1296. * Print out the code for the function, including basic block labels and the
  1297. assembly for the instruction (using ``printInstruction``)
  1298. The ``XXXAsmPrinter`` implementation must also include the code generated by
  1299. TableGen that is output in the ``XXXGenAsmWriter.inc`` file. The code in
  1300. ``XXXGenAsmWriter.inc`` contains an implementation of the ``printInstruction``
  1301. method that may call these methods:
  1302. * ``printOperand``
  1303. * ``printMemOperand``
  1304. * ``printCCOperand`` (for conditional statements)
  1305. * ``printDataDirective``
  1306. * ``printDeclare``
  1307. * ``printImplicitDef``
  1308. * ``printInlineAsm``
  1309. The implementations of ``printDeclare``, ``printImplicitDef``,
  1310. ``printInlineAsm``, and ``printLabel`` in ``AsmPrinter.cpp`` are generally
  1311. adequate for printing assembly and do not need to be overridden.
  1312. The ``printOperand`` method is implemented with a long ``switch``/``case``
  1313. statement for the type of operand: register, immediate, basic block, external
  1314. symbol, global address, constant pool index, or jump table index. For an
  1315. instruction with a memory address operand, the ``printMemOperand`` method
  1316. should be implemented to generate the proper output. Similarly,
  1317. ``printCCOperand`` should be used to print a conditional operand.
  1318. ``doFinalization`` should be overridden in ``XXXAsmPrinter``, and it should be
  1319. called to shut down the assembly printer. During ``doFinalization``, global
  1320. variables and constants are printed to output.
  1321. Subtarget Support
  1322. =================
  1323. Subtarget support is used to inform the code generation process of instruction
  1324. set variations for a given chip set. For example, the LLVM SPARC
  1325. implementation provided covers three major versions of the SPARC microprocessor
  1326. architecture: Version 8 (V8, which is a 32-bit architecture), Version 9 (V9, a
  1327. 64-bit architecture), and the UltraSPARC architecture. V8 has 16
  1328. double-precision floating-point registers that are also usable as either 32
  1329. single-precision or 8 quad-precision registers. V8 is also purely big-endian.
  1330. V9 has 32 double-precision floating-point registers that are also usable as 16
  1331. quad-precision registers, but cannot be used as single-precision registers.
  1332. The UltraSPARC architecture combines V9 with UltraSPARC Visual Instruction Set
  1333. extensions.
  1334. If subtarget support is needed, you should implement a target-specific
  1335. ``XXXSubtarget`` class for your architecture. This class should process the
  1336. command-line options ``-mcpu=`` and ``-mattr=``.
  1337. TableGen uses definitions in the ``Target.td`` and ``Sparc.td`` files to
  1338. generate code in ``SparcGenSubtarget.inc``. In ``Target.td``, shown below, the
  1339. ``SubtargetFeature`` interface is defined. The first 4 string parameters of
  1340. the ``SubtargetFeature`` interface are a feature name, an attribute set by the
  1341. feature, the value of the attribute, and a description of the feature. (The
  1342. fifth parameter is a list of features whose presence is implied, and its
  1343. default value is an empty array.)
  1344. .. code-block:: text
  1345. class SubtargetFeature<string n, string a, string v, string d,
  1346. list<SubtargetFeature> i = []> {
  1347. string Name = n;
  1348. string Attribute = a;
  1349. string Value = v;
  1350. string Desc = d;
  1351. list<SubtargetFeature> Implies = i;
  1352. }
  1353. In the ``Sparc.td`` file, the ``SubtargetFeature`` is used to define the
  1354. following features.
  1355. .. code-block:: text
  1356. def FeatureV9 : SubtargetFeature<"v9", "IsV9", "true",
  1357. "Enable SPARC-V9 instructions">;
  1358. def FeatureV8Deprecated : SubtargetFeature<"deprecated-v8",
  1359. "V8DeprecatedInsts", "true",
  1360. "Enable deprecated V8 instructions in V9 mode">;
  1361. def FeatureVIS : SubtargetFeature<"vis", "IsVIS", "true",
  1362. "Enable UltraSPARC Visual Instruction Set extensions">;
  1363. Elsewhere in ``Sparc.td``, the ``Proc`` class is defined and then is used to
  1364. define particular SPARC processor subtypes that may have the previously
  1365. described features.
  1366. .. code-block:: text
  1367. class Proc<string Name, list<SubtargetFeature> Features>
  1368. : Processor<Name, NoItineraries, Features>;
  1369. def : Proc<"generic", []>;
  1370. def : Proc<"v8", []>;
  1371. def : Proc<"supersparc", []>;
  1372. def : Proc<"sparclite", []>;
  1373. def : Proc<"f934", []>;
  1374. def : Proc<"hypersparc", []>;
  1375. def : Proc<"sparclite86x", []>;
  1376. def : Proc<"sparclet", []>;
  1377. def : Proc<"tsc701", []>;
  1378. def : Proc<"v9", [FeatureV9]>;
  1379. def : Proc<"ultrasparc", [FeatureV9, FeatureV8Deprecated]>;
  1380. def : Proc<"ultrasparc3", [FeatureV9, FeatureV8Deprecated]>;
  1381. def : Proc<"ultrasparc3-vis", [FeatureV9, FeatureV8Deprecated, FeatureVIS]>;
  1382. From ``Target.td`` and ``Sparc.td`` files, the resulting
  1383. ``SparcGenSubtarget.inc`` specifies enum values to identify the features,
  1384. arrays of constants to represent the CPU features and CPU subtypes, and the
  1385. ``ParseSubtargetFeatures`` method that parses the features string that sets
  1386. specified subtarget options. The generated ``SparcGenSubtarget.inc`` file
  1387. should be included in the ``SparcSubtarget.cpp``. The target-specific
  1388. implementation of the ``XXXSubtarget`` method should follow this pseudocode:
  1389. .. code-block:: c++
  1390. XXXSubtarget::XXXSubtarget(const Module &M, const std::string &FS) {
  1391. // Set the default features
  1392. // Determine default and user specified characteristics of the CPU
  1393. // Call ParseSubtargetFeatures(FS, CPU) to parse the features string
  1394. // Perform any additional operations
  1395. }
  1396. JIT Support
  1397. ===========
  1398. The implementation of a target machine optionally includes a Just-In-Time (JIT)
  1399. code generator that emits machine code and auxiliary structures as binary
  1400. output that can be written directly to memory. To do this, implement JIT code
  1401. generation by performing the following steps:
  1402. * Write an ``XXXCodeEmitter.cpp`` file that contains a machine function pass
  1403. that transforms target-machine instructions into relocatable machine
  1404. code.
  1405. * Write an ``XXXJITInfo.cpp`` file that implements the JIT interfaces for
  1406. target-specific code-generation activities, such as emitting machine code and
  1407. stubs.
  1408. * Modify ``XXXTargetMachine`` so that it provides a ``TargetJITInfo`` object
  1409. through its ``getJITInfo`` method.
  1410. There are several different approaches to writing the JIT support code. For
  1411. instance, TableGen and target descriptor files may be used for creating a JIT
  1412. code generator, but are not mandatory. For the Alpha and PowerPC target
  1413. machines, TableGen is used to generate ``XXXGenCodeEmitter.inc``, which
  1414. contains the binary coding of machine instructions and the
  1415. ``getBinaryCodeForInstr`` method to access those codes. Other JIT
  1416. implementations do not.
  1417. Both ``XXXJITInfo.cpp`` and ``XXXCodeEmitter.cpp`` must include the
  1418. ``llvm/CodeGen/MachineCodeEmitter.h`` header file that defines the
  1419. ``MachineCodeEmitter`` class containing code for several callback functions
  1420. that write data (in bytes, words, strings, etc.) to the output stream.
  1421. Machine Code Emitter
  1422. --------------------
  1423. In ``XXXCodeEmitter.cpp``, a target-specific of the ``Emitter`` class is
  1424. implemented as a function pass (subclass of ``MachineFunctionPass``). The
  1425. target-specific implementation of ``runOnMachineFunction`` (invoked by
  1426. ``runOnFunction`` in ``MachineFunctionPass``) iterates through the
  1427. ``MachineBasicBlock`` calls ``emitInstruction`` to process each instruction and
  1428. emit binary code. ``emitInstruction`` is largely implemented with case
  1429. statements on the instruction types defined in ``XXXInstrInfo.h``. For
  1430. example, in ``X86CodeEmitter.cpp``, the ``emitInstruction`` method is built
  1431. around the following ``switch``/``case`` statements:
  1432. .. code-block:: c++
  1433. switch (Desc->TSFlags & X86::FormMask) {
  1434. case X86II::Pseudo: // for not yet implemented instructions
  1435. ... // or pseudo-instructions
  1436. break;
  1437. case X86II::RawFrm: // for instructions with a fixed opcode value
  1438. ...
  1439. break;
  1440. case X86II::AddRegFrm: // for instructions that have one register operand
  1441. ... // added to their opcode
  1442. break;
  1443. case X86II::MRMDestReg:// for instructions that use the Mod/RM byte
  1444. ... // to specify a destination (register)
  1445. break;
  1446. case X86II::MRMDestMem:// for instructions that use the Mod/RM byte
  1447. ... // to specify a destination (memory)
  1448. break;
  1449. case X86II::MRMSrcReg: // for instructions that use the Mod/RM byte
  1450. ... // to specify a source (register)
  1451. break;
  1452. case X86II::MRMSrcMem: // for instructions that use the Mod/RM byte
  1453. ... // to specify a source (memory)
  1454. break;
  1455. case X86II::MRM0r: case X86II::MRM1r: // for instructions that operate on
  1456. case X86II::MRM2r: case X86II::MRM3r: // a REGISTER r/m operand and
  1457. case X86II::MRM4r: case X86II::MRM5r: // use the Mod/RM byte and a field
  1458. case X86II::MRM6r: case X86II::MRM7r: // to hold extended opcode data
  1459. ...
  1460. break;
  1461. case X86II::MRM0m: case X86II::MRM1m: // for instructions that operate on
  1462. case X86II::MRM2m: case X86II::MRM3m: // a MEMORY r/m operand and
  1463. case X86II::MRM4m: case X86II::MRM5m: // use the Mod/RM byte and a field
  1464. case X86II::MRM6m: case X86II::MRM7m: // to hold extended opcode data
  1465. ...
  1466. break;
  1467. case X86II::MRMInitReg: // for instructions whose source and
  1468. ... // destination are the same register
  1469. break;
  1470. }
  1471. The implementations of these case statements often first emit the opcode and
  1472. then get the operand(s). Then depending upon the operand, helper methods may
  1473. be called to process the operand(s). For example, in ``X86CodeEmitter.cpp``,
  1474. for the ``X86II::AddRegFrm`` case, the first data emitted (by ``emitByte``) is
  1475. the opcode added to the register operand. Then an object representing the
  1476. machine operand, ``MO1``, is extracted. The helper methods such as
  1477. ``isImmediate``, ``isGlobalAddress``, ``isExternalSymbol``,
  1478. ``isConstantPoolIndex``, and ``isJumpTableIndex`` determine the operand type.
  1479. (``X86CodeEmitter.cpp`` also has private methods such as ``emitConstant``,
  1480. ``emitGlobalAddress``, ``emitExternalSymbolAddress``, ``emitConstPoolAddress``,
  1481. and ``emitJumpTableAddress`` that emit the data into the output stream.)
  1482. .. code-block:: c++
  1483. case X86II::AddRegFrm:
  1484. MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
  1485. if (CurOp != NumOps) {
  1486. const MachineOperand &MO1 = MI.getOperand(CurOp++);
  1487. unsigned Size = X86InstrInfo::sizeOfImm(Desc);
  1488. if (MO1.isImmediate())
  1489. emitConstant(MO1.getImm(), Size);
  1490. else {
  1491. unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
  1492. : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
  1493. if (Opcode == X86::MOV64ri)
  1494. rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?
  1495. if (MO1.isGlobalAddress()) {
  1496. bool NeedStub = isa<Function>(MO1.getGlobal());
  1497. bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());
  1498. emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
  1499. NeedStub, isLazy);
  1500. } else if (MO1.isExternalSymbol())
  1501. emitExternalSymbolAddress(MO1.getSymbolName(), rt);
  1502. else if (MO1.isConstantPoolIndex())
  1503. emitConstPoolAddress(MO1.getIndex(), rt);
  1504. else if (MO1.isJumpTableIndex())
  1505. emitJumpTableAddress(MO1.getIndex(), rt);
  1506. }
  1507. }
  1508. break;
  1509. In the previous example, ``XXXCodeEmitter.cpp`` uses the variable ``rt``, which
  1510. is a ``RelocationType`` enum that may be used to relocate addresses (for
  1511. example, a global address with a PIC base offset). The ``RelocationType`` enum
  1512. for that target is defined in the short target-specific ``XXXRelocations.h``
  1513. file. The ``RelocationType`` is used by the ``relocate`` method defined in
  1514. ``XXXJITInfo.cpp`` to rewrite addresses for referenced global symbols.
  1515. For example, ``X86Relocations.h`` specifies the following relocation types for
  1516. the X86 addresses. In all four cases, the relocated value is added to the
  1517. value already in memory. For ``reloc_pcrel_word`` and ``reloc_picrel_word``,
  1518. there is an additional initial adjustment.
  1519. .. code-block:: c++
  1520. enum RelocationType {
  1521. reloc_pcrel_word = 0, // add reloc value after adjusting for the PC loc
  1522. reloc_picrel_word = 1, // add reloc value after adjusting for the PIC base
  1523. reloc_absolute_word = 2, // absolute relocation; no additional adjustment
  1524. reloc_absolute_dword = 3 // absolute relocation; no additional adjustment
  1525. };
  1526. Target JIT Info
  1527. ---------------
  1528. ``XXXJITInfo.cpp`` implements the JIT interfaces for target-specific
  1529. code-generation activities, such as emitting machine code and stubs. At
  1530. minimum, a target-specific version of ``XXXJITInfo`` implements the following:
  1531. * ``getLazyResolverFunction`` --- Initializes the JIT, gives the target a
  1532. function that is used for compilation.
  1533. * ``emitFunctionStub`` --- Returns a native function with a specified address
  1534. for a callback function.
  1535. * ``relocate`` --- Changes the addresses of referenced globals, based on
  1536. relocation types.
  1537. * Callback function that are wrappers to a function stub that is used when the
  1538. real target is not initially known.
  1539. ``getLazyResolverFunction`` is generally trivial to implement. It makes the
  1540. incoming parameter as the global ``JITCompilerFunction`` and returns the
  1541. callback function that will be used a function wrapper. For the Alpha target
  1542. (in ``AlphaJITInfo.cpp``), the ``getLazyResolverFunction`` implementation is
  1543. simply:
  1544. .. code-block:: c++
  1545. TargetJITInfo::LazyResolverFn AlphaJITInfo::getLazyResolverFunction(
  1546. JITCompilerFn F) {
  1547. JITCompilerFunction = F;
  1548. return AlphaCompilationCallback;
  1549. }
  1550. For the X86 target, the ``getLazyResolverFunction`` implementation is a little
  1551. more complicated, because it returns a different callback function for
  1552. processors with SSE instructions and XMM registers.
  1553. The callback function initially saves and later restores the callee register
  1554. values, incoming arguments, and frame and return address. The callback
  1555. function needs low-level access to the registers or stack, so it is typically
  1556. implemented with assembler.