2 # Copyright (c) 2018 Linaro Limited
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2 of the License, or (at your option) any later version.
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 # Generate a decoding tree from a specification file.
21 # The tree is built from instruction "patterns". A pattern may represent
22 # a single architectural instruction or a group of same, depending on what
23 # is convenient for further processing.
25 # Each pattern has "fixedbits" & "fixedmask", the combination of which
26 # describes the condition under which the pattern is matched:
28 # (insn & fixedmask) == fixedbits
30 # Each pattern may have "fields", which are extracted from the insn and
31 # passed along to the translator. Examples of such are registers,
32 # immediates, and sub-opcodes.
34 # In support of patterns, one may declare fields, argument sets, and
35 # formats, each of which may be re-used to simplify further definitions.
39 # field_def := '%' identifier ( unnamed_field )+ ( !function=identifier )?
40 # unnamed_field := number ':' ( 's' ) number
42 # For unnamed_field, the first number is the least-significant bit position of
43 # the field and the second number is the length of the field. If the 's' is
44 # present, the field is considered signed. If multiple unnamed_fields are
45 # present, they are concatenated. In this way one can define disjoint fields.
47 # If !function is specified, the concatenated result is passed through the
48 # named function, taking and returning an integral value.
50 # FIXME: the fields of the structure into which this result will be stored
51 # is restricted to "int". Which means that we cannot expand 64-bit items.
55 # %disp 0:s16 -- sextract(i, 0, 16)
56 # %imm9 16:6 10:3 -- extract(i, 16, 6) << 3 | extract(i, 10, 3)
57 # %disp12 0:s1 1:1 2:10 -- sextract(i, 0, 1) << 11
58 # | extract(i, 1, 1) << 10
60 # %shimm8 5:s8 13:1 !function=expand_shimm8
61 # -- expand_shimm8(sextract(i, 5, 8) << 1
62 # | extract(i, 13, 1))
64 # *** Argument set syntax:
66 # args_def := '&' identifier ( args_elt )+ ( !extern )?
67 # args_elt := identifier
69 # Each args_elt defines an argument within the argument set.
70 # Each argument set will be rendered as a C structure "arg_$name"
71 # with each of the fields being one of the member arguments.
73 # If !extern is specified, the backing structure is assumed to
74 # have been already declared, typically via a second decoder.
76 # Argument set examples:
79 # &loadstore reg base offset
83 # fmt_def := '@' identifier ( fmt_elt )+
84 # fmt_elt := fixedbit_elt | field_elt | field_ref | args_ref
85 # fixedbit_elt := [01.-]+
86 # field_elt := identifier ':' 's'? number
87 # field_ref := '%' identifier | identifier '=' '%' identifier
88 # args_ref := '&' identifier
90 # Defining a format is a handy way to avoid replicating groups of fields
91 # across many instruction patterns.
93 # A fixedbit_elt describes a contiguous sequence of bits that must
94 # be 1, 0, [.-] for don't care. The difference between '.' and '-'
95 # is that '.' means that the bit will be covered with a field or a
96 # final [01] from the pattern, and '-' means that the bit is really
97 # ignored by the cpu and will not be specified.
99 # A field_elt describes a simple field only given a width; the position of
100 # the field is implied by its position with respect to other fixedbit_elt
103 # If any fixedbit_elt or field_elt appear then all bits must be defined.
104 # Padding with a fixedbit_elt of all '.' is an easy way to accomplish that.
106 # A field_ref incorporates a field by reference. This is the only way to
107 # add a complex field to a format. A field may be renamed in the process
108 # via assignment to another identifier. This is intended to allow the
109 # same argument set be used with disjoint named fields.
111 # A single args_ref may specify an argument set to use for the format.
112 # The set of fields in the format must be a subset of the arguments in
113 # the argument set. If an argument set is not specified, one will be
114 # inferred from the set of fields.
116 # It is recommended, but not required, that all field_ref and args_ref
117 # appear at the end of the line, not interleaving with fixedbit_elf or
122 # @opr ...... ra:5 rb:5 ... 0 ....... rc:5
123 # @opi ...... ra:5 lit:8 1 ....... rc:5
125 # *** Pattern syntax:
127 # pat_def := identifier ( pat_elt )+
128 # pat_elt := fixedbit_elt | field_elt | field_ref
129 # | args_ref | fmt_ref | const_elt
130 # fmt_ref := '@' identifier
131 # const_elt := identifier '=' number
133 # The fixedbit_elt and field_elt specifiers are unchanged from formats.
134 # A pattern that does not specify a named format will have one inferred
135 # from a referenced argument set (if present) and the set of fields.
137 # A const_elt allows a argument to be set to a constant value. This may
138 # come in handy when fields overlap between patterns and one has to
139 # include the values in the fixedbit_elt instead.
141 # The decoder will call a translator function for each pattern matched.
145 # addl_r 010000 ..... ..... .... 0000000 ..... @opr
146 # addl_i 010000 ..... ..... .... 0000000 ..... @opi
148 # which will, in part, invoke
150 # trans_addl_r(ctx, &arg_opr, insn)
152 # trans_addl_i(ctx, &arg_opi, insn)
161 insnmask = 0xffffffff
167 translate_prefix = 'trans'
168 translate_scope = 'static '
172 insntype = 'uint32_t'
173 decode_function = 'decode'
175 re_ident = '[a-zA-Z][a-zA-Z0-9_]*'
178 def error_with_file(file, lineno, *args):
179 """Print an error message from file:line and args and exit."""
184 r = '{0}:{1}: error:'.format(file, lineno)
186 r = '{0}: error:'.format(file)
193 if output_file and output_fd:
195 os.remove(output_file)
198 def error(lineno, *args):
199 error_with_file(input_file, lineno, args)
207 if sys.version_info >= (3, 0):
208 re_fullmatch = re.fullmatch
210 def re_fullmatch(pat, str):
211 return re.match('^' + pat + '$', str)
214 def output_autogen():
215 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
219 """Return a string with C spaces"""
223 def str_fields(fields):
224 """Return a string uniquely identifing FIELDS"""
226 for n in sorted(fields.keys()):
231 def str_match_bits(bits, mask):
232 """Return a string pretty-printing BITS/MASK"""
235 i = 1 << (insnwidth - 1)
253 """Return true iff X is equal to a power of 2."""
254 return (x & (x - 1)) == 0
258 """Return the number of times 2 factors into X."""
260 while ((x >> r) & 1) == 0:
265 def is_contiguous(bits):
267 if is_pow2((bits >> shift) + 1):
273 def eq_fields_for_args(flds_a, flds_b):
274 if len(flds_a) != len(flds_b):
276 for k, a in flds_a.items():
282 def eq_fields_for_fmts(flds_a, flds_b):
283 if len(flds_a) != len(flds_b):
285 for k, a in flds_a.items():
289 if a.__class__ != b.__class__ or a != b:
295 """Class representing a simple instruction field"""
296 def __init__(self, sign, pos, len):
300 self.mask = ((1 << len) - 1) << pos
307 return str(self.pos) + ':' + s + str(self.len)
309 def str_extract(self):
314 return '{0}(insn, {1}, {2})'.format(extr, self.pos, self.len)
316 def __eq__(self, other):
317 return self.sign == other.sign and self.sign == other.sign
319 def __ne__(self, other):
320 return not self.__eq__(other)
325 """Class representing a compound instruction field"""
326 def __init__(self, subs, mask):
328 self.sign = subs[0].sign
332 return str(self.subs)
334 def str_extract(self):
337 for f in reversed(self.subs):
339 ret = f.str_extract()
341 ret = 'deposit32({0}, {1}, {2}, {3})' \
342 .format(ret, pos, 32 - pos, f.str_extract())
346 def __ne__(self, other):
347 if len(self.subs) != len(other.subs):
349 for a, b in zip(self.subs, other.subs):
350 if a.__class__ != b.__class__ or a != b:
354 def __eq__(self, other):
355 return not self.__ne__(other)
360 """Class representing an argument field with constant value"""
361 def __init__(self, value):
364 self.sign = value < 0
367 return str(self.value)
369 def str_extract(self):
370 return str(self.value)
372 def __cmp__(self, other):
373 return self.value - other.value
378 """Class representing a field passed through an expander"""
379 def __init__(self, func, base):
380 self.mask = base.mask
381 self.sign = base.sign
386 return self.func + '(' + str(self.base) + ')'
388 def str_extract(self):
389 return self.func + '(' + self.base.str_extract() + ')'
391 def __eq__(self, other):
392 return self.func == other.func and self.base == other.base
394 def __ne__(self, other):
395 return not self.__eq__(other)
400 """Class representing the extracted fields of a format"""
401 def __init__(self, nm, flds, extern):
404 self.fields = sorted(flds)
407 return self.name + ' ' + str(self.fields)
409 def struct_name(self):
410 return 'arg_' + self.name
412 def output_def(self):
414 output('typedef struct {\n')
415 for n in self.fields:
416 output(' int ', n, ';\n')
417 output('} ', self.struct_name(), ';\n\n')
422 """Common code between instruction formats and instruction patterns"""
423 def __init__(self, name, lineno, base, fixb, fixm, udfm, fldm, flds):
425 self.file = input_file
428 self.fixedbits = fixb
429 self.fixedmask = fixm
430 self.undefmask = udfm
431 self.fieldmask = fldm
437 r = r + ' ' + self.base.name
439 r = r + ' ' + str(self.fields)
440 r = r + ' ' + str_match_bits(self.fixedbits, self.fixedmask)
444 return str_indent(i) + self.__str__()
448 class Format(General):
449 """Class representing an instruction format"""
451 def extract_name(self):
452 return 'extract_' + self.name
454 def output_extract(self):
455 output('static void ', self.extract_name(), '(',
456 self.base.struct_name(), ' *a, ', insntype, ' insn)\n{\n')
457 for n, f in self.fields.items():
458 output(' a->', n, ' = ', f.str_extract(), ';\n')
463 class Pattern(General):
464 """Class representing an instruction pattern"""
466 def output_decl(self):
467 global translate_scope
468 global translate_prefix
469 output('typedef ', self.base.base.struct_name(),
470 ' arg_', self.name, ';\n')
471 output(translate_scope, 'bool ', translate_prefix, '_', self.name,
472 '(DisasContext *ctx, arg_', self.name, ' *a);\n')
474 def output_code(self, i, extracted, outerbits, outermask):
475 global translate_prefix
477 arg = self.base.base.name
478 output(ind, '/* ', self.file, ':', str(self.lineno), ' */\n')
480 output(ind, self.base.extract_name(), '(&u.f_', arg, ', insn);\n')
481 for n, f in self.fields.items():
482 output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n')
483 output(ind, 'return ', translate_prefix, '_', self.name,
484 '(ctx, &u.f_', arg, ');\n')
488 def parse_field(lineno, name, toks):
489 """Parse one instruction field from TOKS at LINENO"""
494 # A "simple" field will have only one entry;
495 # a "multifield" will have several.
500 if re_fullmatch('!function=' + re_ident, t):
502 error(lineno, 'duplicate function')
507 if re_fullmatch('[0-9]+:s[0-9]+', t):
508 # Signed field extract
509 subtoks = t.split(':s')
511 elif re_fullmatch('[0-9]+:[0-9]+', t):
512 # Unsigned field extract
513 subtoks = t.split(':')
516 error(lineno, 'invalid field token "{0}"'.format(t))
519 if po + le > insnwidth:
520 error(lineno, 'field {0} too large'.format(t))
521 f = Field(sign, po, le)
525 if width > insnwidth:
526 error(lineno, 'field too large')
533 error(lineno, 'field components overlap')
535 f = MultiField(subs, mask)
537 f = FunctionField(func, f)
540 error(lineno, 'duplicate field', name)
545 def parse_arguments(lineno, name, toks):
546 """Parse one argument set from TOKS at LINENO"""
553 if re_fullmatch('!extern', t):
556 if not re_fullmatch(re_ident, t):
557 error(lineno, 'invalid argument set token "{0}"'.format(t))
559 error(lineno, 'duplicate argument "{0}"'.format(t))
562 if name in arguments:
563 error(lineno, 'duplicate argument set', name)
564 arguments[name] = Arguments(name, flds, extern)
565 # end parse_arguments
568 def lookup_field(lineno, name):
572 error(lineno, 'undefined field', name)
575 def add_field(lineno, flds, new_name, f):
577 error(lineno, 'duplicate field', new_name)
582 def add_field_byname(lineno, flds, new_name, old_name):
583 return add_field(lineno, flds, new_name, lookup_field(lineno, old_name))
586 def infer_argument_set(flds):
588 global decode_function
590 for arg in arguments.values():
591 if eq_fields_for_args(flds, arg.fields):
594 name = decode_function + str(len(arguments))
595 arg = Arguments(name, flds.keys(), False)
596 arguments[name] = arg
600 def infer_format(arg, fieldmask, flds):
603 global decode_function
607 for n, c in flds.items():
613 # Look for an existing format with the same argument set and fields
614 for fmt in formats.values():
615 if arg and fmt.base != arg:
617 if fieldmask != fmt.fieldmask:
619 if not eq_fields_for_fmts(flds, fmt.fields):
621 return (fmt, const_flds)
623 name = decode_function + '_Fmt_' + str(len(formats))
625 arg = infer_argument_set(flds)
627 fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds)
630 return (fmt, const_flds)
634 def parse_generic(lineno, is_format, name, toks):
635 """Parse one instruction format from TOKS at LINENO"""
652 # '&Foo' gives a format an explcit argument set.
656 error(lineno, 'multiple argument sets')
660 error(lineno, 'undefined argument set', t)
663 # '@Foo' gives a pattern an explicit format.
667 error(lineno, 'multiple formats')
671 error(lineno, 'undefined format', t)
674 # '%Foo' imports a field.
677 flds = add_field_byname(lineno, flds, tt, tt)
680 # 'Foo=%Bar' imports a field with a different name.
681 if re_fullmatch(re_ident + '=%' + re_ident, t):
682 (fname, iname) = t.split('=%')
683 flds = add_field_byname(lineno, flds, fname, iname)
686 # 'Foo=number' sets an argument field to a constant value
687 if re_fullmatch(re_ident + '=[0-9]+', t):
688 (fname, value) = t.split('=')
690 flds = add_field(lineno, flds, fname, ConstField(value))
693 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
694 # required ones, or dont-cares.
695 if re_fullmatch('[01.-]+', t):
697 fms = t.replace('0', '1')
698 fms = fms.replace('.', '0')
699 fms = fms.replace('-', '0')
700 fbs = t.replace('.', '0')
701 fbs = fbs.replace('-', '0')
702 ubm = t.replace('1', '0')
703 ubm = ubm.replace('.', '0')
704 ubm = ubm.replace('-', '1')
708 fixedbits = (fixedbits << shift) | fbs
709 fixedmask = (fixedmask << shift) | fms
710 undefmask = (undefmask << shift) | ubm
711 # Otherwise, fieldname:fieldwidth
712 elif re_fullmatch(re_ident + ':s?[0-9]+', t):
713 (fname, flen) = t.split(':')
718 shift = int(flen, 10)
719 f = Field(sign, insnwidth - width - shift, shift)
720 flds = add_field(lineno, flds, fname, f)
725 error(lineno, 'invalid token "{0}"'.format(t))
728 # We should have filled in all of the bits of the instruction.
729 if not (is_format and width == 0) and width != insnwidth:
730 error(lineno, 'definition has {0} bits'.format(width))
732 # Do not check for fields overlaping fields; one valid usage
733 # is to be able to duplicate fields via import.
735 for f in flds.values():
738 # Fix up what we've parsed to match either a format or a pattern.
740 # Formats cannot reference formats.
742 error(lineno, 'format referencing format')
743 # If an argument set is given, then there should be no fields
744 # without a place to store it.
746 for f in flds.keys():
747 if f not in arg.fields:
748 error(lineno, 'field {0} not in argument set {1}'
749 .format(f, arg.name))
751 arg = infer_argument_set(flds)
753 error(lineno, 'duplicate format name', name)
754 fmt = Format(name, lineno, arg, fixedbits, fixedmask,
755 undefmask, fieldmask, flds)
758 # Patterns can reference a format ...
760 # ... but not an argument simultaneously
762 error(lineno, 'pattern specifies both format and argument set')
763 if fixedmask & fmt.fixedmask:
764 error(lineno, 'pattern fixed bits overlap format fixed bits')
765 fieldmask |= fmt.fieldmask
766 fixedbits |= fmt.fixedbits
767 fixedmask |= fmt.fixedmask
768 undefmask |= fmt.undefmask
770 (fmt, flds) = infer_format(arg, fieldmask, flds)
772 for f in flds.keys():
773 if f not in arg.fields:
774 error(lineno, 'field {0} not in argument set {1}'
775 .format(f, arg.name))
776 if f in fmt.fields.keys():
777 error(lineno, 'field {0} set by format and pattern'.format(f))
779 if f not in flds.keys() and f not in fmt.fields.keys():
780 error(lineno, 'field {0} not initialized'.format(f))
781 pat = Pattern(name, lineno, fmt, fixedbits, fixedmask,
782 undefmask, fieldmask, flds)
785 # Validate the masks that we have assembled.
786 if fieldmask & fixedmask:
787 error(lineno, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
788 .format(fieldmask, fixedmask))
789 if fieldmask & undefmask:
790 error(lineno, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
791 .format(fieldmask, undefmask))
792 if fixedmask & undefmask:
793 error(lineno, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
794 .format(fixedmask, undefmask))
796 allbits = fieldmask | fixedmask | undefmask
797 if allbits != insnmask:
798 error(lineno, 'bits left unspecified (0x{0:08x})'
799 .format(allbits ^ insnmask))
804 """Parse all of the patterns within a file"""
806 # Read all of the lines of the file. Concatenate lines
807 # ending in backslash; discard empty lines and comments.
820 # Next line after continuation
834 error(lineno, 'short line')
839 # Determine the type of object needing to be parsed.
841 parse_field(lineno, name[1:], toks)
843 parse_arguments(lineno, name[1:], toks)
845 parse_generic(lineno, True, name[1:], toks)
847 parse_generic(lineno, False, name, toks)
853 """Class representing a node in a decode tree"""
855 def __init__(self, fm, tm):
863 r = '{0}{1:08x}'.format(ind, self.fixedmask)
865 r += ' ' + self.format.name
867 for (b, s) in self.subs:
868 r += '{0} {1:08x}:\n'.format(ind, b)
869 r += s.str1(i + 4) + '\n'
876 def output_code(self, i, extracted, outerbits, outermask):
879 # If we identified all nodes below have the same format,
880 # extract the fields now.
881 if not extracted and self.base:
882 output(ind, self.base.extract_name(),
883 '(&u.f_', self.base.base.name, ', insn);\n')
886 # Attempt to aid the compiler in producing compact switch statements.
887 # If the bits in the mask are contiguous, extract them.
888 sh = is_contiguous(self.thismask)
890 # Propagate SH down into the local functions.
891 def str_switch(b, sh=sh):
892 return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh)
894 def str_case(b, sh=sh):
895 return '0x{0:x}'.format(b >> sh)
898 return 'insn & 0x{0:08x}'.format(b)
901 return '0x{0:08x}'.format(b)
903 output(ind, 'switch (', str_switch(self.thismask), ') {\n')
904 for b, s in sorted(self.subs):
905 assert (self.thismask & ~s.fixedmask) == 0
906 innermask = outermask | self.thismask
907 innerbits = outerbits | b
908 output(ind, 'case ', str_case(b), ':\n')
910 str_match_bits(innerbits, innermask), ' */\n')
911 s.output_code(i + 4, extracted, innerbits, innermask)
913 output(ind, 'return false;\n')
917 def build_tree(pats, outerbits, outermask):
918 # Find the intersection of all remaining fixedmask.
919 innermask = ~outermask
921 innermask &= i.fixedmask
926 pnames.append(p.name + ':' + p.file + ':' + str(p.lineno))
927 error_with_file(pats[0].file, pats[0].lineno,
928 'overlapping patterns:', pnames)
930 fullmask = outermask | innermask
932 # Sort each element of pats into the bin selected by the mask.
935 fb = i.fixedbits & innermask
941 # We must recurse if any bin has more than one element or if
942 # the single element in the bin has not been fully matched.
943 t = Tree(fullmask, innermask)
945 for b, l in bins.items():
947 if len(l) > 1 or s.fixedmask & ~fullmask != 0:
948 s = build_tree(l, b | outerbits, fullmask)
949 t.subs.append((b, s))
955 def prop_format(tree):
956 """Propagate Format objects into the decode tree"""
958 # Depth first search.
959 for (b, s) in tree.subs:
960 if isinstance(s, Tree):
963 # If all entries in SUBS have the same format, then
964 # propagate that into the tree.
966 for (b, s) in tree.subs:
981 global translate_scope
982 global translate_prefix
989 global decode_function
991 decode_scope = 'static '
993 long_opts = ['decode=', 'translate=', 'output=', 'insnwidth=']
995 (opts, args) = getopt.getopt(sys.argv[1:], 'o:w:', long_opts)
996 except getopt.GetoptError as err:
999 if o in ('-o', '--output'):
1001 elif o == '--decode':
1004 elif o == '--translate':
1005 translate_prefix = a
1006 translate_scope = ''
1007 elif o in ('-w', '--insnwidth'):
1010 insntype = 'uint16_t'
1012 elif insnwidth != 32:
1013 error(0, 'cannot handle insns of width', insnwidth)
1015 assert False, 'unhandled option'
1018 error(0, 'missing input file')
1019 for filename in args:
1020 input_file = filename
1021 f = open(filename, 'r')
1025 t = build_tree(patterns, 0, 0)
1029 output_fd = open(output_file, 'w')
1031 output_fd = sys.stdout
1034 for n in sorted(arguments.keys()):
1038 # A single translate function can be invoked for different patterns.
1039 # Make sure that the argument sets are the same, and declare the
1040 # function only once.
1043 if i.name in out_pats:
1044 p = out_pats[i.name]
1045 if i.base.base != p.base.base:
1046 error(0, i.name, ' has conflicting argument sets')
1049 out_pats[i.name] = i
1052 for n in sorted(formats.keys()):
1056 output(decode_scope, 'bool ', decode_function,
1057 '(DisasContext *ctx, ', insntype, ' insn)\n{\n')
1060 output(i4, 'union {\n')
1061 for n in sorted(arguments.keys()):
1063 output(i4, i4, f.struct_name(), ' f_', f.name, ';\n')
1064 output(i4, '} u;\n\n')
1066 t.output_code(4, False, 0, 0)
1075 if __name__ == '__main__':