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.
20 # See the syntax and semantics in docs/devel/decodetree.rst.
37 translate_prefix
= 'trans'
38 translate_scope
= 'static '
43 decode_function
= 'decode'
45 re_ident
= '[a-zA-Z][a-zA-Z0-9_]*'
48 def error_with_file(file, lineno
, *args
):
49 """Print an error message from file:line and args and exit."""
54 r
= '{0}:{1}: error:'.format(file, lineno
)
56 r
= '{0}: error:'.format(file)
63 if output_file
and output_fd
:
65 os
.remove(output_file
)
68 def error(lineno
, *args
):
69 error_with_file(input_file
, lineno
, args
)
77 if sys
.version_info
>= (3, 4):
78 re_fullmatch
= re
.fullmatch
80 def re_fullmatch(pat
, str):
81 return re
.match('^' + pat
+ '$', str)
85 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
89 """Return a string with C spaces"""
93 def str_fields(fields
):
94 """Return a string uniquely identifing FIELDS"""
96 for n
in sorted(fields
.keys()):
101 def str_match_bits(bits
, mask
):
102 """Return a string pretty-printing BITS/MASK"""
105 i
= 1 << (insnwidth
- 1)
123 """Return true iff X is equal to a power of 2."""
124 return (x
& (x
- 1)) == 0
128 """Return the number of times 2 factors into X."""
130 while ((x
>> r
) & 1) == 0:
135 def is_contiguous(bits
):
137 if is_pow2((bits
>> shift
) + 1):
143 def eq_fields_for_args(flds_a
, flds_b
):
144 if len(flds_a
) != len(flds_b
):
146 for k
, a
in flds_a
.items():
152 def eq_fields_for_fmts(flds_a
, flds_b
):
153 if len(flds_a
) != len(flds_b
):
155 for k
, a
in flds_a
.items():
159 if a
.__class
__ != b
.__class
__ or a
!= b
:
165 """Class representing a simple instruction field"""
166 def __init__(self
, sign
, pos
, len):
170 self
.mask
= ((1 << len) - 1) << pos
177 return str(self
.pos
) + ':' + s
+ str(self
.len)
179 def str_extract(self
):
184 return '{0}(insn, {1}, {2})'.format(extr
, self
.pos
, self
.len)
186 def __eq__(self
, other
):
187 return self
.sign
== other
.sign
and self
.mask
== other
.mask
189 def __ne__(self
, other
):
190 return not self
.__eq
__(other
)
195 """Class representing a compound instruction field"""
196 def __init__(self
, subs
, mask
):
198 self
.sign
= subs
[0].sign
202 return str(self
.subs
)
204 def str_extract(self
):
207 for f
in reversed(self
.subs
):
209 ret
= f
.str_extract()
211 ret
= 'deposit32({0}, {1}, {2}, {3})' \
212 .format(ret
, pos
, 32 - pos
, f
.str_extract())
216 def __ne__(self
, other
):
217 if len(self
.subs
) != len(other
.subs
):
219 for a
, b
in zip(self
.subs
, other
.subs
):
220 if a
.__class
__ != b
.__class
__ or a
!= b
:
224 def __eq__(self
, other
):
225 return not self
.__ne
__(other
)
230 """Class representing an argument field with constant value"""
231 def __init__(self
, value
):
234 self
.sign
= value
< 0
237 return str(self
.value
)
239 def str_extract(self
):
240 return str(self
.value
)
242 def __cmp__(self
, other
):
243 return self
.value
- other
.value
248 """Class representing a field passed through a function"""
249 def __init__(self
, func
, base
):
250 self
.mask
= base
.mask
251 self
.sign
= base
.sign
256 return self
.func
+ '(' + str(self
.base
) + ')'
258 def str_extract(self
):
259 return self
.func
+ '(ctx, ' + self
.base
.str_extract() + ')'
261 def __eq__(self
, other
):
262 return self
.func
== other
.func
and self
.base
== other
.base
264 def __ne__(self
, other
):
265 return not self
.__eq
__(other
)
269 class ParameterField
:
270 """Class representing a pseudo-field read from a function"""
271 def __init__(self
, func
):
279 def str_extract(self
):
280 return self
.func
+ '(ctx)'
282 def __eq__(self
, other
):
283 return self
.func
== other
.func
285 def __ne__(self
, other
):
286 return not self
.__eq
__(other
)
291 """Class representing the extracted fields of a format"""
292 def __init__(self
, nm
, flds
, extern
):
295 self
.fields
= sorted(flds
)
298 return self
.name
+ ' ' + str(self
.fields
)
300 def struct_name(self
):
301 return 'arg_' + self
.name
303 def output_def(self
):
305 output('typedef struct {\n')
306 for n
in self
.fields
:
307 output(' int ', n
, ';\n')
308 output('} ', self
.struct_name(), ';\n\n')
313 """Common code between instruction formats and instruction patterns"""
314 def __init__(self
, name
, lineno
, base
, fixb
, fixm
, udfm
, fldm
, flds
, w
):
316 self
.file = input_file
319 self
.fixedbits
= fixb
320 self
.fixedmask
= fixm
321 self
.undefmask
= udfm
322 self
.fieldmask
= fldm
327 return self
.name
+ ' ' + str_match_bits(self
.fixedbits
, self
.fixedmask
)
330 return str_indent(i
) + self
.__str
__()
334 class Format(General
):
335 """Class representing an instruction format"""
337 def extract_name(self
):
338 global decode_function
339 return decode_function
+ '_extract_' + self
.name
341 def output_extract(self
):
342 output('static void ', self
.extract_name(), '(DisasContext *ctx, ',
343 self
.base
.struct_name(), ' *a, ', insntype
, ' insn)\n{\n')
344 for n
, f
in self
.fields
.items():
345 output(' a->', n
, ' = ', f
.str_extract(), ';\n')
350 class Pattern(General
):
351 """Class representing an instruction pattern"""
353 def output_decl(self
):
354 global translate_scope
355 global translate_prefix
356 output('typedef ', self
.base
.base
.struct_name(),
357 ' arg_', self
.name
, ';\n')
358 output(translate_scope
, 'bool ', translate_prefix
, '_', self
.name
,
359 '(DisasContext *ctx, arg_', self
.name
, ' *a);\n')
361 def output_code(self
, i
, extracted
, outerbits
, outermask
):
362 global translate_prefix
364 arg
= self
.base
.base
.name
365 output(ind
, '/* ', self
.file, ':', str(self
.lineno
), ' */\n')
367 output(ind
, self
.base
.extract_name(),
368 '(ctx, &u.f_', arg
, ', insn);\n')
369 for n
, f
in self
.fields
.items():
370 output(ind
, 'u.f_', arg
, '.', n
, ' = ', f
.str_extract(), ';\n')
371 output(ind
, 'if (', translate_prefix
, '_', self
.name
,
372 '(ctx, &u.f_', arg
, ')) return true;\n')
376 class MultiPattern(General
):
377 """Class representing an overlapping set of instruction patterns"""
379 def __init__(self
, lineno
, pats
, fixb
, fixm
, udfm
, w
):
380 self
.file = input_file
384 self
.fixedbits
= fixb
385 self
.fixedmask
= fixm
386 self
.undefmask
= udfm
395 def output_decl(self
):
399 def output_code(self
, i
, extracted
, outerbits
, outermask
):
400 global translate_prefix
403 if outermask
!= p
.fixedmask
:
404 innermask
= p
.fixedmask
& ~outermask
405 innerbits
= p
.fixedbits
& ~outermask
406 output(ind
, 'if ((insn & ',
407 '0x{0:08x}) == 0x{1:08x}'.format(innermask
, innerbits
),
410 str_match_bits(p
.fixedbits
, p
.fixedmask
), ' */\n')
411 p
.output_code(i
+ 4, extracted
, p
.fixedbits
, p
.fixedmask
)
414 p
.output_code(i
, extracted
, p
.fixedbits
, p
.fixedmask
)
418 def parse_field(lineno
, name
, toks
):
419 """Parse one instruction field from TOKS at LINENO"""
424 # A "simple" field will have only one entry;
425 # a "multifield" will have several.
430 if re_fullmatch('!function=' + re_ident
, t
):
432 error(lineno
, 'duplicate function')
437 if re_fullmatch('[0-9]+:s[0-9]+', t
):
438 # Signed field extract
439 subtoks
= t
.split(':s')
441 elif re_fullmatch('[0-9]+:[0-9]+', t
):
442 # Unsigned field extract
443 subtoks
= t
.split(':')
446 error(lineno
, 'invalid field token "{0}"'.format(t
))
449 if po
+ le
> insnwidth
:
450 error(lineno
, 'field {0} too large'.format(t
))
451 f
= Field(sign
, po
, le
)
455 if width
> insnwidth
:
456 error(lineno
, 'field too large')
459 f
= ParameterField(func
)
461 error(lineno
, 'field with no value')
469 error(lineno
, 'field components overlap')
471 f
= MultiField(subs
, mask
)
473 f
= FunctionField(func
, f
)
476 error(lineno
, 'duplicate field', name
)
481 def parse_arguments(lineno
, name
, toks
):
482 """Parse one argument set from TOKS at LINENO"""
489 if re_fullmatch('!extern', t
):
492 if not re_fullmatch(re_ident
, t
):
493 error(lineno
, 'invalid argument set token "{0}"'.format(t
))
495 error(lineno
, 'duplicate argument "{0}"'.format(t
))
498 if name
in arguments
:
499 error(lineno
, 'duplicate argument set', name
)
500 arguments
[name
] = Arguments(name
, flds
, extern
)
501 # end parse_arguments
504 def lookup_field(lineno
, name
):
508 error(lineno
, 'undefined field', name
)
511 def add_field(lineno
, flds
, new_name
, f
):
513 error(lineno
, 'duplicate field', new_name
)
518 def add_field_byname(lineno
, flds
, new_name
, old_name
):
519 return add_field(lineno
, flds
, new_name
, lookup_field(lineno
, old_name
))
522 def infer_argument_set(flds
):
524 global decode_function
526 for arg
in arguments
.values():
527 if eq_fields_for_args(flds
, arg
.fields
):
530 name
= decode_function
+ str(len(arguments
))
531 arg
= Arguments(name
, flds
.keys(), False)
532 arguments
[name
] = arg
536 def infer_format(arg
, fieldmask
, flds
, width
):
539 global decode_function
543 for n
, c
in flds
.items():
549 # Look for an existing format with the same argument set and fields
550 for fmt
in formats
.values():
551 if arg
and fmt
.base
!= arg
:
553 if fieldmask
!= fmt
.fieldmask
:
555 if width
!= fmt
.width
:
557 if not eq_fields_for_fmts(flds
, fmt
.fields
):
559 return (fmt
, const_flds
)
561 name
= decode_function
+ '_Fmt_' + str(len(formats
))
563 arg
= infer_argument_set(flds
)
565 fmt
= Format(name
, 0, arg
, 0, 0, 0, fieldmask
, var_flds
, width
)
568 return (fmt
, const_flds
)
572 def parse_generic(lineno
, is_format
, name
, toks
):
573 """Parse one instruction format from TOKS at LINENO"""
592 # '&Foo' gives a format an explcit argument set.
596 error(lineno
, 'multiple argument sets')
600 error(lineno
, 'undefined argument set', t
)
603 # '@Foo' gives a pattern an explicit format.
607 error(lineno
, 'multiple formats')
611 error(lineno
, 'undefined format', t
)
614 # '%Foo' imports a field.
617 flds
= add_field_byname(lineno
, flds
, tt
, tt
)
620 # 'Foo=%Bar' imports a field with a different name.
621 if re_fullmatch(re_ident
+ '=%' + re_ident
, t
):
622 (fname
, iname
) = t
.split('=%')
623 flds
= add_field_byname(lineno
, flds
, fname
, iname
)
626 # 'Foo=number' sets an argument field to a constant value
627 if re_fullmatch(re_ident
+ '=[+-]?[0-9]+', t
):
628 (fname
, value
) = t
.split('=')
630 flds
= add_field(lineno
, flds
, fname
, ConstField(value
))
633 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
634 # required ones, or dont-cares.
635 if re_fullmatch('[01.-]+', t
):
637 fms
= t
.replace('0', '1')
638 fms
= fms
.replace('.', '0')
639 fms
= fms
.replace('-', '0')
640 fbs
= t
.replace('.', '0')
641 fbs
= fbs
.replace('-', '0')
642 ubm
= t
.replace('1', '0')
643 ubm
= ubm
.replace('.', '0')
644 ubm
= ubm
.replace('-', '1')
648 fixedbits
= (fixedbits
<< shift
) | fbs
649 fixedmask
= (fixedmask
<< shift
) | fms
650 undefmask
= (undefmask
<< shift
) | ubm
651 # Otherwise, fieldname:fieldwidth
652 elif re_fullmatch(re_ident
+ ':s?[0-9]+', t
):
653 (fname
, flen
) = t
.split(':')
658 shift
= int(flen
, 10)
659 if shift
+ width
> insnwidth
:
660 error(lineno
, 'field {0} exceeds insnwidth'.format(fname
))
661 f
= Field(sign
, insnwidth
- width
- shift
, shift
)
662 flds
= add_field(lineno
, flds
, fname
, f
)
667 error(lineno
, 'invalid token "{0}"'.format(t
))
670 if variablewidth
and width
< insnwidth
and width
% 8 == 0:
671 shift
= insnwidth
- width
675 undefmask |
= (1 << shift
) - 1
677 # We should have filled in all of the bits of the instruction.
678 elif not (is_format
and width
== 0) and width
!= insnwidth
:
679 error(lineno
, 'definition has {0} bits'.format(width
))
681 # Do not check for fields overlaping fields; one valid usage
682 # is to be able to duplicate fields via import.
684 for f
in flds
.values():
687 # Fix up what we've parsed to match either a format or a pattern.
689 # Formats cannot reference formats.
691 error(lineno
, 'format referencing format')
692 # If an argument set is given, then there should be no fields
693 # without a place to store it.
695 for f
in flds
.keys():
696 if f
not in arg
.fields
:
697 error(lineno
, 'field {0} not in argument set {1}'
698 .format(f
, arg
.name
))
700 arg
= infer_argument_set(flds
)
702 error(lineno
, 'duplicate format name', name
)
703 fmt
= Format(name
, lineno
, arg
, fixedbits
, fixedmask
,
704 undefmask
, fieldmask
, flds
, width
)
707 # Patterns can reference a format ...
709 # ... but not an argument simultaneously
711 error(lineno
, 'pattern specifies both format and argument set')
712 if fixedmask
& fmt
.fixedmask
:
713 error(lineno
, 'pattern fixed bits overlap format fixed bits')
714 if width
!= fmt
.width
:
715 error(lineno
, 'pattern uses format of different width')
716 fieldmask |
= fmt
.fieldmask
717 fixedbits |
= fmt
.fixedbits
718 fixedmask |
= fmt
.fixedmask
719 undefmask |
= fmt
.undefmask
721 (fmt
, flds
) = infer_format(arg
, fieldmask
, flds
, width
)
723 for f
in flds
.keys():
724 if f
not in arg
.fields
:
725 error(lineno
, 'field {0} not in argument set {1}'
726 .format(f
, arg
.name
))
727 if f
in fmt
.fields
.keys():
728 error(lineno
, 'field {0} set by format and pattern'.format(f
))
730 if f
not in flds
.keys() and f
not in fmt
.fields
.keys():
731 error(lineno
, 'field {0} not initialized'.format(f
))
732 pat
= Pattern(name
, lineno
, fmt
, fixedbits
, fixedmask
,
733 undefmask
, fieldmask
, flds
, width
)
735 allpatterns
.append(pat
)
737 # Validate the masks that we have assembled.
738 if fieldmask
& fixedmask
:
739 error(lineno
, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
740 .format(fieldmask
, fixedmask
))
741 if fieldmask
& undefmask
:
742 error(lineno
, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
743 .format(fieldmask
, undefmask
))
744 if fixedmask
& undefmask
:
745 error(lineno
, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
746 .format(fixedmask
, undefmask
))
748 allbits
= fieldmask | fixedmask | undefmask
749 if allbits
!= insnmask
:
750 error(lineno
, 'bits left unspecified (0x{0:08x})'
751 .format(allbits ^ insnmask
))
754 def build_multi_pattern(lineno
, pats
):
755 """Validate the Patterns going into a MultiPattern."""
760 error(lineno
, 'less than two patterns within braces')
765 # Collect fixed/undefmask for all of the children.
766 # Move the defining lineno back to that of the first child.
768 fixedmask
&= p
.fixedmask
769 undefmask
&= p
.undefmask
770 if p
.lineno
< lineno
:
777 elif width
!= p
.width
:
778 error(lineno
, 'width mismatch in patterns within braces')
783 error(lineno
, 'no overlap in patterns within braces')
786 thisbits
= p
.fixedbits
& fixedmask
787 if fixedbits
is None:
789 elif fixedbits
!= thisbits
:
790 fixedmask
&= ~
(fixedbits ^ thisbits
)
795 mp
= MultiPattern(lineno
, pats
, fixedbits
, fixedmask
, undefmask
, width
)
797 # end build_multi_pattern
800 """Parse all of the patterns within a file"""
804 # Read all of the lines of the file. Concatenate lines
805 # ending in backslash; discard empty lines and comments.
814 # Expand and strip spaces, to find indent.
816 line
= line
.expandtabs()
828 # Next line after continuation
831 # Allow completely blank lines.
835 # Empty line due to comment.
837 # Indentation must be correct, even for comment lines.
838 if indent
!= nesting
:
839 error(lineno
, 'indentation ', indent
, ' != ', nesting
)
841 start_lineno
= lineno
855 error(start_lineno
, 'mismatched close brace')
857 error(start_lineno
, 'extra tokens after close brace')
859 if indent
!= nesting
:
860 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
862 patterns
= saved_pats
.pop()
863 build_multi_pattern(lineno
, pats
)
867 # Everything else should have current indentation.
868 if indent
!= nesting
:
869 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
874 error(start_lineno
, 'extra tokens after open brace')
875 saved_pats
.append(patterns
)
881 # Determine the type of object needing to be parsed.
883 parse_field(start_lineno
, name
[1:], toks
)
885 parse_arguments(start_lineno
, name
[1:], toks
)
887 parse_generic(start_lineno
, True, name
[1:], toks
)
889 parse_generic(start_lineno
, False, name
, toks
)
895 """Class representing a node in a decode tree"""
897 def __init__(self
, fm
, tm
):
905 r
= '{0}{1:08x}'.format(ind
, self
.fixedmask
)
907 r
+= ' ' + self
.format
.name
909 for (b
, s
) in self
.subs
:
910 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
911 r
+= s
.str1(i
+ 4) + '\n'
918 def output_code(self
, i
, extracted
, outerbits
, outermask
):
921 # If we identified all nodes below have the same format,
922 # extract the fields now.
923 if not extracted
and self
.base
:
924 output(ind
, self
.base
.extract_name(),
925 '(ctx, &u.f_', self
.base
.base
.name
, ', insn);\n')
928 # Attempt to aid the compiler in producing compact switch statements.
929 # If the bits in the mask are contiguous, extract them.
930 sh
= is_contiguous(self
.thismask
)
932 # Propagate SH down into the local functions.
933 def str_switch(b
, sh
=sh
):
934 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
936 def str_case(b
, sh
=sh
):
937 return '0x{0:x}'.format(b
>> sh
)
940 return 'insn & 0x{0:08x}'.format(b
)
943 return '0x{0:08x}'.format(b
)
945 output(ind
, 'switch (', str_switch(self
.thismask
), ') {\n')
946 for b
, s
in sorted(self
.subs
):
947 assert (self
.thismask
& ~s
.fixedmask
) == 0
948 innermask
= outermask | self
.thismask
949 innerbits
= outerbits | b
950 output(ind
, 'case ', str_case(b
), ':\n')
952 str_match_bits(innerbits
, innermask
), ' */\n')
953 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
954 output(ind
, ' return false;\n')
959 def build_tree(pats
, outerbits
, outermask
):
960 # Find the intersection of all remaining fixedmask.
961 innermask
= ~outermask
& insnmask
963 innermask
&= i
.fixedmask
966 text
= 'overlapping patterns:'
968 text
+= '\n' + p
.file + ':' + str(p
.lineno
) + ': ' + str(p
)
969 error_with_file(pats
[0].file, pats
[0].lineno
, text
)
971 fullmask
= outermask | innermask
973 # Sort each element of pats into the bin selected by the mask.
976 fb
= i
.fixedbits
& innermask
982 # We must recurse if any bin has more than one element or if
983 # the single element in the bin has not been fully matched.
984 t
= Tree(fullmask
, innermask
)
986 for b
, l
in bins
.items():
988 if len(l
) > 1 or s
.fixedmask
& ~fullmask
!= 0:
989 s
= build_tree(l
, b | outerbits
, fullmask
)
990 t
.subs
.append((b
, s
))
997 """Class representing a node in a size decode tree"""
999 def __init__(self
, m
, w
):
1007 r
= '{0}{1:08x}'.format(ind
, self
.mask
)
1009 for (b
, s
) in self
.subs
:
1010 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
1011 r
+= s
.str1(i
+ 4) + '\n'
1018 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1021 # If we need to load more bytes to test, do so now.
1022 if extracted
< self
.width
:
1023 output(ind
, 'insn = ', decode_function
,
1024 '_load_bytes(ctx, insn, {0}, {1});\n'
1025 .format(extracted
/ 8, self
.width
/ 8));
1026 extracted
= self
.width
1028 # Attempt to aid the compiler in producing compact switch statements.
1029 # If the bits in the mask are contiguous, extract them.
1030 sh
= is_contiguous(self
.mask
)
1032 # Propagate SH down into the local functions.
1033 def str_switch(b
, sh
=sh
):
1034 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
1036 def str_case(b
, sh
=sh
):
1037 return '0x{0:x}'.format(b
>> sh
)
1040 return 'insn & 0x{0:08x}'.format(b
)
1043 return '0x{0:08x}'.format(b
)
1045 output(ind
, 'switch (', str_switch(self
.mask
), ') {\n')
1046 for b
, s
in sorted(self
.subs
):
1047 innermask
= outermask | self
.mask
1048 innerbits
= outerbits | b
1049 output(ind
, 'case ', str_case(b
), ':\n')
1051 str_match_bits(innerbits
, innermask
), ' */\n')
1052 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
1054 output(ind
, 'return insn;\n')
1058 """Class representing a leaf node in a size decode tree"""
1060 def __init__(self
, m
, w
):
1066 return '{0}{1:08x}'.format(ind
, self
.mask
)
1071 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1072 global decode_function
1075 # If we need to load more bytes, do so now.
1076 if extracted
< self
.width
:
1077 output(ind
, 'insn = ', decode_function
,
1078 '_load_bytes(ctx, insn, {0}, {1});\n'
1079 .format(extracted
/ 8, self
.width
/ 8));
1080 extracted
= self
.width
1081 output(ind
, 'return insn;\n')
1085 def build_size_tree(pats
, width
, outerbits
, outermask
):
1088 # Collect the mask of bits that are fixed in this width
1089 innermask
= 0xff << (insnwidth
- width
)
1090 innermask
&= ~outermask
1094 innermask
&= i
.fixedmask
1095 if minwidth
is None:
1097 elif minwidth
!= i
.width
:
1099 if minwidth
< i
.width
:
1103 return SizeLeaf(innermask
, minwidth
)
1106 if width
< minwidth
:
1107 return build_size_tree(pats
, width
+ 8, outerbits
, outermask
)
1111 pnames
.append(p
.name
+ ':' + p
.file + ':' + str(p
.lineno
))
1112 error_with_file(pats
[0].file, pats
[0].lineno
,
1113 'overlapping patterns size {0}:'.format(width
), pnames
)
1117 fb
= i
.fixedbits
& innermask
1123 fullmask
= outermask | innermask
1124 lens
= sorted(bins
.keys())
1127 return build_size_tree(bins
[b
], width
+ 8, b | outerbits
, fullmask
)
1129 r
= SizeTree(innermask
, width
)
1130 for b
, l
in bins
.items():
1131 s
= build_size_tree(l
, width
, b | outerbits
, fullmask
)
1132 r
.subs
.append((b
, s
))
1134 # end build_size_tree
1137 def prop_format(tree
):
1138 """Propagate Format objects into the decode tree"""
1140 # Depth first search.
1141 for (b
, s
) in tree
.subs
:
1142 if isinstance(s
, Tree
):
1145 # If all entries in SUBS have the same format, then
1146 # propagate that into the tree.
1148 for (b
, s
) in tree
.subs
:
1159 def prop_size(tree
):
1160 """Propagate minimum widths up the decode size tree"""
1162 if isinstance(tree
, SizeTree
):
1164 for (b
, s
) in tree
.subs
:
1165 width
= prop_size(s
)
1166 if min is None or min > width
:
1168 assert min >= tree
.width
1181 global translate_scope
1182 global translate_prefix
1189 global decode_function
1190 global variablewidth
1192 decode_scope
= 'static '
1194 long_opts
= ['decode=', 'translate=', 'output=', 'insnwidth=',
1195 'static-decode=', 'varinsnwidth=']
1197 (opts
, args
) = getopt
.getopt(sys
.argv
[1:], 'o:vw:', long_opts
)
1198 except getopt
.GetoptError
as err
:
1201 if o
in ('-o', '--output'):
1203 elif o
== '--decode':
1206 elif o
== '--static-decode':
1208 elif o
== '--translate':
1209 translate_prefix
= a
1210 translate_scope
= ''
1211 elif o
in ('-w', '--insnwidth', '--varinsnwidth'):
1212 if o
== '--varinsnwidth':
1213 variablewidth
= True
1216 insntype
= 'uint16_t'
1218 elif insnwidth
!= 32:
1219 error(0, 'cannot handle insns of width', insnwidth
)
1221 assert False, 'unhandled option'
1224 error(0, 'missing input file')
1225 for filename
in args
:
1226 input_file
= filename
1227 f
= open(filename
, 'r')
1232 stree
= build_size_tree(patterns
, 8, 0, 0)
1235 dtree
= build_tree(patterns
, 0, 0)
1239 output_fd
= open(output_file
, 'w')
1241 output_fd
= sys
.stdout
1244 for n
in sorted(arguments
.keys()):
1248 # A single translate function can be invoked for different patterns.
1249 # Make sure that the argument sets are the same, and declare the
1250 # function only once.
1252 for i
in allpatterns
:
1253 if i
.name
in out_pats
:
1254 p
= out_pats
[i
.name
]
1255 if i
.base
.base
!= p
.base
.base
:
1256 error(0, i
.name
, ' has conflicting argument sets')
1259 out_pats
[i
.name
] = i
1262 for n
in sorted(formats
.keys()):
1266 output(decode_scope
, 'bool ', decode_function
,
1267 '(DisasContext *ctx, ', insntype
, ' insn)\n{\n')
1271 if len(allpatterns
) != 0:
1272 output(i4
, 'union {\n')
1273 for n
in sorted(arguments
.keys()):
1275 output(i4
, i4
, f
.struct_name(), ' f_', f
.name
, ';\n')
1276 output(i4
, '} u;\n\n')
1277 dtree
.output_code(4, False, 0, 0)
1279 output(i4
, 'return false;\n')
1283 output('\n', decode_scope
, insntype
, ' ', decode_function
,
1284 '_load(DisasContext *ctx)\n{\n',
1285 ' ', insntype
, ' insn = 0;\n\n')
1286 stree
.output_code(4, 0, 0, 0)
1294 if __name__
== '__main__':