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