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