1===============================
2TableGen Programmer's Reference
3===============================
4
5.. sectnum::
6
7.. contents::
8   :local:
9
10Introduction
11============
12
13The purpose of TableGen is to generate complex output files based on
14information from source files that are significantly easier to code than the
15output files would be, and also easier to maintain and modify over time. The
16information is coded in a declarative style involving classes and records,
17which are then processed by TableGen. The internalized records are passed on
18to various backends, which extract information from a subset of the records
19and generate one or more output files. These output files are typically
20``.inc`` files for C++, but may be any type of file that the backend
21developer needs.
22
23This document describes the LLVM TableGen facility in detail. It is intended
24for the programmer who is using TableGen to produce code for a project. If
25you are looking for a simple overview, check out the :doc:`TableGen Overview
26<./index>`.  The various ``xxx-tblgen`` commands used to invoke TableGen are
27described in :doc:`xxx-tblgen: Target Description to C++ Code
28<../CommandGuide/tblgen>`.
29
30An example of a backend is ``RegisterInfo``, which generates the register
31file information for a particular target machine, for use by the LLVM
32target-independent code generator. See :doc:`TableGen Backends <./BackEnds>`
33for a description of the LLVM TableGen backends, and :doc:`TableGen
34Backend Developer's Guide <./BackGuide>` for a guide to writing a new
35backend.
36
37Here are a few of the things backends can do.
38
39* Generate the register file information for a particular target machine.
40
41* Generate the instruction definitions for a target.
42
43* Generate the patterns that the code generator uses to match instructions
44  to intermediate representation (IR) nodes.
45
46* Generate semantic attribute identifiers for Clang.
47
48* Generate abstract syntax tree (AST) declaration node definitions for Clang.
49
50* Generate AST statement node definitions for Clang.
51
52
53Concepts
54--------
55
56TableGen source files contain two primary items: *abstract records* and
57*concrete records*. In this and other TableGen documents, abstract records
58are called *classes.* (These classes are different from C++ classes and do
59not map onto them.) In addition, concrete records are usually just called
60records, although sometimes the term *record* refers to both classes and
61concrete records. The distinction should be clear in context.
62
63Classes and concrete records have a unique *name*, either chosen by
64the programmer or generated by TableGen. Associated with that name
65is a list of *fields* with values and an optional list of *superclasses*
66(sometimes called base or parent classes). The fields are the primary data that
67backends will process. Note that TableGen assigns no meanings to fields; the
68meanings are entirely up to the backends and the programs that incorporate
69the output of those backends.
70
71A backend processes some subset of the concrete records built by the
72TableGen parser and emits the output files. These files are usually C++
73``.inc`` files that are included by the programs that require the data in
74those records. However, a backend can produce any type of output files. For
75example, it could produce a data file containing messages tagged with
76identifiers and substitution parameters. In a complex use case such as the
77LLVM code generator, there can be many concrete records and some of them can
78have an unexpectedly large number of fields, resulting in large output files.
79
80In order to reduce the complexity of TableGen files, classes are used to
81abstract out groups of record fields. For example, a few classes may
82abstract the concept of a machine register file, while other classes may
83abstract the instruction formats, and still others may abstract the
84individual instructions. TableGen allows an arbitrary hierarchy of classes,
85so that the abstract classes for two concepts can share a third superclass that
86abstracts common "sub-concepts" from the two original concepts.
87
88In order to make classes more useful, a concrete record (or another class)
89can request a class as a superclass and pass *template arguments* to it.
90These template arguments can be used in the fields of the superclass to
91initialize them in a custom manner. That is, record or class ``A`` can
92request superclass ``S`` with one set of template arguments, while record or class
93``B`` can request ``S`` with a different set of arguments. Without template
94arguments, many more classes would be required, one for each combination of
95the template arguments.
96
97Both classes and concrete records can include fields that are uninitialized.
98The uninitialized "value" is represented by a question mark (``?``). Classes
99often have uninitialized fields that are expected to be filled in when those
100classes are inherited by concrete records. Even so, some fields of concrete
101records may remain uninitialized.
102
103TableGen provides *multiclasses* to collect a group of record definitions in
104one place. A multiclass is a sort of macro that can be "invoked" to define
105multiple concrete records all at once. A multiclass can inherit from other
106multiclasses, which means that the multiclass inherits all the definitions
107from its parent multiclasses.
108
109`Appendix C: Sample Record`_ illustrates a complex record in the Intel X86
110target and the simple way in which it is defined.
111
112Source Files
113============
114
115TableGen source files are plain ASCII text files. The files can contain
116statements, comments, and blank lines (see `Lexical Analysis`_). The standard file
117extension for TableGen files is ``.td``.
118
119TableGen files can grow quite large, so there is an include mechanism that
120allows one file to include the content of another file (see `Include
121Files`_). This allows large files to be broken up into smaller ones, and
122also provides a simple library mechanism where multiple source files can
123include the same library file.
124
125TableGen supports a simple preprocessor that can be used to conditionalize
126portions of ``.td`` files. See `Preprocessing Facilities`_ for more
127information.
128
129Lexical Analysis
130================
131
132The lexical and syntax notation used here is intended to imitate
133`Python's`_ notation. In particular, for lexical definitions, the productions
134operate at the character level and there is no implied whitespace between
135elements. The syntax definitions operate at the token level, so there is
136implied whitespace between tokens.
137
138.. _`Python's`: http://docs.python.org/py3k/reference/introduction.html#notation
139
140TableGen supports BCPL-style comments (``// ...``) and nestable C-style
141comments (``/* ... */``).
142TableGen also provides simple `Preprocessing Facilities`_.
143
144Formfeed characters may be used freely in files to produce page breaks when
145the file is printed for review.
146
147The following are the basic punctuation tokens::
148
149   - + [ ] { } ( ) < > : ; . ... = ? #
150
151Literals
152--------
153
154Numeric literals take one of the following forms:
155
156.. productionlist::
157   TokInteger: `DecimalInteger` | `HexInteger` | `BinInteger`
158   DecimalInteger: ["+" | "-"] ("0"..."9")+
159   HexInteger: "0x" ("0"..."9" | "a"..."f" | "A"..."F")+
160   BinInteger: "0b" ("0" | "1")+
161
162Observe that the :token:`DecimalInteger` token includes the optional ``+``
163or ``-`` sign, unlike most languages where the sign would be treated as a
164unary operator.
165
166TableGen has two kinds of string literals:
167
168.. productionlist::
169   TokString: '"' (non-'"' characters and escapes) '"'
170   TokCodeFragment: "[{" (shortest text not containing "}]") "}]"
171
172A :token:`TokCodeFragment` is nothing more than a multi-line string literal
173delimited by ``[{`` and ``}]``. It can break across lines.
174
175The current implementation accepts the following escape sequences::
176
177   \\ \' \" \t \n
178
179Identifiers
180-----------
181
182TableGen has name- and identifier-like tokens, which are case-sensitive.
183
184.. productionlist::
185   ualpha: "a"..."z" | "A"..."Z" | "_"
186   TokIdentifier: ("0"..."9")* `ualpha` (`ualpha` | "0"..."9")*
187   TokVarName: "$" `ualpha` (`ualpha` |  "0"..."9")*
188
189Note that, unlike most languages, TableGen allows :token:`TokIdentifier` to
190begin with an integer. In case of ambiguity, a token is interpreted as a
191numeric literal rather than an identifier.
192
193TableGen has the following reserved keywords, which cannot be used as
194identifiers::
195
196   bit        bits          class         code          dag
197   def        else          false         foreach       defm
198   defset     defvar        field         if            in
199   include    int           let           list          multiclass
200   string     then          true
201
202.. warning::
203  The ``field`` reserved word is deprecated.
204
205Bang operators
206--------------
207
208TableGen provides "bang operators" that have a wide variety of uses:
209
210.. productionlist::
211   BangOperator: one of
212               : !add        !and         !cast        !con         !dag
213               : !empty      !eq          !foldl       !foreach     !filter
214               : !ge         !getdagop    !gt          !head        !if
215               : !interleave !isa         !le          !listconcat  !listsplat
216               : !lt         !mul         !ne          !not         !or
217               : !setdagop   !shl         !size        !sra         !srl
218               : !strconcat  !sub         !subst       !tail        !xor
219
220The ``!cond`` operator has a slightly different
221syntax compared to other bang operators, so it is defined separately:
222
223.. productionlist::
224   CondOperator: !cond
225
226See `Appendix A: Bang Operators`_ for a description of each bang operator.
227
228Include files
229-------------
230
231TableGen has an include mechanism. The content of the included file
232lexically replaces the ``include`` directive and is then parsed as if it was
233originally in the main file.
234
235.. productionlist::
236   IncludeDirective: "include" `TokString`
237
238Portions of the main file and included files can be conditionalized using
239preprocessor directives.
240
241.. productionlist::
242   PreprocessorDirective: "#define" | "#ifdef" | "#ifndef"
243
244Types
245=====
246
247The TableGen language is statically typed, using a simple but complete type
248system. Types are used to check for errors, to perform implicit conversions,
249and to help interface designers constrain the allowed input. Every value is
250required to have an associated type.
251
252TableGen supports a mixture of low-level types (e.g., ``bit``) and
253high-level types (e.g., ``dag``). This flexibility allows you to describe a
254wide range of records conveniently and compactly.
255
256.. productionlist::
257   Type: "bit" | "int" | "string" | "code" | "dag"
258       :| "bits" "<" `TokInteger` ">"
259       :| "list" "<" `Type` ">"
260       :| `ClassID`
261   ClassID: `TokIdentifier`
262
263``bit``
264    A ``bit`` is a boolean value that can be 0 or 1.
265
266``int``
267    The ``int`` type represents a simple 64-bit integer value, such as 5 or
268    -42.
269
270``string``
271    The ``string`` type represents an ordered sequence of characters of arbitrary
272    length.
273
274``code``
275    The ``code`` type represents a code fragment. The values are the same as
276    those for the ``string`` type; the ``code`` type is provided just to indicate
277    the programmer's intention.
278
279``bits<``\ *n*\ ``>``
280    The ``bits`` type is a fixed-sized integer of arbitrary length *n* that
281    is treated as separate bits. These bits can be accessed individually.
282    A field of this type is useful for representing an instruction operation
283    code, register number, or address mode/register/displacement.  The bits of
284    the field can be set individually or as subfields. For example, in an
285    instruction address, the addressing mode, base register number, and
286    displacement can be set separately.
287
288``list<``\ *type*\ ``>``
289    This type represents a list whose elements are of the *type* specified in
290    angle brackets. The element type is arbitrary; it can even be another
291    list type. List elements are indexed from 0.
292
293``dag``
294    This type represents a nestable directed acyclic graph (DAG) of nodes.
295    Each node has an *operator* and zero or more *arguments* (or *operands*).
296    An argument can be
297    another ``dag`` object, allowing an arbitrary tree of nodes and edges.
298    As an example, DAGs are used to represent code patterns for use by
299    the code generator instruction selection algorithms. See `Directed
300    acyclic graphs (DAGs)`_ for more details;
301
302:token:`ClassID`
303    Specifying a class name in a type context indicates
304    that the type of the defined value must
305    be a subclass of the specified class.  This is useful in conjunction with
306    the ``list`` type; for example, to constrain the elements of the list to a
307    common base class (e.g., a ``list<Register>`` can only contain definitions
308    derived from the ``Register`` class).
309    The :token:`ClassID` must name a class that has been previously
310    declared or defined.
311
312
313Values and Expressions
314======================
315
316There are many contexts in TableGen statements where a value is required. A
317common example is in the definition of a record, where each field is
318specified by a name and an optional value. TableGen allows for a reasonable
319number of different forms when building up value expressions. These forms
320allow the TableGen file to be written in a syntax that is natural for the
321application.
322
323Note that all of the values have rules for converting them from one type to
324another. For example, these rules allow you to assign a value like ``7``
325to an entity of type ``bits<4>``.
326
327.. productionlist::
328   Value: `SimpleValue` `ValueSuffix`*
329        :| `Value` "#" `Value`
330   ValueSuffix: "{" `RangeList` "}"
331              :| "[" `RangeList` "]"
332              :| "." `TokIdentifier`
333   RangeList: `RangePiece` ("," `RangePiece`)*
334   RangePiece: `TokInteger`
335             :| `TokInteger` "..." `TokInteger`
336             :| `TokInteger` "-" `TokInteger`
337             :| `TokInteger` `TokInteger`
338
339.. warning::
340  The peculiar last form of :token:`RangePiece` is due to the fact that the
341  "``-``" is included in the :token:`TokInteger`, hence ``1-5`` gets lexed as
342  two consecutive tokens, with values ``1`` and ``-5``, instead of "1", "-",
343  and "5". The use of hyphen as the range punctuation is deprecated.
344
345Simple values
346-------------
347
348The :token:`SimpleValue` has a number of forms.
349
350.. productionlist::
351   SimpleValue: `TokInteger` | `TokString`+ | `TokCodeFragment`
352
353A value can be an integer literal, a string literal, or a code fragment
354literal. Multiple adjacent string literals are concatenated as in C/C++; the
355simple value is the concatenation of the strings. Code fragments become
356strings and then are indistinguishable from them.
357
358.. productionlist::
359   SimpleValue2: "true" | "false"
360
361The ``true`` and ``false`` literals are essentially syntactic sugar for the
362integer values 1 and 0. They improve the readability of TableGen files when
363boolean values are used in field initializations, bit sequences, ``if``
364statements.  etc. When parsed, these literals are converted to integers.
365
366.. note::
367
368  Although ``true`` and ``false`` are literal names for 1 and 0, we
369  recommend as a stylistic rule that you use them for boolean
370  values only.
371
372.. productionlist::
373   SimpleValue3: "?"
374
375A question mark represents an uninitialized value.
376
377.. productionlist::
378   SimpleValue4: "{" [`ValueList`] "}"
379   ValueList: `ValueListNE`
380   ValueListNE: `Value` ("," `Value`)*
381
382This value represents a sequence of bits, which can be used to initialize a
383``bits<``\ *n*\ ``>`` field (note the braces). When doing so, the values
384must represent a total of *n* bits.
385
386.. productionlist::
387   SimpleValue5: "[" `ValueList` "]" ["<" `Type` ">"]
388
389This value is a list initializer (note the brackets). The values in brackets
390are the elements of the list. The optional :token:`Type` can be used to
391indicate a specific element type; otherwise the element type is inferred
392from the given values. TableGen can usually infer the type, although
393sometimes not when the value is the empty list (``[]``).
394
395.. productionlist::
396   SimpleValue6: "(" `DagArg` [`DagArgList`] ")"
397   DagArgList: `DagArg` ("," `DagArg`)*
398   DagArg: `Value` [":" `TokVarName`] | `TokVarName`
399
400This represents a DAG initializer (note the parentheses).  The first
401:token:`DagArg` is called the "operator" of the DAG and must be a record.
402See `Directed acyclic graphs (DAGs)`_ for more details.
403
404.. productionlist::
405   SimpleValue7: `TokIdentifier`
406
407The resulting value is the value of the entity named by the identifier. The
408possible identifiers are described here, but the descriptions will make more
409sense after reading the remainder of this guide.
410
411.. The code for this is exceptionally abstruse. These examples are a
412   best-effort attempt.
413
414* A template argument of a ``class``, such as the use of ``Bar`` in::
415
416     class Foo <int Bar> {
417       int Baz = Bar;
418     }
419
420* The implicit template argument ``NAME`` in a ``class`` or ``multiclass``
421  definition (see `NAME`_).
422
423* A field local to a ``class``, such as the use of ``Bar`` in::
424
425     class Foo {
426       int Bar = 5;
427       int Baz = Bar;
428     }
429
430* The name of a record definition, such as the use of ``Bar`` in the
431  definition of ``Foo``::
432
433     def Bar : SomeClass {
434       int X = 5;
435     }
436
437     def Foo {
438       SomeClass Baz = Bar;
439     }
440
441* A field local to a record definition, such as the use of ``Bar`` in::
442
443     def Foo {
444       int Bar = 5;
445       int Baz = Bar;
446     }
447
448  Fields inherited from the record's parent classes can be accessed the same way.
449
450* A template argument of a ``multiclass``, such as the use of ``Bar`` in::
451
452     multiclass Foo <int Bar> {
453       def : SomeClass<Bar>;
454     }
455
456* A variable defined with the ``defvar`` or ``defset`` statements.
457
458* The iteration variable of a ``foreach``, such as the use of ``i`` in::
459
460     foreach i = 0...5 in
461       def Foo#i;
462
463.. productionlist::
464   SimpleValue8: `ClassID` "<" `ValueListNE` ">"
465
466This form creates a new anonymous record definition (as would be created by an
467unnamed ``def`` inheriting from the given class with the given template
468arguments; see `def`_) and the value is that record. A field of the record can be
469obtained using a suffix; see `Suffixed Values`_.
470
471Invoking a class in this manner can provide a simple subroutine facility.
472See `Using Classes as Subroutines`_ for more information.
473
474.. productionlist::
475   SimpleValue9: `BangOperator` ["<" `Type` ">"] "(" `ValueListNE` ")"
476              :| `CondOperator` "(" `CondClause` ("," `CondClause`)* ")"
477   CondClause: `Value` ":" `Value`
478
479The bang operators provide functions that are not available with the other
480simple values. Except in the case of ``!cond``, a bang
481operator takes a list of arguments enclosed in parentheses and performs some
482function on those arguments, producing a value for that
483bang operator. The ``!cond`` operator takes a list of pairs of arguments
484separated by colons. See `Appendix A: Bang Operators`_ for a description of
485each bang operator.
486
487
488Suffixed values
489---------------
490
491The :token:`SimpleValue` values described above can be specified with
492certain suffixes. The purpose of a suffix is to obtain a subvalue of the
493primary value. Here are the possible suffixes for some primary *value*.
494
495*value*\ ``{17}``
496    The final value is bit 17 of the integer *value* (note the braces).
497
498*value*\ ``{8...15}``
499    The final value is bits 8--15 of the integer *value*. The order of the
500    bits can be reversed by specifying ``{15...8}``.
501
502*value*\ ``[4...7,17,2...3,4]``
503    The final value is a new list that is a slice of the list *value* (note
504    the brackets). The
505    new list contains elements 4, 5, 6, 7, 17, 2, 3, and 4. Elements may be
506    included multiple times and in any order.
507
508*value*\ ``.`` *field*
509    The final value is the value of the specified *field* in the specified
510    record *value*.
511
512The paste operator
513------------------
514
515The paste operator (``#``) is the only infix operator availabe in TableGen
516expressions. It allows you to concatenate strings or lists, but has a few
517unusual features.
518
519The paste operator can be used when specifying the record name in a
520:token:`Def` or :token:`Defm` statement, in which case it must construct a
521string. If an operand is an undefined name (:token:`TokIdentifier`) or the
522name of a global :token:`Defvar` or :token:`Defset`, it is treated as a
523verbatim string of characters. The value of a global name is not used.
524
525The paste operator can be used in all other value expressions, in which case
526it can construct a string or a list. Rather oddly, but consistent with the
527previous case, if the *right-hand-side* operand is an undefined name or a
528global name, it is treated as a verbatim string of characters. The
529left-hand-side operand is treated normally.
530
531`Appendix B: Paste Operator Examples`_ presents examples of the behavior of
532the paste operator.
533
534Statements
535==========
536
537The following statements may appear at the top level of TableGen source
538files.
539
540.. productionlist::
541   TableGenFile: `Statement`*
542   Statement: `Class` | `Def` | `Defm` | `Defset` | `Defvar` | `Foreach`
543            :| `If` | `Let` | `MultiClass`
544
545The following sections describe each of these top-level statements.
546
547
548``class`` --- define an abstract record class
549---------------------------------------------
550
551A ``class`` statement defines an abstract record class from which other
552classes and records can inherit.
553
554.. productionlist::
555   Class: "class" `ClassID` [`TemplateArgList`] `RecordBody`
556   TemplateArgList: "<" `TemplateArgDecl` ("," `TemplateArgDecl`)* ">"
557   TemplateArgDecl: `Type` `TokIdentifier` ["=" `Value`]
558
559A class can be parameterized by a list of "template arguments," whose values
560can be used in the class's record body.  These template arguments are
561specified each time the class is inherited by another class or record.
562
563If a template argument is not assigned a default value with ``=``, it is
564uninitialized (has the "value" ``?``) and must be specified in the template
565argument list when the class is inherited. If an argument is assigned a
566default value, then it need not be specified in the argument list. The
567template argument default values are evaluated from left to right.
568
569The :token:`RecordBody` is defined below. It can include a list of
570superclasses from which the current class inherits, along with field definitions
571and other statements. When a class ``C`` inherits from another class ``D``,
572the fields of ``D`` are effectively merged into the fields of ``C``.
573
574A given class can only be defined once. A ``class`` statement is
575considered to define the class if *any* of the following are true (the
576:token:`RecordBody` elements are described below).
577
578* The :token:`TemplateArgList` is present, or
579* The :token:`ParentClassList` in the :token:`RecordBody` is present, or
580* The :token:`Body` in the :token:`RecordBody` is present and not empty.
581
582You can declare an empty class by specifying an empty :token:`TemplateArgList`
583and an empty :token:`RecordBody`. This can serve as a restricted form of
584forward declaration. Note that records derived from a forward-declared
585class will inherit no fields from it, because those records are built when
586their declarations are parsed, and thus before the class is finally defined.
587
588.. _NAME:
589
590Every class has an implicit template argument named ``NAME`` (uppercase),
591which is bound to the name of the :token:`Def` or :token:`Defm` inheriting
592the class. The value of ``NAME`` is undefined if the class is inherited by
593an anonymous record.
594
595See `Examples: classes and records`_ for examples.
596
597Record Bodies
598`````````````
599
600Record bodies appear in both class and record definitions. A record body can
601include a parent class list, which specifies the classes from which the
602current class or record inherits fields. Such classes are called the
603superclasses or parent classes of the class or record. The record body also
604includes the main body of the definition, which contains the specification
605of the fields of the class or record.
606
607.. productionlist::
608   RecordBody: `ParentClassList` `Body`
609   ParentClassList: [":" `ParentClassListNE`]
610   ParentClassListNE: `ClassRef` ("," `ClassRef`)*
611   ClassRef: (`ClassID` | `MultiClassID`) ["<" `ValueList` ">"]
612
613A :token:`ParentClassList` containing a :token:`MultiClassID` is valid only
614in the class list of a ``defm`` statement. In that case, the ID must be the
615name of a multiclass.
616
617.. productionlist::
618   Body: ";" | "{" `BodyItem`* "}"
619   BodyItem: `Type` `TokIdentifier` ["=" `Value`] ";"
620           :| "let" `TokIdentifier` ["{" `RangeList` "}"] "=" `Value` ";"
621           :| "defvar" `TokIdentifier` "=" `Value` ";"
622
623A field definition in the body specifies a field to be included in the class
624or record. If no initial value is specified, then the field's value is
625uninitialized. The type must be specified; TableGen will not infer it from
626the value.
627
628The ``let`` form is used to reset a field to a new value. This can be done
629for fields defined directly in the body or fields inherited from
630superclasses.  A :token:`RangeList` can be specified to reset certain bits
631in a ``bit<n>`` field.
632
633The ``defvar`` form defines a variable whose value can be used in other
634value expressions within the body. The variable is not a field: it does not
635become a field of the class or record being defined. Variables are provided
636to hold temporary values while processing the body. See `Defvar in a Record
637Body`_ for more details.
638
639When class ``C2`` inherits from class ``C1``, it acquires all the field
640definitions of ``C1``. As those definitions are merged into class ``C2``, any
641template arguments passed to ``C1`` by ``C2`` are substituted into the
642definitions. In other words, the abstract record fields defined by ``C1`` are
643expanded with the template arguments before being merged into ``C2``.
644
645
646.. _def:
647
648``def`` --- define a concrete record
649------------------------------------
650
651A ``def`` statement defines a new concrete record.
652
653.. productionlist::
654   Def: "def" [`NameValue`] `RecordBody`
655   NameValue: `Value` (parsed in a special manner)
656
657The name value is optional. If specified, it is parsed in a special mode
658where undefined (unrecognized) identifiers are interpreted as literal
659strings. In particular, global identifiers are considered unrecognized.
660These include global variables defined by ``defvar`` and ``defset``.
661
662If no name value is given, the record is *anonymous*. The final name of an
663anonymous record is unspecified but globally unique.
664
665Special handling occurs if a ``def`` appears inside a ``multiclass``
666statement. See the ``multiclass`` section below for details.
667
668A record can inherit from one or more classes by specifying the
669:token:`ParentClassList` clause at the beginning of its record body. All of
670the fields in the parent classes are added to the record. If two or more
671parent classes provide the same field, the record ends up with the field value
672of the last parent class.
673
674As a special case, the name of a record can be passed in a template argument
675to that record's superclasses. For example:
676
677.. code-block:: text
678
679  class A <dag d> {
680    dag the_dag = d;
681  }
682
683  def rec1 : A<(ops rec1)>
684
685The DAG ``(ops rec1)`` is passed as a template argument to class ``A``. Notice
686that the DAG includes ``rec1``, the record being defined.
687
688The steps taken to create a new record are somewhat complex. See `How
689records are built`_.
690
691See `Examples: classes and records`_ for examples.
692
693
694Examples: classes and records
695-----------------------------
696
697Here is a simple TableGen file with one class and two record definitions.
698
699.. code-block:: text
700
701  class C {
702    bit V = 1;
703  }
704
705  def X : C;
706  def Y : C {
707    let V = 0;
708    string Greeting = "Hello!";
709  }
710
711First, the abstract class ``C`` is defined. It has one field named ``V``
712that is a bit initialized to 1.
713
714Next, two records are defined, derived from class ``C``; that is, with ``C``
715as their superclass. Thus they both inherit the ``V`` field. Record ``Y``
716also defines another string field, ``Greeting``, which is initialized to
717``"Hello!"``. In addition, ``Y`` overrides the inherited ``V`` field,
718setting it to 0.
719
720A class is useful for isolating the common features of multiple records in
721one place. A class can initialize common fields to default values, but
722records inheriting from that class can override the defaults.
723
724TableGen supports the definition of parameterized classes as well as
725nonparameterized ones. Parameterized classes specify a list of variable
726declarations, which may optionally have defaults, that are bound when the
727class is specified as a superclass of another class or record.
728
729.. code-block:: text
730
731  class FPFormat <bits<3> val> {
732    bits<3> Value = val;
733  }
734
735  def NotFP      : FPFormat<0>;
736  def ZeroArgFP  : FPFormat<1>;
737  def OneArgFP   : FPFormat<2>;
738  def OneArgFPRW : FPFormat<3>;
739  def TwoArgFP   : FPFormat<4>;
740  def CompareFP  : FPFormat<5>;
741  def CondMovFP  : FPFormat<6>;
742  def SpecialFP  : FPFormat<7>;
743
744The purpose of the ``FPFormat`` class is to act as a sort of enumerated
745type. It provides a single field, ``Value``, which holds a 3-bit number. Its
746template argument, ``val``, is used to set the ``Value`` field.
747Each of the eight records is defined with ``FPFormat`` as its superclass. The
748enumeration value is passed in angle brackets as the template argument. Each
749record will inherent the ``Value`` field with the appropriate enumeration
750value.
751
752Here is a more complex example of classes with template arguments. First, we
753define a class similar to the ``FPFormat`` class above. It takes a template
754argument and uses it to initialize a field named ``Value``. Then we define
755four records that inherit the ``Value`` field with its four different
756integer values.
757
758.. code-block:: text
759
760  class ModRefVal <bits<2> val> {
761    bits<2> Value = val;
762  }
763
764  def None   : ModRefVal<0>;
765  def Mod    : ModRefVal<1>;
766  def Ref    : ModRefVal<2>;
767  def ModRef : ModRefVal<3>;
768
769This is somewhat contrived, but let's say we would like to examine the two
770bits of the ``Value`` field independently. We can define a class that
771accepts a ``ModRefVal`` record as a template argument and splits up its
772value into two fields, one bit each. Then we can define records that inherit from
773``ModRefBits`` and so acquire two fields from it, one for each bit in the
774``ModRefVal`` record passed as the template argument.
775
776.. code-block:: text
777
778  class ModRefBits <ModRefVal mrv> {
779    // Break the value up into its bits, which can provide a nice
780    // interface to the ModRefVal values.
781    bit isMod = mrv.Value{0};
782    bit isRef = mrv.Value{1};
783  }
784
785  // Example uses.
786  def foo   : ModRefBits<Mod>;
787  def bar   : ModRefBits<Ref>;
788  def snork : ModRefBits<ModRef>;
789
790This illustrates how one class can be defined to reorganize the
791fields in another class, thus hiding the internal representation of that
792other class.
793
794Running ``llvm-tblgen`` on the example prints the following definitions:
795
796.. code-block:: text
797
798  def bar {      // Value
799    bit isMod = 0;
800    bit isRef = 1;
801  }
802  def foo {      // Value
803    bit isMod = 1;
804    bit isRef = 0;
805  }
806  def snork {      // Value
807    bit isMod = 1;
808    bit isRef = 1;
809  }
810
811``let`` --- override fields in classes or records
812-------------------------------------------------
813
814A ``let`` statement collects a set of field values (sometimes called
815*bindings*) and applies them to all the classes and records defined by
816statements within the scope of the ``let``.
817
818.. productionlist::
819   Let:  "let" `LetList` "in" "{" `Statement`* "}"
820      :| "let" `LetList` "in" `Statement`
821   LetList: `LetItem` ("," `LetItem`)*
822   LetItem: `TokIdentifier` ["<" `RangeList` ">"] "=" `Value`
823
824The ``let`` statement establishes a scope, which is a sequence of statements
825in braces or a single statement with no braces. The bindings in the
826:token:`LetList` apply to the statements in that scope.
827
828The field names in the :token:`LetList` must name fields in classes inherited by
829the classes and records defined in the statements. The field values are
830applied to the classes and records *after* the records inherit all the fields from
831their superclasses. So the ``let`` acts to override inherited field
832values. A ``let`` cannot override the value of a template argument.
833
834Top-level ``let`` statements are often useful when a few fields need to be
835overriden in several records. Here are two examples. Note that ``let``
836statements can be nested.
837
838.. code-block:: text
839
840  let isTerminator = 1, isReturn = 1, isBarrier = 1, hasCtrlDep = 1 in
841    def RET : I<0xC3, RawFrm, (outs), (ins), "ret", [(X86retflag 0)]>;
842
843  let isCall = 1 in
844    // All calls clobber the non-callee saved registers...
845    let Defs = [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0,
846                MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7, XMM0, XMM1, XMM2,
847                XMM3, XMM4, XMM5, XMM6, XMM7, EFLAGS] in {
848      def CALLpcrel32 : Ii32<0xE8, RawFrm, (outs), (ins i32imm:$dst, variable_ops),
849                             "call\t${dst:call}", []>;
850      def CALL32r     : I<0xFF, MRM2r, (outs), (ins GR32:$dst, variable_ops),
851                          "call\t{*}$dst", [(X86call GR32:$dst)]>;
852      def CALL32m     : I<0xFF, MRM2m, (outs), (ins i32mem:$dst, variable_ops),
853                          "call\t{*}$dst", []>;
854    }
855
856Note that a top-level ``let`` will not override fields defined in the classes or records
857themselves.
858
859
860``multiclass`` --- define multiple records
861------------------------------------------
862
863While classes with template arguments are a good way to factor out commonality
864between multiple records, multiclasses allow a convenient method for
865defining multiple records at once. For example, consider a 3-address
866instruction architecture whose instructions come in two formats: ``reg = reg
867op reg`` and ``reg = reg op imm`` (e.g., SPARC). We would like to specify in
868one place that these two common formats exist, then in a separate place
869specify what all the operations are. The ``multiclass`` and ``defm``
870statements accomplish this goal. You can think of a multiclass as a macro or
871template that expands into multiple records.
872
873.. productionlist::
874   MultiClass: "multiclass" `TokIdentifier` [`TemplateArgList`]
875             : [":" `ParentMultiClassList`]
876             : "{" `Statement`+ "}"
877   ParentMultiClassList: `MultiClassID` ("," `MultiClassID`)*
878   MultiClassID: `TokIdentifier`
879
880As with regular classes, the multiclass has a name and can accept template
881arguments. A multiclass can inherit from other multiclasses, which causes
882the other multiclasses to be expanded and contribute to the record
883definitions in the inheriting multiclass. The body of the multiclass
884contains a series of statements that define records, using :token:`Def` and
885:token:`Defm`. In addition, :token:`Defvar`, :token:`Foreach`, and
886:token:`Let` statements can be used to factor out even more common elements.
887The :token:`If` statement can also be used.
888
889Also as with regular classes, the multiclass has the implicit template
890argument ``NAME`` (see NAME_). When a named (non-anonymous) record is
891defined in a multiclass and the record's name does not contain a use of the
892template argument ``NAME``, such a use is automatically prepended
893to the name.  That is, the following are equivalent inside a multiclass::
894
895    def Foo ...
896    def NAME#Foo ...
897
898The records defined in a multiclass are instantiated when the multiclass is
899"invoked" by a ``defm`` statement outside the multiclass definition. Each
900``def`` statement produces a record. As with top-level ``def`` statements,
901these definitions can inherit from multiple superclasses.
902
903See `Examples: multiclasses and defms`_ for examples.
904
905
906``defm`` --- invoke multiclasses to define multiple records
907-----------------------------------------------------------
908
909Once multiclasses have been defined, you use the ``defm`` statement to
910"invoke" multiclasses and process the multiple record definitions in those
911multiclasses. Those record definitions are specified by ``def``
912statements in the multiclasses, and indirectly by ``defm`` statements.
913
914.. productionlist::
915   Defm: "defm" [`NameValue`] `ParentClassList` ";"
916
917The optional :token:`NameValue` is formed in the same way as the name of a
918``def``. The :token:`ParentClassList` is a colon followed by a list of at least one
919multiclass and any number of regular classes. The multiclasses must
920precede the regular classes. Note that the ``defm`` does not have a body.
921
922This statement instantiates all the records defined in all the specified
923multiclasses, either directly by ``def`` statements or indirectly by
924``defm`` statements. These records also receive the fields defined in any
925regular classes included in the parent class list. This is useful for adding
926a common set of fields to all the records created by the ``defm``.
927
928The name is parsed in the same special mode used by ``def``. If the name is
929not included, a globally unique name is provided. That is, the following
930examples end up with different names::
931
932    defm    : SomeMultiClass<...>;   // A globally unique name.
933    defm "" : SomeMultiClass<...>;   // An empty name.
934
935The ``defm`` statement can be used in a multiclass body. When this occurs,
936the second variant is equivalent to::
937
938  defm NAME : SomeMultiClass<...>;
939
940More generally, when ``defm`` occurs in a multiclass and its name does not
941include a use of the implicit template argument ``NAME``, then ``NAME`` will
942be prepended automatically. That is, the following are equivalent inside a
943multiclass::
944
945    defm Foo      : SomeMultiClass<...>;
946    defm NAME#Foo : SomeMultiClass<...>;
947
948See `Examples: multiclasses and defms`_ for examples.
949
950Examples: multiclasses and defms
951--------------------------------
952
953Here is a simple example using ``multiclass`` and ``defm``.  Consider a
9543-address instruction architecture whose instructions come in two formats:
955``reg = reg op reg`` and ``reg = reg op imm`` (immediate). The SPARC is an
956example of such an architecture.
957
958.. code-block:: text
959
960  def ops;
961  def GPR;
962  def Imm;
963  class inst <int opc, string asmstr, dag operandlist>;
964
965  multiclass ri_inst <int opc, string asmstr> {
966    def _rr : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
967                     (ops GPR:$dst, GPR:$src1, GPR:$src2)>;
968    def _ri : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
969                     (ops GPR:$dst, GPR:$src1, Imm:$src2)>;
970  }
971
972  // Define records for each instruction in the RR and RI formats.
973  defm ADD : ri_inst<0b111, "add">;
974  defm SUB : ri_inst<0b101, "sub">;
975  defm MUL : ri_inst<0b100, "mul">;
976
977Each use of the ``ri_inst`` multiclass defines two records, one with the
978``_rr`` suffix and one with ``_ri``. Recall that the name of the ``defm``
979that uses a multiclass is prepended to the names of the records defined in
980that multiclass. So the resulting definitions are named::
981
982  ADD_rr, ADD_ri
983  SUB_rr, SUB_ri
984  MUL_rr, MUL_ri
985
986Without the ``multiclass`` feature, the instructions would have to be
987defined as follows.
988
989.. code-block:: text
990
991  def ops;
992  def GPR;
993  def Imm;
994  class inst <int opc, string asmstr, dag operandlist>;
995
996  class rrinst <int opc, string asmstr>
997    : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
998             (ops GPR:$dst, GPR:$src1, GPR:$src2)>;
999
1000  class riinst <int opc, string asmstr>
1001    : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
1002             (ops GPR:$dst, GPR:$src1, Imm:$src2)>;
1003
1004  // Define records for each instruction in the RR and RI formats.
1005  def ADD_rr : rrinst<0b111, "add">;
1006  def ADD_ri : riinst<0b111, "add">;
1007  def SUB_rr : rrinst<0b101, "sub">;
1008  def SUB_ri : riinst<0b101, "sub">;
1009  def MUL_rr : rrinst<0b100, "mul">;
1010  def MUL_ri : riinst<0b100, "mul">;
1011
1012A ``defm`` can be used in a multiclass to "invoke" other multiclasses and
1013create the records defined in those multiclasses in addition to the records
1014defined in the current multiclass. In the following example, the ``basic_s``
1015and ``basic_p`` multiclasses contain ``defm`` statements that refer to the
1016``basic_r`` multiclass. The ``basic_r`` multiclass contains only ``def``
1017statements.
1018
1019.. code-block:: text
1020
1021  class Instruction <bits<4> opc, string Name> {
1022    bits<4> opcode = opc;
1023    string name = Name;
1024  }
1025
1026  multiclass basic_r <bits<4> opc> {
1027    def rr : Instruction<opc, "rr">;
1028    def rm : Instruction<opc, "rm">;
1029  }
1030
1031  multiclass basic_s <bits<4> opc> {
1032    defm SS : basic_r<opc>;
1033    defm SD : basic_r<opc>;
1034    def X : Instruction<opc, "x">;
1035  }
1036
1037  multiclass basic_p <bits<4> opc> {
1038    defm PS : basic_r<opc>;
1039    defm PD : basic_r<opc>;
1040    def Y : Instruction<opc, "y">;
1041  }
1042
1043  defm ADD : basic_s<0xf>, basic_p<0xf>;
1044
1045The final ``defm`` creates the following records, five from the ``basic_s``
1046multiclass and five from the ``basic_p`` multiclass::
1047
1048  ADDSSrr, ADDSSrm
1049  ADDSDrr, ADDSDrm
1050  ADDX
1051  ADDPSrr, ADDPSrm
1052  ADDPDrr, ADDPDrm
1053  ADDY
1054
1055A ``defm`` statement, both at top level and in a multiclass, can inherit
1056from regular classes in addition to multiclasses. The rule is that the
1057regular classes must be listed after the multiclasses, and there must be at least
1058one multiclass.
1059
1060.. code-block:: text
1061
1062  class XD {
1063    bits<4> Prefix = 11;
1064  }
1065  class XS {
1066    bits<4> Prefix = 12;
1067  }
1068  class I <bits<4> op> {
1069    bits<4> opcode = op;
1070  }
1071
1072  multiclass R {
1073    def rr : I<4>;
1074    def rm : I<2>;
1075  }
1076
1077  multiclass Y {
1078    defm SS : R, XD;    // First multiclass R, then regular class XD.
1079    defm SD : R, XS;
1080  }
1081
1082  defm Instr : Y;
1083
1084This example will create four records, shown here in alphabetical order with
1085their fields.
1086
1087.. code-block:: text
1088
1089  def InstrSDrm {
1090    bits<4> opcode = { 0, 0, 1, 0 };
1091    bits<4> Prefix = { 1, 1, 0, 0 };
1092  }
1093
1094  def InstrSDrr {
1095    bits<4> opcode = { 0, 1, 0, 0 };
1096    bits<4> Prefix = { 1, 1, 0, 0 };
1097  }
1098
1099  def InstrSSrm {
1100    bits<4> opcode = { 0, 0, 1, 0 };
1101    bits<4> Prefix = { 1, 0, 1, 1 };
1102  }
1103
1104  def InstrSSrr {
1105    bits<4> opcode = { 0, 1, 0, 0 };
1106    bits<4> Prefix = { 1, 0, 1, 1 };
1107  }
1108
1109It's also possible to use ``let`` statements inside multiclasses, providing
1110another way to factor out commonality from the records, especially when
1111using several levels of multiclass instantiations.
1112
1113.. code-block:: text
1114
1115  multiclass basic_r <bits<4> opc> {
1116    let Predicates = [HasSSE2] in {
1117      def rr : Instruction<opc, "rr">;
1118      def rm : Instruction<opc, "rm">;
1119    }
1120    let Predicates = [HasSSE3] in
1121      def rx : Instruction<opc, "rx">;
1122  }
1123
1124  multiclass basic_ss <bits<4> opc> {
1125    let IsDouble = 0 in
1126      defm SS : basic_r<opc>;
1127
1128    let IsDouble = 1 in
1129      defm SD : basic_r<opc>;
1130  }
1131
1132  defm ADD : basic_ss<0xf>;
1133
1134
1135``defset`` --- create a definition set
1136--------------------------------------
1137
1138The ``defset`` statement is used to collect a set of records into a global
1139list of records.
1140
1141.. productionlist::
1142   Defset: "defset" `Type` `TokIdentifier` "=" "{" `Statement`* "}"
1143
1144All records defined inside the braces via ``def`` and ``defm`` are defined
1145as usual, and they are also collected in a global list of the given name
1146(:token:`TokIdentifier`).
1147
1148The specified type must be ``list<``\ *class*\ ``>``, where *class* is some
1149record class.  The ``defset`` statement establishes a scope for its
1150statements. It is an error to define a record in the scope of the
1151``defset`` that is not of type *class*.
1152
1153The ``defset`` statement can be nested. The inner ``defset`` adds the
1154records to its own set, and all those records are also added to the outer
1155set.
1156
1157Anonymous records created inside initialization expressions using the
1158``ClassID<...>`` syntax are not collected in the set.
1159
1160
1161``defvar`` --- define a variable
1162--------------------------------
1163
1164A ``defvar`` statement defines a global variable. Its value can be used
1165throughout the statements that follow the definition.
1166
1167.. productionlist::
1168   Defvar: "defvar" `TokIdentifier` "=" `Value` ";"
1169
1170The identifier on the left of the ``=`` is defined to be a global variable
1171whose value is given by the value expression on the right of the ``=``. The
1172type of the variable is automatically inferred.
1173
1174Once a variable has been defined, it cannot be set to another value.
1175
1176Variables defined in a top-level ``foreach`` go out of scope at the end of
1177each loop iteration, so their value in one iteration is not available in
1178the next iteration.  The following ``defvar`` will not work::
1179
1180  defvar i = !add(i, 1)
1181
1182Variables can also be defined with ``defvar`` in a record body. See
1183`Defvar in a Record Body`_ for more details.
1184
1185``foreach`` --- iterate over a sequence of statements
1186-----------------------------------------------------
1187
1188The ``foreach`` statement iterates over a series of statements, varying a
1189variable over a sequence of values.
1190
1191.. productionlist::
1192   Foreach: "foreach" `ForeachIterator` "in" "{" `Statement`* "}"
1193          :| "foreach" `ForeachIterator` "in" `Statement`
1194   ForeachIterator: `TokIdentifier` "=" ("{" `RangeList` "}" | `RangePiece` | `Value`)
1195
1196The body of the ``foreach`` is a series of statements in braces or a
1197single statement with no braces. The statements are re-evaluated once for
1198each value in the range list, range piece, or single value. On each
1199iteration, the :token:`TokIdentifier` variable is set to the value and can
1200be used in the statements.
1201
1202The statement list establishes an inner scope. Variables local to a
1203``foreach`` go out of scope at the end of each loop iteration, so their
1204values do not carry over from one iteration to the next. Foreach loops may
1205be nested.
1206
1207The ``foreach`` statement can also be used in a record :token:`Body`.
1208
1209.. Note that the productions involving RangeList and RangePiece have precedence
1210   over the more generic value parsing based on the first token.
1211
1212.. code-block:: text
1213
1214  foreach i = [0, 1, 2, 3] in {
1215    def R#i : Register<...>;
1216    def F#i : Register<...>;
1217  }
1218
1219This loop defines records named ``R0``, ``R1``, ``R2``, and ``R3``, along
1220with ``F0``, ``F1``, ``F2``, and ``F3``.
1221
1222
1223``if`` --- select statements based on a test
1224--------------------------------------------
1225
1226The ``if`` statement allows one of two statement groups to be selected based
1227on the value of an expression.
1228
1229.. productionlist::
1230   If: "if" `Value` "then" `IfBody`
1231     :| "if" `Value` "then" `IfBody` "else" `IfBody`
1232   IfBody: "{" `Statement`* "}" | `Statement`
1233
1234The value expression is evaluated. If it evaluates to true (in the same
1235sense used by the bang operators), then the statements following the
1236``then`` reserved word are processed. Otherwise, if there is an ``else``
1237reserved word, the statements following the ``else`` are processed. If the
1238value is false and there is no ``else`` arm, no statements are processed.
1239
1240Because the braces around the ``then`` statements are optional, this grammar rule
1241has the usual ambiguity with "dangling else" clauses, and it is resolved in
1242the usual way: in a case like ``if v1 then if v2 then {...} else {...}``, the
1243``else`` associates with the inner ``if`` rather than the outer one.
1244
1245The :token:`IfBody` of the then and else arms of the ``if`` establish an
1246inner scope. Any ``defvar`` variables defined in the bodies go out of scope
1247when the bodies are finished (see `Defvar in a Record Body`_ for more details).
1248
1249The ``if`` statement can also be used in a record :token:`Body`.
1250
1251
1252Additional Details
1253==================
1254
1255Directed acyclic graphs (DAGs)
1256------------------------------
1257
1258A directed acyclic graph can be represented directly in TableGen using the
1259``dag`` datatype. A DAG node consists of an operator and zero or more
1260arguments (or operands). Each argument can be of any desired type. By using
1261another DAG node as an argument, an arbitrary graph of DAG nodes can be
1262built.
1263
1264The syntax of a ``dag`` instance is:
1265
1266  ``(`` *operator* *argument1*\ ``,`` *argument2*\ ``,`` ... ``)``
1267
1268The operator must be present and must be a record. There can be zero or more
1269arguments, separated by commas. The operator and arguments can have three
1270formats.
1271
1272====================== =============================================
1273Format                 Meaning
1274====================== =============================================
1275*value*                argument value
1276*value*\ ``:``\ *name* argument value and associated name
1277*name*                 argument name with unset (uninitialized) value
1278====================== =============================================
1279
1280The *value* can be any TableGen value. The *name*, if present, must be a
1281:token:`TokVarName`, which starts with a dollar sign (``$``). The purpose of
1282a name is to tag an operator or argument in a DAG with a particular meaning,
1283or to associate an argument in one DAG with a like-named argument in another
1284DAG.
1285
1286The following bang operators are useful for working with DAGs:
1287``!con``, ``!dag``, ``!empty``, ``!foreach``, ``!getdagop``, ``!setdagop``, ``!size``.
1288
1289Defvar in a record body
1290-----------------------
1291
1292In addition to defining global variables, the ``defvar`` statement can
1293be used inside the :token:`Body` of a class or record definition to define
1294local variables. The scope of the variable extends from the ``defvar``
1295statement to the end of the body. It cannot be set to a different value
1296within its scope. The ``defvar`` statement can also be used in the statement
1297list of a ``foreach``, which establishes a scope.
1298
1299A variable named ``V`` in an inner scope shadows (hides) any variables ``V``
1300in outer scopes. In particular, ``V`` in a record body shadows a global
1301``V``, and ``V`` in a ``foreach`` statement list shadows any ``V`` in
1302surrounding record or global scopes.
1303
1304Variables defined in a ``foreach`` go out of scope at the end of
1305each loop iteration, so their value in one iteration is not available in
1306the next iteration.  The following ``defvar`` will not work::
1307
1308  defvar i = !add(i, 1)
1309
1310How records are built
1311---------------------
1312
1313The following steps are taken by TableGen when a record is built. Classes are simply
1314abstract records and so go through the same steps.
1315
13161. Build the record name (:token:`NameValue`) and create an empty record.
1317
13182. Parse the superclasses in the :token:`ParentClassList` from left to
1319   right, visiting each superclass's ancestor classes from top to bottom.
1320
1321  a. Add the fields from the superclass to the record.
1322  b. Substitute the template arguments into those fields.
1323  c. Add the superclass to the record's list of inherited classes.
1324
13253. Apply any top-level ``let`` bindings to the record. Recall that top-level
1326   bindings only apply to inherited fields.
1327
13284. Parse the body of the record.
1329
1330  * Add any fields to the record.
1331  * Modify the values of fields according to local ``let`` statements.
1332  * Define any ``defvar`` variables.
1333
13345. Make a pass over all the fields to resolve any inter-field references.
1335
13366. Add the record to the master record list.
1337
1338Because references between fields are resolved (step 5) after ``let`` bindings are
1339applied (step 3), the ``let`` statement has unusual power. For example:
1340
1341.. code-block:: text
1342
1343  class C <int x> {
1344    int Y = x;
1345    int Yplus1 = !add(Y, 1);
1346    int xplus1 = !add(x, 1);
1347  }
1348
1349  let Y = 10 in {
1350    def rec1 : C<5> {
1351    }
1352  }
1353
1354  def rec2 : C<5> {
1355    let Y = 10;
1356  }
1357
1358In both cases, one where a top-level ``let`` is used to bind ``Y`` and one
1359where a local ``let`` does the same thing, the results are:
1360
1361.. code-block:: text
1362
1363  def rec1 {      // C
1364    int Y = 10;
1365    int Yplus1 = 11;
1366    int xplus1 = 6;
1367  }
1368  def rec2 {      // C
1369    int Y = 10;
1370    int Yplus1 = 11;
1371    int xplus1 = 6;
1372  }
1373
1374``Yplus1`` is 11 because the ``let Y`` is performed before the ``!add(Y,
13751)`` is resolved. Use this power wisely.
1376
1377
1378Using Classes as Subroutines
1379============================
1380
1381As described in `Simple values`_, a class can be invoked in an expression
1382and passed template arguments. This causes TableGen to create a new anonymous
1383record inheriting from that class. As usual, the record receives all the
1384fields defined in the class.
1385
1386This feature can be employed as a simple subroutine facility. The class can
1387use the template arguments to define various variables and fields, which end
1388up in the anonymous record. Those fields can then be retrieved in the
1389expression invoking the class as follows. Assume that the field ``ret``
1390contains the final value of the subroutine.
1391
1392.. code-block:: text
1393
1394  int Result = ... CalcValue<arg>.ret ...;
1395
1396The ``CalcValue`` class is invoked with the template argument ``arg``. It
1397calculates a value for the ``ret`` field, which is then retrieved at the
1398"point of call" in the initialization for the Result field. The anonymous
1399record created in this example serves no other purpose than to carry the
1400result value.
1401
1402Here is a practical example. The class ``isValidSize`` determines whether a
1403specified number of bytes represents a valid data size. The bit ``ret`` is
1404set appropriately. The field ``ValidSize`` obtains its initial value by
1405invoking ``isValidSize`` with the data size and retrieving the ``ret`` field
1406from the resulting anonymous record.
1407
1408.. code-block:: text
1409
1410  class isValidSize<int size> {
1411    bit ret = !cond(!eq(size,  1): 1,
1412                    !eq(size,  2): 1,
1413                    !eq(size,  4): 1,
1414                    !eq(size,  8): 1,
1415                    !eq(size, 16): 1,
1416                    true: 0);
1417  }
1418
1419  def Data1 {
1420    int Size = ...;
1421    bit ValidSize = isValidSize<Size>.ret;
1422  }
1423
1424Preprocessing Facilities
1425========================
1426
1427The preprocessor embedded in TableGen is intended only for simple
1428conditional compilation. It supports the following directives, which are
1429specified somewhat informally.
1430
1431.. productionlist::
1432   LineBegin: beginning of line
1433   LineEnd: newline | return | EOF
1434   WhiteSpace: space | tab
1435   CComment: "/*" ... "*/"
1436   BCPLComment: "//" ... `LineEnd`
1437   WhiteSpaceOrCComment: `WhiteSpace` | `CComment`
1438   WhiteSpaceOrAnyComment: `WhiteSpace` | `CComment` | `BCPLComment`
1439   MacroName: `ualpha` (`ualpha` | "0"..."9")*
1440   PreDefine: `LineBegin` (`WhiteSpaceOrCComment`)*
1441            : "#define" (`WhiteSpace`)+ `MacroName`
1442            : (`WhiteSpaceOrAnyComment`)* `LineEnd`
1443   PreIfdef: `LineBegin` (`WhiteSpaceOrCComment`)*
1444           : ("#ifdef" | "#ifndef") (`WhiteSpace`)+ `MacroName`
1445           : (`WhiteSpaceOrAnyComment`)* `LineEnd`
1446   PreElse: `LineBegin` (`WhiteSpaceOrCComment`)*
1447          : "#else" (`WhiteSpaceOrAnyComment`)* `LineEnd`
1448   PreEndif: `LineBegin` (`WhiteSpaceOrCComment`)*
1449           : "#endif" (`WhiteSpaceOrAnyComment`)* `LineEnd`
1450
1451..
1452   PreRegContentException: `PreIfdef` | `PreElse` | `PreEndif` | EOF
1453   PreRegion: .* - `PreRegContentException`
1454             :| `PreIfdef`
1455             :  (`PreRegion`)*
1456             :  [`PreElse`]
1457             :  (`PreRegion`)*
1458             :  `PreEndif`
1459
1460A :token:`MacroName` can be defined anywhere in a TableGen file. The name has
1461no value; it can only be tested to see whether it is defined.
1462
1463A macro test region begins with an ``#ifdef`` or ``#ifndef`` directive. If
1464the macro name is defined (``#ifdef``) or undefined (``#ifndef``), then the
1465source code between the directive and the corresponding ``#else`` or
1466``#endif`` is processed. If the test fails but there is an ``#else``
1467clause, the source code between the ``#else`` and the ``#endif`` is
1468processed. If the test fails and there is no ``#else`` clause, then no
1469source code in the test region is processed.
1470
1471Test regions may be nested, but they must be properly nested. A region
1472started in a file must end in that file; that is, must have its
1473``#endif`` in the same file.
1474
1475A :token:`MacroName` may be defined externally using the ``-D`` option on the
1476``xxx-tblgen`` command line::
1477
1478  llvm-tblgen self-reference.td -Dmacro1 -Dmacro3
1479
1480Appendix A: Bang Operators
1481==========================
1482
1483Bang operators act as functions in value expressions. A bang operator takes
1484one or more arguments, operates on them, and produces a result. If the
1485operator produces a boolean result, the result value will be 1 for true or 0
1486for false. When an operator tests a boolean argument, it interprets 0 as false
1487and non-0 as true.
1488
1489.. warning::
1490  The ``!getop`` and ``!setop`` bang operators are deprecated in favor of
1491  ``!getdagop`` and ``!setdagop``.
1492
1493``!add(``\ *a*\ ``,`` *b*\ ``, ...)``
1494    This operator adds *a*, *b*, etc., and produces the sum.
1495
1496``!and(``\ *a*\ ``,`` *b*\ ``, ...)``
1497    This operator does a bitwise AND on *a*, *b*, etc., and produces the
1498    result. A logical AND can be performed if all the arguments are either
1499    0 or 1.
1500
1501``!cast<``\ *type*\ ``>(``\ *a*\ ``)``
1502    This operator performs a cast on *a* and produces the result.
1503    If *a* is not a string, then a straightforward cast is performed, say
1504    between an ``int`` and a ``bit``, or between record types. This allows
1505    casting a record to a class. If a record is cast to ``string``, the
1506    record's name is produced.
1507
1508    If *a* is a string, then it is treated as a record name and looked up in
1509    the list of all defined records. The resulting record is expected to be of
1510    the specified *type*.
1511
1512    For example, if ``!cast<``\ *type*\ ``>(``\ *name*\ ``)``
1513    appears in a multiclass definition, or in a
1514    class instantiated inside a multiclass definition, and the *name* does not
1515    reference any template arguments of the multiclass, then a record by
1516    that name must have been instantiated earlier
1517    in the source file. If *name* does reference
1518    a template argument, then the lookup is delayed until ``defm`` statements
1519    instantiating the multiclass (or later, if the defm occurs in another
1520    multiclass and template arguments of the inner multiclass that are
1521    referenced by *name* are substituted by values that themselves contain
1522    references to template arguments of the outer multiclass).
1523
1524    If the type of *a* does not match *type*, TableGen raises an error.
1525
1526``!con(``\ *a*\ ``,`` *b*\ ``, ...)``
1527    This operator concatenates the DAG nodes *a*, *b*, etc. Their operations
1528    must equal.
1529
1530    ``!con((op a1:$name1, a2:$name2), (op b1:$name3))``
1531
1532    results in the DAG node ``(op a1:$name1, a2:$name2, b1:$name3)``.
1533
1534``!cond(``\ *cond1* ``:`` *val1*\ ``,`` *cond2* ``:`` *val2*\ ``, ...,`` *condn* ``:`` *valn*\ ``)``
1535    This operator tests *cond1* and returns *val1* if the result is true.
1536    If false, the operator tests *cond2* and returns *val2* if the result is
1537    true. And so forth. An error is reported if no conditions are true.
1538
1539    This example produces the sign word for an integer::
1540
1541    !cond(!lt(x, 0) : "negative", !eq(x, 0) : "zero", true : "positive")
1542
1543``!dag(``\ *op*\ ``,`` *arguments*\ ``,`` *names*\ ``)``
1544    This operator creates a DAG node with the given operator and
1545    arguments. The *arguments* and *names* arguments must be lists
1546    of equal length or uninitialized (``?``). The *names* argument
1547    must be of type ``list<string>``.
1548
1549    Due to limitations of the type system, *arguments* must be a list of items
1550    of a common type. In practice, this means that they should either have the
1551    same type or be records with a common superclass. Mixing ``dag`` and
1552    non-``dag`` items is not possible. However, ``?`` can be used.
1553
1554    Example: ``!dag(op, [a1, a2, ?], ["name1", "name2", "name3"])`` results in
1555    ``(op a1-value:$name1, a2-value:$name2, ?:$name3)``.
1556
1557``!empty(``\ *a*\ ``)``
1558    This operator produces 1 if the string, list, or DAG *a* is empty; 0 otherwise.
1559    A dag is empty if it has no arguments; the operator does not count.
1560
1561``!eq(`` *a*\ `,` *b*\ ``)``
1562    This operator produces 1 if *a* is equal to *b*; 0 otherwise.
1563    The arguments must be ``bit``, ``bits``, ``int``, ``string``, or
1564    record values. Use ``!cast<string>`` to compare other types of objects.
1565
1566``!filter(``\ *var*\ ``,`` *list*\ ``,`` *predicate*\ ``)``
1567
1568    This operator creates a new ``list`` by filtering the elements in
1569    *list*. To perform the filtering, TableGen binds the variable *var* to each
1570    element and then evaluates the *predicate* expression, which presumably
1571    refers to *var*. The predicate must
1572    produce a boolean value (``bit``, ``bits``, or ``int``). The value is
1573    interpreted as with ``!if``:
1574    if the value is 0, the element is not included in the new list. If the value
1575    is anything else, the element is included.
1576
1577``!foldl(``\ *init*\ ``,`` *list*\ ``,`` *acc*\ ``,`` *var*\ ``,`` *expr*\ ``)``
1578    This operator performs a left-fold over the items in *list*. The
1579    variable *acc* acts as the accumulator and is initialized to *init*.
1580    The variable *var* is bound to each element in the *list*. The
1581    expression is evaluated for each element and presumably uses *acc* and
1582    *var* to calculate the accumulated value, which ``!foldl`` stores back in
1583    *acc*. The type of *acc* is the same as *init*; the type of *var* is the
1584    same as the elements of *list*; *expr* must have the same type as *init*.
1585
1586    The following example computes the total of the ``Number`` field in the
1587    list of records in ``RecList``::
1588
1589      int x = !foldl(0, RecList, total, rec, !add(total, rec.Number));
1590
1591    If your goal is to filter the list and produce a new list that includes only
1592    some of the elements, see ``!filter``.
1593
1594``!foreach(``\ *var*\ ``,`` *sequence*\ ``,`` *expr*\ ``)``
1595    This operator creates a new ``list``/``dag`` in which each element is a
1596    function of the corresponding element in the *sequence* ``list``/``dag``.
1597    To perform the function, TableGen binds the variable *var* to an element
1598    and then evaluates the expression. The expression presumably refers
1599    to the variable *var* and calculates the result value.
1600
1601    If you simply want to create a list of a certain length containing
1602    the same value repeated multiple times, see ``!listsplat``.
1603
1604``!ge(``\ *a*\ `,` *b*\ ``)``
1605    This operator produces 1 if *a* is greater than or equal to *b*; 0 otherwise.
1606    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.
1607
1608``!getdagop(``\ *dag*\ ``)`` --or-- ``!getdagop<``\ *type*\ ``>(``\ *dag*\ ``)``
1609    This operator produces the operator of the given *dag* node.
1610    Example: ``!getdagop((foo 1, 2))`` results in ``foo``. Recall that
1611    DAG operators are always records.
1612
1613    The result of ``!getdagop`` can be used directly in a context where
1614    any record class at all is acceptable (typically placing it into
1615    another dag value). But in other contexts, it must be explicitly
1616    cast to a particular class. The ``<``\ *type*\ ``>`` syntax is
1617    provided to make this easy.
1618
1619    For example, to assign the result to a value of type ``BaseClass``, you
1620    could write either of these::
1621
1622      BaseClass b = !getdagop<BaseClass>(someDag);
1623      BaseClass b = !cast<BaseClass>(!getdagop(someDag));
1624
1625    But to create a new DAG node that reuses the operator from another, no
1626    cast is necessary::
1627
1628      dag d = !dag(!getdagop(someDag), args, names);
1629
1630``!gt(``\ *a*\ `,` *b*\ ``)``
1631    This operator produces 1 if *a* is greater than *b*; 0 otherwise.
1632    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.
1633
1634``!head(``\ *a*\ ``)``
1635    This operator produces the zeroth element of the list *a*.
1636    (See also ``!tail``.)
1637
1638``!if(``\ *test*\ ``,`` *then*\ ``,`` *else*\ ``)``
1639  This operator evaluates the *test*, which must produce a ``bit`` or
1640  ``int``. If the result is not 0, the *then* expression is produced; otherwise
1641  the *else* expression is produced.
1642
1643``!interleave(``\ *list*\ ``,`` *delim*\ ``)``
1644    This operator concatenates the items in the *list*, interleaving the
1645    *delim* string between each pair, and produces the resulting string.
1646    The list can be a list of string, int, bits, or bit. An empty list
1647    results in an empty string. The delimiter can be the empty string.
1648
1649``!isa<``\ *type*\ ``>(``\ *a*\ ``)``
1650    This operator produces 1 if the type of *a* is a subtype of the given *type*; 0
1651    otherwise.
1652
1653``!le(``\ *a*\ ``,`` *b*\ ``)``
1654    This operator produces 1 if *a* is less than or equal to *b*; 0 otherwise.
1655    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.
1656
1657``!listconcat(``\ *list1*\ ``,`` *list2*\ ``, ...)``
1658    This operator concatenates the list arguments *list1*, *list2*, etc., and
1659    produces the resulting list. The lists must have the same element type.
1660
1661``!listsplat(``\ *value*\ ``,`` *count*\ ``)``
1662    This operator produces a list of length *count* whose elements are all
1663    equal to the *value*. For example, ``!listsplat(42, 3)`` results in
1664    ``[42, 42, 42]``.
1665
1666``!lt(``\ *a*\ `,` *b*\ ``)``
1667    This operator produces 1 if *a* is less than *b*; 0 otherwise.
1668    The arguments must be ``bit``, ``bits``, ``int``, or ``string`` values.
1669
1670``!mul(``\ *a*\ ``,`` *b*\ ``, ...)``
1671    This operator multiplies *a*, *b*, etc., and produces the product.
1672
1673``!ne(``\ *a*\ `,` *b*\ ``)``
1674    This operator produces 1 if *a* is not equal to *b*; 0 otherwise.
1675    The arguments must be ``bit``, ``bits``, ``int``, ``string``,
1676    or record values. Use ``!cast<string>`` to compare other types of objects.
1677
1678``!not(``\ *a*\ ``)``
1679    This operator performs a logical NOT on *a*, which must be
1680    an integer. The argument 0 results in 1 (true); any other
1681    argument results in 0 (false).
1682
1683``!or(``\ *a*\ ``,`` *b*\ ``, ...)``
1684    This operator does a bitwise OR on *a*, *b*, etc., and produces the
1685    result. A logical OR can be performed if all the arguments are either
1686    0 or 1.
1687
1688``!setdagop(``\ *dag*\ ``,`` *op*\ ``)``
1689    This operator produces a DAG node with the same arguments as *dag*, but with its
1690    operator replaced with *op*.
1691
1692    Example: ``!setdagop((foo 1, 2), bar)`` results in ``(bar 1, 2)``.
1693
1694``!shl(``\ *a*\ ``,`` *count*\ ``)``
1695    This operator shifts *a* left logically by *count* bits and produces the resulting
1696    value. The operation is performed on a 64-bit integer; the result
1697    is undefined for shift counts outside 0...63.
1698
1699``!size(``\ *a*\ ``)``
1700    This operator produces the size of the string, list, or dag *a*.
1701    The size of a DAG is the number of arguments; the operator does not count.
1702
1703``!sra(``\ *a*\ ``,`` *count*\ ``)``
1704    This operator shifts *a* right arithmetically by *count* bits and produces the resulting
1705    value. The operation is performed on a 64-bit integer; the result
1706    is undefined for shift counts outside 0...63.
1707
1708``!srl(``\ *a*\ ``,`` *count*\ ``)``
1709    This operator shifts *a* right logically by *count* bits and produces the resulting
1710    value. The operation is performed on a 64-bit integer; the result
1711    is undefined for shift counts outside 0...63.
1712
1713``!strconcat(``\ *str1*\ ``,`` *str2*\ ``, ...)``
1714    This operator concatenates the string arguments *str1*, *str2*, etc., and
1715    produces the resulting string.
1716
1717``!sub(``\ *a*\ ``,`` *b*\ ``)``
1718    This operator subtracts *b* from *a* and produces the arithmetic difference.
1719
1720``!subst(``\ *target*\ ``,`` *repl*\ ``,`` *value*\ ``)``
1721    This operator replaces all occurrences of the *target* in the *value* with
1722    the *repl* and produces the resulting value. The *value* can
1723    be a string, in which case substring substitution is performed.
1724
1725    The *value* can be a record name, in which case the operator produces the *repl*
1726    record if the *target* record name equals the *value* record name; otherwise it
1727    produces the *value*.
1728
1729``!tail(``\ *a*\ ``)``
1730    This operator produces a new list with all the elements
1731    of the list *a* except for the zeroth one. (See also ``!head``.)
1732
1733``!xor(``\ *a*\ ``,`` *b*\ ``, ...)``
1734    This operator does a bitwise EXCLUSIVE OR on *a*, *b*, etc., and produces
1735    the result. A logical XOR can be performed if all the arguments are either
1736    0 or 1.
1737
1738Appendix B: Paste Operator Examples
1739===================================
1740
1741Here is an example illustrating the use of the paste operator in record names.
1742
1743.. code-block:: text
1744
1745  defvar suffix = "_suffstring";
1746  defvar some_ints = [0, 1, 2, 3];
1747
1748  def name # suffix {
1749  }
1750
1751  foreach i = [1, 2] in {
1752  def rec # i {
1753  }
1754  }
1755
1756The first ``def`` does not use the value of the ``suffix`` variable. The
1757second def does use the value of the ``i`` iterator variable, because it is not a
1758global name. The following records are produced.
1759
1760.. code-block:: text
1761
1762  def namesuffix {
1763  }
1764  def rec1 {
1765  }
1766  def rec2 {
1767  }
1768
1769Here is a second example illustrating the paste operator in field value expressions.
1770
1771.. code-block:: text
1772
1773  def test {
1774    string strings = suffix # suffix;
1775    list<int> integers = some_ints # [4, 5, 6];
1776  }
1777
1778The ``strings`` field expression uses ``suffix`` on both sides of the paste
1779operator. It is evaluated normally on the left hand side, but taken verbatim
1780on the right hand side. The ``integers`` field expression uses the value of
1781the ``some_ints`` variable and a literal list. The following record is
1782produced.
1783
1784.. code-block:: text
1785
1786  def test {
1787    string strings = "_suffstringsuffix";
1788    list<int> ints = [0, 1, 2, 3, 4, 5, 6];
1789  }
1790
1791
1792Appendix C: Sample Record
1793=========================
1794
1795One target machine supported by LLVM is the Intel x86. The following output
1796from TableGen shows the record that is created to represent the 32-bit
1797register-to-register ADD instruction.
1798
1799.. code-block:: text
1800
1801  def ADD32rr {	// InstructionEncoding Instruction X86Inst I ITy Sched BinOpRR BinOpRR_RF
1802    int Size = 0;
1803    string DecoderNamespace = "";
1804    list<Predicate> Predicates = [];
1805    string DecoderMethod = "";
1806    bit hasCompleteDecoder = 1;
1807    string Namespace = "X86";
1808    dag OutOperandList = (outs GR32:$dst);
1809    dag InOperandList = (ins GR32:$src1, GR32:$src2);
1810    string AsmString = "add{l}	{$src2, $src1|$src1, $src2}";
1811    EncodingByHwMode EncodingInfos = ?;
1812    list<dag> Pattern = [(set GR32:$dst, EFLAGS, (X86add_flag GR32:$src1, GR32:$src2))];
1813    list<Register> Uses = [];
1814    list<Register> Defs = [EFLAGS];
1815    int CodeSize = 3;
1816    int AddedComplexity = 0;
1817    bit isPreISelOpcode = 0;
1818    bit isReturn = 0;
1819    bit isBranch = 0;
1820    bit isEHScopeReturn = 0;
1821    bit isIndirectBranch = 0;
1822    bit isCompare = 0;
1823    bit isMoveImm = 0;
1824    bit isMoveReg = 0;
1825    bit isBitcast = 0;
1826    bit isSelect = 0;
1827    bit isBarrier = 0;
1828    bit isCall = 0;
1829    bit isAdd = 0;
1830    bit isTrap = 0;
1831    bit canFoldAsLoad = 0;
1832    bit mayLoad = ?;
1833    bit mayStore = ?;
1834    bit mayRaiseFPException = 0;
1835    bit isConvertibleToThreeAddress = 1;
1836    bit isCommutable = 1;
1837    bit isTerminator = 0;
1838    bit isReMaterializable = 0;
1839    bit isPredicable = 0;
1840    bit isUnpredicable = 0;
1841    bit hasDelaySlot = 0;
1842    bit usesCustomInserter = 0;
1843    bit hasPostISelHook = 0;
1844    bit hasCtrlDep = 0;
1845    bit isNotDuplicable = 0;
1846    bit isConvergent = 0;
1847    bit isAuthenticated = 0;
1848    bit isAsCheapAsAMove = 0;
1849    bit hasExtraSrcRegAllocReq = 0;
1850    bit hasExtraDefRegAllocReq = 0;
1851    bit isRegSequence = 0;
1852    bit isPseudo = 0;
1853    bit isExtractSubreg = 0;
1854    bit isInsertSubreg = 0;
1855    bit variadicOpsAreDefs = 0;
1856    bit hasSideEffects = ?;
1857    bit isCodeGenOnly = 0;
1858    bit isAsmParserOnly = 0;
1859    bit hasNoSchedulingInfo = 0;
1860    InstrItinClass Itinerary = NoItinerary;
1861    list<SchedReadWrite> SchedRW = [WriteALU];
1862    string Constraints = "$src1 = $dst";
1863    string DisableEncoding = "";
1864    string PostEncoderMethod = "";
1865    bits<64> TSFlags = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0 };
1866    string AsmMatchConverter = "";
1867    string TwoOperandAliasConstraint = "";
1868    string AsmVariantName = "";
1869    bit UseNamedOperandTable = 0;
1870    bit FastISelShouldIgnore = 0;
1871    bits<8> Opcode = { 0, 0, 0, 0, 0, 0, 0, 1 };
1872    Format Form = MRMDestReg;
1873    bits<7> FormBits = { 0, 1, 0, 1, 0, 0, 0 };
1874    ImmType ImmT = NoImm;
1875    bit ForceDisassemble = 0;
1876    OperandSize OpSize = OpSize32;
1877    bits<2> OpSizeBits = { 1, 0 };
1878    AddressSize AdSize = AdSizeX;
1879    bits<2> AdSizeBits = { 0, 0 };
1880    Prefix OpPrefix = NoPrfx;
1881    bits<3> OpPrefixBits = { 0, 0, 0 };
1882    Map OpMap = OB;
1883    bits<3> OpMapBits = { 0, 0, 0 };
1884    bit hasREX_WPrefix = 0;
1885    FPFormat FPForm = NotFP;
1886    bit hasLockPrefix = 0;
1887    Domain ExeDomain = GenericDomain;
1888    bit hasREPPrefix = 0;
1889    Encoding OpEnc = EncNormal;
1890    bits<2> OpEncBits = { 0, 0 };
1891    bit HasVEX_W = 0;
1892    bit IgnoresVEX_W = 0;
1893    bit EVEX_W1_VEX_W0 = 0;
1894    bit hasVEX_4V = 0;
1895    bit hasVEX_L = 0;
1896    bit ignoresVEX_L = 0;
1897    bit hasEVEX_K = 0;
1898    bit hasEVEX_Z = 0;
1899    bit hasEVEX_L2 = 0;
1900    bit hasEVEX_B = 0;
1901    bits<3> CD8_Form = { 0, 0, 0 };
1902    int CD8_EltSize = 0;
1903    bit hasEVEX_RC = 0;
1904    bit hasNoTrackPrefix = 0;
1905    bits<7> VectSize = { 0, 0, 1, 0, 0, 0, 0 };
1906    bits<7> CD8_Scale = { 0, 0, 0, 0, 0, 0, 0 };
1907    string FoldGenRegForm = ?;
1908    string EVEX2VEXOverride = ?;
1909    bit isMemoryFoldable = 1;
1910    bit notEVEX2VEXConvertible = 0;
1911  }
1912
1913On the first line of the record, you can see that the ``ADD32rr`` record
1914inherited from eight classes. Although the inheritance hierarchy is complex,
1915using superclasses is much simpler than specifying the 109 individual fields for each
1916instruction.
1917
1918Here is the code fragment used to define ``ADD32rr`` and multiple other
1919``ADD`` instructions:
1920
1921.. code-block:: text
1922
1923  defm ADD : ArithBinOp_RF<0x00, 0x02, 0x04, "add", MRM0r, MRM0m,
1924                           X86add_flag, add, 1, 1, 1>;
1925
1926The ``defm`` statement tells TableGen that ``ArithBinOp_RF`` is a
1927multiclass, which contains multiple concrete record definitions that inherit
1928from ``BinOpRR_RF``. That class, in turn, inherits from ``BinOpRR``, which
1929inherits from ``ITy`` and ``Sched``, and so forth. The fields are inherited
1930from all the parent classes; for example, ``IsIndirectBranch`` is inherited
1931from the ``Instruction`` class.
1932