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.
38 translate_prefix
= 'trans'
39 translate_scope
= 'static '
44 decode_function
= 'decode'
46 re_ident
= '[a-zA-Z][a-zA-Z0-9_]*'
49 def error_with_file(file, lineno
, *args
):
50 """Print an error message from file:line and args and exit."""
55 r
= '{0}:{1}: error:'.format(file, lineno
)
57 r
= '{0}: error:'.format(file)
64 if output_file
and output_fd
:
66 os
.remove(output_file
)
69 def error(lineno
, *args
):
70 error_with_file(input_file
, lineno
, args
)
79 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
83 """Return a string with C spaces"""
87 def str_fields(fields
):
88 """Return a string uniquely identifing FIELDS"""
90 for n
in sorted(fields
.keys()):
95 def str_match_bits(bits
, mask
):
96 """Return a string pretty-printing BITS/MASK"""
99 i
= 1 << (insnwidth
- 1)
117 """Return true iff X is equal to a power of 2."""
118 return (x
& (x
- 1)) == 0
122 """Return the number of times 2 factors into X."""
124 while ((x
>> r
) & 1) == 0:
129 def is_contiguous(bits
):
131 if is_pow2((bits
>> shift
) + 1):
137 def eq_fields_for_args(flds_a
, flds_b
):
138 if len(flds_a
) != len(flds_b
):
140 for k
, a
in flds_a
.items():
146 def eq_fields_for_fmts(flds_a
, flds_b
):
147 if len(flds_a
) != len(flds_b
):
149 for k
, a
in flds_a
.items():
153 if a
.__class
__ != b
.__class
__ or a
!= b
:
159 """Class representing a simple instruction field"""
160 def __init__(self
, sign
, pos
, len):
164 self
.mask
= ((1 << len) - 1) << pos
171 return str(self
.pos
) + ':' + s
+ str(self
.len)
173 def str_extract(self
):
178 return '{0}(insn, {1}, {2})'.format(extr
, self
.pos
, self
.len)
180 def __eq__(self
, other
):
181 return self
.sign
== other
.sign
and self
.mask
== other
.mask
183 def __ne__(self
, other
):
184 return not self
.__eq
__(other
)
189 """Class representing a compound instruction field"""
190 def __init__(self
, subs
, mask
):
192 self
.sign
= subs
[0].sign
196 return str(self
.subs
)
198 def str_extract(self
):
201 for f
in reversed(self
.subs
):
203 ret
= f
.str_extract()
205 ret
= 'deposit32({0}, {1}, {2}, {3})' \
206 .format(ret
, pos
, 32 - pos
, f
.str_extract())
210 def __ne__(self
, other
):
211 if len(self
.subs
) != len(other
.subs
):
213 for a
, b
in zip(self
.subs
, other
.subs
):
214 if a
.__class
__ != b
.__class
__ or a
!= b
:
218 def __eq__(self
, other
):
219 return not self
.__ne
__(other
)
224 """Class representing an argument field with constant value"""
225 def __init__(self
, value
):
228 self
.sign
= value
< 0
231 return str(self
.value
)
233 def str_extract(self
):
234 return str(self
.value
)
236 def __cmp__(self
, other
):
237 return self
.value
- other
.value
242 """Class representing a field passed through a function"""
243 def __init__(self
, func
, base
):
244 self
.mask
= base
.mask
245 self
.sign
= base
.sign
250 return self
.func
+ '(' + str(self
.base
) + ')'
252 def str_extract(self
):
253 return self
.func
+ '(ctx, ' + self
.base
.str_extract() + ')'
255 def __eq__(self
, other
):
256 return self
.func
== other
.func
and self
.base
== other
.base
258 def __ne__(self
, other
):
259 return not self
.__eq
__(other
)
263 class ParameterField
:
264 """Class representing a pseudo-field read from a function"""
265 def __init__(self
, func
):
273 def str_extract(self
):
274 return self
.func
+ '(ctx)'
276 def __eq__(self
, other
):
277 return self
.func
== other
.func
279 def __ne__(self
, other
):
280 return not self
.__eq
__(other
)
285 """Class representing the extracted fields of a format"""
286 def __init__(self
, nm
, flds
, extern
):
289 self
.fields
= sorted(flds
)
292 return self
.name
+ ' ' + str(self
.fields
)
294 def struct_name(self
):
295 return 'arg_' + self
.name
297 def output_def(self
):
299 output('typedef struct {\n')
300 for n
in self
.fields
:
301 output(' int ', n
, ';\n')
302 output('} ', self
.struct_name(), ';\n\n')
307 """Common code between instruction formats and instruction patterns"""
308 def __init__(self
, name
, lineno
, base
, fixb
, fixm
, udfm
, fldm
, flds
, w
):
310 self
.file = input_file
313 self
.fixedbits
= fixb
314 self
.fixedmask
= fixm
315 self
.undefmask
= udfm
316 self
.fieldmask
= fldm
321 return self
.name
+ ' ' + str_match_bits(self
.fixedbits
, self
.fixedmask
)
324 return str_indent(i
) + self
.__str
__()
328 class Format(General
):
329 """Class representing an instruction format"""
331 def extract_name(self
):
332 global decode_function
333 return decode_function
+ '_extract_' + self
.name
335 def output_extract(self
):
336 output('static void ', self
.extract_name(), '(DisasContext *ctx, ',
337 self
.base
.struct_name(), ' *a, ', insntype
, ' insn)\n{\n')
338 for n
, f
in self
.fields
.items():
339 output(' a->', n
, ' = ', f
.str_extract(), ';\n')
344 class Pattern(General
):
345 """Class representing an instruction pattern"""
347 def output_decl(self
):
348 global translate_scope
349 global translate_prefix
350 output('typedef ', self
.base
.base
.struct_name(),
351 ' arg_', self
.name
, ';\n')
352 output(translate_scope
, 'bool ', translate_prefix
, '_', self
.name
,
353 '(DisasContext *ctx, arg_', self
.name
, ' *a);\n')
355 def output_code(self
, i
, extracted
, outerbits
, outermask
):
356 global translate_prefix
358 arg
= self
.base
.base
.name
359 output(ind
, '/* ', self
.file, ':', str(self
.lineno
), ' */\n')
361 output(ind
, self
.base
.extract_name(),
362 '(ctx, &u.f_', arg
, ', insn);\n')
363 for n
, f
in self
.fields
.items():
364 output(ind
, 'u.f_', arg
, '.', n
, ' = ', f
.str_extract(), ';\n')
365 output(ind
, 'if (', translate_prefix
, '_', self
.name
,
366 '(ctx, &u.f_', arg
, ')) return true;\n')
370 class MultiPattern(General
):
371 """Class representing an overlapping set of instruction patterns"""
373 def __init__(self
, lineno
, pats
, fixb
, fixm
, udfm
, w
):
374 self
.file = input_file
378 self
.fixedbits
= fixb
379 self
.fixedmask
= fixm
380 self
.undefmask
= udfm
389 def output_decl(self
):
393 def output_code(self
, i
, extracted
, outerbits
, outermask
):
394 global translate_prefix
397 if outermask
!= p
.fixedmask
:
398 innermask
= p
.fixedmask
& ~outermask
399 innerbits
= p
.fixedbits
& ~outermask
400 output(ind
, 'if ((insn & ',
401 '0x{0:08x}) == 0x{1:08x}'.format(innermask
, innerbits
),
404 str_match_bits(p
.fixedbits
, p
.fixedmask
), ' */\n')
405 p
.output_code(i
+ 4, extracted
, p
.fixedbits
, p
.fixedmask
)
408 p
.output_code(i
, extracted
, p
.fixedbits
, p
.fixedmask
)
412 def parse_field(lineno
, name
, toks
):
413 """Parse one instruction field from TOKS at LINENO"""
418 # A "simple" field will have only one entry;
419 # a "multifield" will have several.
424 if re
.fullmatch('!function=' + re_ident
, t
):
426 error(lineno
, 'duplicate function')
431 if re
.fullmatch('[0-9]+:s[0-9]+', t
):
432 # Signed field extract
433 subtoks
= t
.split(':s')
435 elif re
.fullmatch('[0-9]+:[0-9]+', t
):
436 # Unsigned field extract
437 subtoks
= t
.split(':')
440 error(lineno
, 'invalid field token "{0}"'.format(t
))
443 if po
+ le
> insnwidth
:
444 error(lineno
, 'field {0} too large'.format(t
))
445 f
= Field(sign
, po
, le
)
449 if width
> insnwidth
:
450 error(lineno
, 'field too large')
453 f
= ParameterField(func
)
455 error(lineno
, 'field with no value')
463 error(lineno
, 'field components overlap')
465 f
= MultiField(subs
, mask
)
467 f
= FunctionField(func
, f
)
470 error(lineno
, 'duplicate field', name
)
475 def parse_arguments(lineno
, name
, toks
):
476 """Parse one argument set from TOKS at LINENO"""
484 if re
.fullmatch('!extern', t
):
488 if not re
.fullmatch(re_ident
, t
):
489 error(lineno
, 'invalid argument set token "{0}"'.format(t
))
491 error(lineno
, 'duplicate argument "{0}"'.format(t
))
494 if name
in arguments
:
495 error(lineno
, 'duplicate argument set', name
)
496 arguments
[name
] = Arguments(name
, flds
, extern
)
497 # end parse_arguments
500 def lookup_field(lineno
, name
):
504 error(lineno
, 'undefined field', name
)
507 def add_field(lineno
, flds
, new_name
, f
):
509 error(lineno
, 'duplicate field', new_name
)
514 def add_field_byname(lineno
, flds
, new_name
, old_name
):
515 return add_field(lineno
, flds
, new_name
, lookup_field(lineno
, old_name
))
518 def infer_argument_set(flds
):
520 global decode_function
522 for arg
in arguments
.values():
523 if eq_fields_for_args(flds
, arg
.fields
):
526 name
= decode_function
+ str(len(arguments
))
527 arg
= Arguments(name
, flds
.keys(), False)
528 arguments
[name
] = arg
532 def infer_format(arg
, fieldmask
, flds
, width
):
535 global decode_function
539 for n
, c
in flds
.items():
545 # Look for an existing format with the same argument set and fields
546 for fmt
in formats
.values():
547 if arg
and fmt
.base
!= arg
:
549 if fieldmask
!= fmt
.fieldmask
:
551 if width
!= fmt
.width
:
553 if not eq_fields_for_fmts(flds
, fmt
.fields
):
555 return (fmt
, const_flds
)
557 name
= decode_function
+ '_Fmt_' + str(len(formats
))
559 arg
= infer_argument_set(flds
)
561 fmt
= Format(name
, 0, arg
, 0, 0, 0, fieldmask
, var_flds
, width
)
564 return (fmt
, const_flds
)
568 def parse_generic(lineno
, is_format
, name
, toks
):
569 """Parse one instruction format from TOKS at LINENO"""
588 # '&Foo' gives a format an explcit argument set.
592 error(lineno
, 'multiple argument sets')
596 error(lineno
, 'undefined argument set', t
)
599 # '@Foo' gives a pattern an explicit format.
603 error(lineno
, 'multiple formats')
607 error(lineno
, 'undefined format', t
)
610 # '%Foo' imports a field.
613 flds
= add_field_byname(lineno
, flds
, tt
, tt
)
616 # 'Foo=%Bar' imports a field with a different name.
617 if re
.fullmatch(re_ident
+ '=%' + re_ident
, t
):
618 (fname
, iname
) = t
.split('=%')
619 flds
= add_field_byname(lineno
, flds
, fname
, iname
)
622 # 'Foo=number' sets an argument field to a constant value
623 if re
.fullmatch(re_ident
+ '=[+-]?[0-9]+', t
):
624 (fname
, value
) = t
.split('=')
626 flds
= add_field(lineno
, flds
, fname
, ConstField(value
))
629 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
630 # required ones, or dont-cares.
631 if re
.fullmatch('[01.-]+', t
):
633 fms
= t
.replace('0', '1')
634 fms
= fms
.replace('.', '0')
635 fms
= fms
.replace('-', '0')
636 fbs
= t
.replace('.', '0')
637 fbs
= fbs
.replace('-', '0')
638 ubm
= t
.replace('1', '0')
639 ubm
= ubm
.replace('.', '0')
640 ubm
= ubm
.replace('-', '1')
644 fixedbits
= (fixedbits
<< shift
) | fbs
645 fixedmask
= (fixedmask
<< shift
) | fms
646 undefmask
= (undefmask
<< shift
) | ubm
647 # Otherwise, fieldname:fieldwidth
648 elif re
.fullmatch(re_ident
+ ':s?[0-9]+', t
):
649 (fname
, flen
) = t
.split(':')
654 shift
= int(flen
, 10)
655 if shift
+ width
> insnwidth
:
656 error(lineno
, 'field {0} exceeds insnwidth'.format(fname
))
657 f
= Field(sign
, insnwidth
- width
- shift
, shift
)
658 flds
= add_field(lineno
, flds
, fname
, f
)
663 error(lineno
, 'invalid token "{0}"'.format(t
))
666 if variablewidth
and width
< insnwidth
and width
% 8 == 0:
667 shift
= insnwidth
- width
671 undefmask |
= (1 << shift
) - 1
673 # We should have filled in all of the bits of the instruction.
674 elif not (is_format
and width
== 0) and width
!= insnwidth
:
675 error(lineno
, 'definition has {0} bits'.format(width
))
677 # Do not check for fields overlaping fields; one valid usage
678 # is to be able to duplicate fields via import.
680 for f
in flds
.values():
683 # Fix up what we've parsed to match either a format or a pattern.
685 # Formats cannot reference formats.
687 error(lineno
, 'format referencing format')
688 # If an argument set is given, then there should be no fields
689 # without a place to store it.
691 for f
in flds
.keys():
692 if f
not in arg
.fields
:
693 error(lineno
, 'field {0} not in argument set {1}'
694 .format(f
, arg
.name
))
696 arg
= infer_argument_set(flds
)
698 error(lineno
, 'duplicate format name', name
)
699 fmt
= Format(name
, lineno
, arg
, fixedbits
, fixedmask
,
700 undefmask
, fieldmask
, flds
, width
)
703 # Patterns can reference a format ...
705 # ... but not an argument simultaneously
707 error(lineno
, 'pattern specifies both format and argument set')
708 if fixedmask
& fmt
.fixedmask
:
709 error(lineno
, 'pattern fixed bits overlap format fixed bits')
710 if width
!= fmt
.width
:
711 error(lineno
, 'pattern uses format of different width')
712 fieldmask |
= fmt
.fieldmask
713 fixedbits |
= fmt
.fixedbits
714 fixedmask |
= fmt
.fixedmask
715 undefmask |
= fmt
.undefmask
717 (fmt
, flds
) = infer_format(arg
, fieldmask
, flds
, width
)
719 for f
in flds
.keys():
720 if f
not in arg
.fields
:
721 error(lineno
, 'field {0} not in argument set {1}'
722 .format(f
, arg
.name
))
723 if f
in fmt
.fields
.keys():
724 error(lineno
, 'field {0} set by format and pattern'.format(f
))
726 if f
not in flds
.keys() and f
not in fmt
.fields
.keys():
727 error(lineno
, 'field {0} not initialized'.format(f
))
728 pat
= Pattern(name
, lineno
, fmt
, fixedbits
, fixedmask
,
729 undefmask
, fieldmask
, flds
, width
)
731 allpatterns
.append(pat
)
733 # Validate the masks that we have assembled.
734 if fieldmask
& fixedmask
:
735 error(lineno
, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
736 .format(fieldmask
, fixedmask
))
737 if fieldmask
& undefmask
:
738 error(lineno
, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
739 .format(fieldmask
, undefmask
))
740 if fixedmask
& undefmask
:
741 error(lineno
, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
742 .format(fixedmask
, undefmask
))
744 allbits
= fieldmask | fixedmask | undefmask
745 if allbits
!= insnmask
:
746 error(lineno
, 'bits left unspecified (0x{0:08x})'
747 .format(allbits ^ insnmask
))
750 def build_multi_pattern(lineno
, pats
):
751 """Validate the Patterns going into a MultiPattern."""
756 error(lineno
, 'less than two patterns within braces')
761 # Collect fixed/undefmask for all of the children.
762 # Move the defining lineno back to that of the first child.
764 fixedmask
&= p
.fixedmask
765 undefmask
&= p
.undefmask
766 if p
.lineno
< lineno
:
773 elif width
!= p
.width
:
774 error(lineno
, 'width mismatch in patterns within braces')
779 error(lineno
, 'no overlap in patterns within braces')
782 thisbits
= p
.fixedbits
& fixedmask
783 if fixedbits
is None:
785 elif fixedbits
!= thisbits
:
786 fixedmask
&= ~
(fixedbits ^ thisbits
)
791 mp
= MultiPattern(lineno
, pats
, fixedbits
, fixedmask
, undefmask
, width
)
793 # end build_multi_pattern
796 """Parse all of the patterns within a file"""
800 # Read all of the lines of the file. Concatenate lines
801 # ending in backslash; discard empty lines and comments.
810 # Expand and strip spaces, to find indent.
812 line
= line
.expandtabs()
824 # Next line after continuation
827 # Allow completely blank lines.
831 # Empty line due to comment.
833 # Indentation must be correct, even for comment lines.
834 if indent
!= nesting
:
835 error(lineno
, 'indentation ', indent
, ' != ', nesting
)
837 start_lineno
= lineno
851 error(start_lineno
, 'mismatched close brace')
853 error(start_lineno
, 'extra tokens after close brace')
855 if indent
!= nesting
:
856 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
858 patterns
= saved_pats
.pop()
859 build_multi_pattern(lineno
, pats
)
863 # Everything else should have current indentation.
864 if indent
!= nesting
:
865 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
870 error(start_lineno
, 'extra tokens after open brace')
871 saved_pats
.append(patterns
)
877 # Determine the type of object needing to be parsed.
879 parse_field(start_lineno
, name
[1:], toks
)
881 parse_arguments(start_lineno
, name
[1:], toks
)
883 parse_generic(start_lineno
, True, name
[1:], toks
)
885 parse_generic(start_lineno
, False, name
, toks
)
891 """Class representing a node in a decode tree"""
893 def __init__(self
, fm
, tm
):
901 r
= '{0}{1:08x}'.format(ind
, self
.fixedmask
)
903 r
+= ' ' + self
.format
.name
905 for (b
, s
) in self
.subs
:
906 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
907 r
+= s
.str1(i
+ 4) + '\n'
914 def output_code(self
, i
, extracted
, outerbits
, outermask
):
917 # If we identified all nodes below have the same format,
918 # extract the fields now.
919 if not extracted
and self
.base
:
920 output(ind
, self
.base
.extract_name(),
921 '(ctx, &u.f_', self
.base
.base
.name
, ', insn);\n')
924 # Attempt to aid the compiler in producing compact switch statements.
925 # If the bits in the mask are contiguous, extract them.
926 sh
= is_contiguous(self
.thismask
)
928 # Propagate SH down into the local functions.
929 def str_switch(b
, sh
=sh
):
930 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
932 def str_case(b
, sh
=sh
):
933 return '0x{0:x}'.format(b
>> sh
)
936 return 'insn & 0x{0:08x}'.format(b
)
939 return '0x{0:08x}'.format(b
)
941 output(ind
, 'switch (', str_switch(self
.thismask
), ') {\n')
942 for b
, s
in sorted(self
.subs
):
943 assert (self
.thismask
& ~s
.fixedmask
) == 0
944 innermask
= outermask | self
.thismask
945 innerbits
= outerbits | b
946 output(ind
, 'case ', str_case(b
), ':\n')
948 str_match_bits(innerbits
, innermask
), ' */\n')
949 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
950 output(ind
, ' return false;\n')
955 def build_tree(pats
, outerbits
, outermask
):
956 # Find the intersection of all remaining fixedmask.
957 innermask
= ~outermask
& insnmask
959 innermask
&= i
.fixedmask
962 text
= 'overlapping patterns:'
964 text
+= '\n' + p
.file + ':' + str(p
.lineno
) + ': ' + str(p
)
965 error_with_file(pats
[0].file, pats
[0].lineno
, text
)
967 fullmask
= outermask | innermask
969 # Sort each element of pats into the bin selected by the mask.
972 fb
= i
.fixedbits
& innermask
978 # We must recurse if any bin has more than one element or if
979 # the single element in the bin has not been fully matched.
980 t
= Tree(fullmask
, innermask
)
982 for b
, l
in bins
.items():
984 if len(l
) > 1 or s
.fixedmask
& ~fullmask
!= 0:
985 s
= build_tree(l
, b | outerbits
, fullmask
)
986 t
.subs
.append((b
, s
))
993 """Class representing a node in a size decode tree"""
995 def __init__(self
, m
, w
):
1003 r
= '{0}{1:08x}'.format(ind
, self
.mask
)
1005 for (b
, s
) in self
.subs
:
1006 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
1007 r
+= s
.str1(i
+ 4) + '\n'
1014 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1017 # If we need to load more bytes to test, do so now.
1018 if extracted
< self
.width
:
1019 output(ind
, 'insn = ', decode_function
,
1020 '_load_bytes(ctx, insn, {0}, {1});\n'
1021 .format(extracted
// 8, self
.width
// 8));
1022 extracted
= self
.width
1024 # Attempt to aid the compiler in producing compact switch statements.
1025 # If the bits in the mask are contiguous, extract them.
1026 sh
= is_contiguous(self
.mask
)
1028 # Propagate SH down into the local functions.
1029 def str_switch(b
, sh
=sh
):
1030 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
1032 def str_case(b
, sh
=sh
):
1033 return '0x{0:x}'.format(b
>> sh
)
1036 return 'insn & 0x{0:08x}'.format(b
)
1039 return '0x{0:08x}'.format(b
)
1041 output(ind
, 'switch (', str_switch(self
.mask
), ') {\n')
1042 for b
, s
in sorted(self
.subs
):
1043 innermask
= outermask | self
.mask
1044 innerbits
= outerbits | b
1045 output(ind
, 'case ', str_case(b
), ':\n')
1047 str_match_bits(innerbits
, innermask
), ' */\n')
1048 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
1050 output(ind
, 'return insn;\n')
1054 """Class representing a leaf node in a size decode tree"""
1056 def __init__(self
, m
, w
):
1062 return '{0}{1:08x}'.format(ind
, self
.mask
)
1067 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1068 global decode_function
1071 # If we need to load more bytes, do so now.
1072 if extracted
< self
.width
:
1073 output(ind
, 'insn = ', decode_function
,
1074 '_load_bytes(ctx, insn, {0}, {1});\n'
1075 .format(extracted
// 8, self
.width
// 8));
1076 extracted
= self
.width
1077 output(ind
, 'return insn;\n')
1081 def build_size_tree(pats
, width
, outerbits
, outermask
):
1084 # Collect the mask of bits that are fixed in this width
1085 innermask
= 0xff << (insnwidth
- width
)
1086 innermask
&= ~outermask
1090 innermask
&= i
.fixedmask
1091 if minwidth
is None:
1093 elif minwidth
!= i
.width
:
1095 if minwidth
< i
.width
:
1099 return SizeLeaf(innermask
, minwidth
)
1102 if width
< minwidth
:
1103 return build_size_tree(pats
, width
+ 8, outerbits
, outermask
)
1107 pnames
.append(p
.name
+ ':' + p
.file + ':' + str(p
.lineno
))
1108 error_with_file(pats
[0].file, pats
[0].lineno
,
1109 'overlapping patterns size {0}:'.format(width
), pnames
)
1113 fb
= i
.fixedbits
& innermask
1119 fullmask
= outermask | innermask
1120 lens
= sorted(bins
.keys())
1123 return build_size_tree(bins
[b
], width
+ 8, b | outerbits
, fullmask
)
1125 r
= SizeTree(innermask
, width
)
1126 for b
, l
in bins
.items():
1127 s
= build_size_tree(l
, width
, b | outerbits
, fullmask
)
1128 r
.subs
.append((b
, s
))
1130 # end build_size_tree
1133 def prop_format(tree
):
1134 """Propagate Format objects into the decode tree"""
1136 # Depth first search.
1137 for (b
, s
) in tree
.subs
:
1138 if isinstance(s
, Tree
):
1141 # If all entries in SUBS have the same format, then
1142 # propagate that into the tree.
1144 for (b
, s
) in tree
.subs
:
1155 def prop_size(tree
):
1156 """Propagate minimum widths up the decode size tree"""
1158 if isinstance(tree
, SizeTree
):
1160 for (b
, s
) in tree
.subs
:
1161 width
= prop_size(s
)
1162 if min is None or min > width
:
1164 assert min >= tree
.width
1177 global translate_scope
1178 global translate_prefix
1185 global decode_function
1186 global variablewidth
1189 decode_scope
= 'static '
1191 long_opts
= ['decode=', 'translate=', 'output=', 'insnwidth=',
1192 'static-decode=', 'varinsnwidth=']
1194 (opts
, args
) = getopt
.getopt(sys
.argv
[1:], 'o:vw:', long_opts
)
1195 except getopt
.GetoptError
as err
:
1198 if o
in ('-o', '--output'):
1200 elif o
== '--decode':
1203 elif o
== '--static-decode':
1205 elif o
== '--translate':
1206 translate_prefix
= a
1207 translate_scope
= ''
1208 elif o
in ('-w', '--insnwidth', '--varinsnwidth'):
1209 if o
== '--varinsnwidth':
1210 variablewidth
= True
1213 insntype
= 'uint16_t'
1215 elif insnwidth
!= 32:
1216 error(0, 'cannot handle insns of width', insnwidth
)
1218 assert False, 'unhandled option'
1221 error(0, 'missing input file')
1222 for filename
in args
:
1223 input_file
= filename
1224 f
= open(filename
, 'r')
1229 stree
= build_size_tree(patterns
, 8, 0, 0)
1232 dtree
= build_tree(patterns
, 0, 0)
1236 output_fd
= open(output_file
, 'w')
1238 output_fd
= sys
.stdout
1241 for n
in sorted(arguments
.keys()):
1245 # A single translate function can be invoked for different patterns.
1246 # Make sure that the argument sets are the same, and declare the
1247 # function only once.
1249 # If we're sharing formats, we're likely also sharing trans_* functions,
1250 # but we can't tell which ones. Prevent issues from the compiler by
1251 # suppressing redundant declaration warnings.
1253 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1254 "# pragma GCC diagnostic push\n",
1255 "# pragma GCC diagnostic ignored \"-Wredundant-decls\"\n",
1256 "# ifdef __clang__\n"
1257 "# pragma GCC diagnostic ignored \"-Wtypedef-redefinition\"\n",
1262 for i
in allpatterns
:
1263 if i
.name
in out_pats
:
1264 p
= out_pats
[i
.name
]
1265 if i
.base
.base
!= p
.base
.base
:
1266 error(0, i
.name
, ' has conflicting argument sets')
1269 out_pats
[i
.name
] = i
1273 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1274 "# pragma GCC diagnostic pop\n",
1277 for n
in sorted(formats
.keys()):
1281 output(decode_scope
, 'bool ', decode_function
,
1282 '(DisasContext *ctx, ', insntype
, ' insn)\n{\n')
1286 if len(allpatterns
) != 0:
1287 output(i4
, 'union {\n')
1288 for n
in sorted(arguments
.keys()):
1290 output(i4
, i4
, f
.struct_name(), ' f_', f
.name
, ';\n')
1291 output(i4
, '} u;\n\n')
1292 dtree
.output_code(4, False, 0, 0)
1294 output(i4
, 'return false;\n')
1298 output('\n', decode_scope
, insntype
, ' ', decode_function
,
1299 '_load(DisasContext *ctx)\n{\n',
1300 ' ', insntype
, ' insn = 0;\n\n')
1301 stree
.output_code(4, 0, 0, 0)
1309 if __name__
== '__main__':