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
.sign
== other
.sign
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 an expander"""
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
)
270 """Class representing the extracted fields of a format"""
271 def __init__(self
, nm
, flds
, extern
):
274 self
.fields
= sorted(flds
)
277 return self
.name
+ ' ' + str(self
.fields
)
279 def struct_name(self
):
280 return 'arg_' + self
.name
282 def output_def(self
):
284 output('typedef struct {\n')
285 for n
in self
.fields
:
286 output(' int ', n
, ';\n')
287 output('} ', self
.struct_name(), ';\n\n')
292 """Common code between instruction formats and instruction patterns"""
293 def __init__(self
, name
, lineno
, base
, fixb
, fixm
, udfm
, fldm
, flds
, w
):
295 self
.file = input_file
298 self
.fixedbits
= fixb
299 self
.fixedmask
= fixm
300 self
.undefmask
= udfm
301 self
.fieldmask
= fldm
306 return self
.name
+ ' ' + str_match_bits(self
.fixedbits
, self
.fixedmask
)
309 return str_indent(i
) + self
.__str
__()
313 class Format(General
):
314 """Class representing an instruction format"""
316 def extract_name(self
):
317 global decode_function
318 return decode_function
+ '_extract_' + self
.name
320 def output_extract(self
):
321 output('static void ', self
.extract_name(), '(DisasContext *ctx, ',
322 self
.base
.struct_name(), ' *a, ', insntype
, ' insn)\n{\n')
323 for n
, f
in self
.fields
.items():
324 output(' a->', n
, ' = ', f
.str_extract(), ';\n')
329 class Pattern(General
):
330 """Class representing an instruction pattern"""
332 def output_decl(self
):
333 global translate_scope
334 global translate_prefix
335 output('typedef ', self
.base
.base
.struct_name(),
336 ' arg_', self
.name
, ';\n')
337 output(translate_scope
, 'bool ', translate_prefix
, '_', self
.name
,
338 '(DisasContext *ctx, arg_', self
.name
, ' *a);\n')
340 def output_code(self
, i
, extracted
, outerbits
, outermask
):
341 global translate_prefix
343 arg
= self
.base
.base
.name
344 output(ind
, '/* ', self
.file, ':', str(self
.lineno
), ' */\n')
346 output(ind
, self
.base
.extract_name(),
347 '(ctx, &u.f_', arg
, ', insn);\n')
348 for n
, f
in self
.fields
.items():
349 output(ind
, 'u.f_', arg
, '.', n
, ' = ', f
.str_extract(), ';\n')
350 output(ind
, 'if (', translate_prefix
, '_', self
.name
,
351 '(ctx, &u.f_', arg
, ')) return true;\n')
355 class MultiPattern(General
):
356 """Class representing an overlapping set of instruction patterns"""
358 def __init__(self
, lineno
, pats
, fixb
, fixm
, udfm
, w
):
359 self
.file = input_file
363 self
.fixedbits
= fixb
364 self
.fixedmask
= fixm
365 self
.undefmask
= udfm
374 def output_decl(self
):
378 def output_code(self
, i
, extracted
, outerbits
, outermask
):
379 global translate_prefix
382 if outermask
!= p
.fixedmask
:
383 innermask
= p
.fixedmask
& ~outermask
384 innerbits
= p
.fixedbits
& ~outermask
385 output(ind
, 'if ((insn & ',
386 '0x{0:08x}) == 0x{1:08x}'.format(innermask
, innerbits
),
389 str_match_bits(p
.fixedbits
, p
.fixedmask
), ' */\n')
390 p
.output_code(i
+ 4, extracted
, p
.fixedbits
, p
.fixedmask
)
393 p
.output_code(i
, extracted
, p
.fixedbits
, p
.fixedmask
)
397 def parse_field(lineno
, name
, toks
):
398 """Parse one instruction field from TOKS at LINENO"""
403 # A "simple" field will have only one entry;
404 # a "multifield" will have several.
409 if re_fullmatch('!function=' + re_ident
, t
):
411 error(lineno
, 'duplicate function')
416 if re_fullmatch('[0-9]+:s[0-9]+', t
):
417 # Signed field extract
418 subtoks
= t
.split(':s')
420 elif re_fullmatch('[0-9]+:[0-9]+', t
):
421 # Unsigned field extract
422 subtoks
= t
.split(':')
425 error(lineno
, 'invalid field token "{0}"'.format(t
))
428 if po
+ le
> insnwidth
:
429 error(lineno
, 'field {0} too large'.format(t
))
430 f
= Field(sign
, po
, le
)
434 if width
> insnwidth
:
435 error(lineno
, 'field too large')
442 error(lineno
, 'field components overlap')
444 f
= MultiField(subs
, mask
)
446 f
= FunctionField(func
, f
)
449 error(lineno
, 'duplicate field', name
)
454 def parse_arguments(lineno
, name
, toks
):
455 """Parse one argument set from TOKS at LINENO"""
462 if re_fullmatch('!extern', t
):
465 if not re_fullmatch(re_ident
, t
):
466 error(lineno
, 'invalid argument set token "{0}"'.format(t
))
468 error(lineno
, 'duplicate argument "{0}"'.format(t
))
471 if name
in arguments
:
472 error(lineno
, 'duplicate argument set', name
)
473 arguments
[name
] = Arguments(name
, flds
, extern
)
474 # end parse_arguments
477 def lookup_field(lineno
, name
):
481 error(lineno
, 'undefined field', name
)
484 def add_field(lineno
, flds
, new_name
, f
):
486 error(lineno
, 'duplicate field', new_name
)
491 def add_field_byname(lineno
, flds
, new_name
, old_name
):
492 return add_field(lineno
, flds
, new_name
, lookup_field(lineno
, old_name
))
495 def infer_argument_set(flds
):
497 global decode_function
499 for arg
in arguments
.values():
500 if eq_fields_for_args(flds
, arg
.fields
):
503 name
= decode_function
+ str(len(arguments
))
504 arg
= Arguments(name
, flds
.keys(), False)
505 arguments
[name
] = arg
509 def infer_format(arg
, fieldmask
, flds
, width
):
512 global decode_function
516 for n
, c
in flds
.items():
522 # Look for an existing format with the same argument set and fields
523 for fmt
in formats
.values():
524 if arg
and fmt
.base
!= arg
:
526 if fieldmask
!= fmt
.fieldmask
:
528 if width
!= fmt
.width
:
530 if not eq_fields_for_fmts(flds
, fmt
.fields
):
532 return (fmt
, const_flds
)
534 name
= decode_function
+ '_Fmt_' + str(len(formats
))
536 arg
= infer_argument_set(flds
)
538 fmt
= Format(name
, 0, arg
, 0, 0, 0, fieldmask
, var_flds
, width
)
541 return (fmt
, const_flds
)
545 def parse_generic(lineno
, is_format
, name
, toks
):
546 """Parse one instruction format from TOKS at LINENO"""
565 # '&Foo' gives a format an explcit argument set.
569 error(lineno
, 'multiple argument sets')
573 error(lineno
, 'undefined argument set', t
)
576 # '@Foo' gives a pattern an explicit format.
580 error(lineno
, 'multiple formats')
584 error(lineno
, 'undefined format', t
)
587 # '%Foo' imports a field.
590 flds
= add_field_byname(lineno
, flds
, tt
, tt
)
593 # 'Foo=%Bar' imports a field with a different name.
594 if re_fullmatch(re_ident
+ '=%' + re_ident
, t
):
595 (fname
, iname
) = t
.split('=%')
596 flds
= add_field_byname(lineno
, flds
, fname
, iname
)
599 # 'Foo=number' sets an argument field to a constant value
600 if re_fullmatch(re_ident
+ '=[+-]?[0-9]+', t
):
601 (fname
, value
) = t
.split('=')
603 flds
= add_field(lineno
, flds
, fname
, ConstField(value
))
606 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
607 # required ones, or dont-cares.
608 if re_fullmatch('[01.-]+', t
):
610 fms
= t
.replace('0', '1')
611 fms
= fms
.replace('.', '0')
612 fms
= fms
.replace('-', '0')
613 fbs
= t
.replace('.', '0')
614 fbs
= fbs
.replace('-', '0')
615 ubm
= t
.replace('1', '0')
616 ubm
= ubm
.replace('.', '0')
617 ubm
= ubm
.replace('-', '1')
621 fixedbits
= (fixedbits
<< shift
) | fbs
622 fixedmask
= (fixedmask
<< shift
) | fms
623 undefmask
= (undefmask
<< shift
) | ubm
624 # Otherwise, fieldname:fieldwidth
625 elif re_fullmatch(re_ident
+ ':s?[0-9]+', t
):
626 (fname
, flen
) = t
.split(':')
631 shift
= int(flen
, 10)
632 if shift
+ width
> insnwidth
:
633 error(lineno
, 'field {0} exceeds insnwidth'.format(fname
))
634 f
= Field(sign
, insnwidth
- width
- shift
, shift
)
635 flds
= add_field(lineno
, flds
, fname
, f
)
640 error(lineno
, 'invalid token "{0}"'.format(t
))
643 if variablewidth
and width
< insnwidth
and width
% 8 == 0:
644 shift
= insnwidth
- width
648 undefmask |
= (1 << shift
) - 1
650 # We should have filled in all of the bits of the instruction.
651 elif not (is_format
and width
== 0) and width
!= insnwidth
:
652 error(lineno
, 'definition has {0} bits'.format(width
))
654 # Do not check for fields overlaping fields; one valid usage
655 # is to be able to duplicate fields via import.
657 for f
in flds
.values():
660 # Fix up what we've parsed to match either a format or a pattern.
662 # Formats cannot reference formats.
664 error(lineno
, 'format referencing format')
665 # If an argument set is given, then there should be no fields
666 # without a place to store it.
668 for f
in flds
.keys():
669 if f
not in arg
.fields
:
670 error(lineno
, 'field {0} not in argument set {1}'
671 .format(f
, arg
.name
))
673 arg
= infer_argument_set(flds
)
675 error(lineno
, 'duplicate format name', name
)
676 fmt
= Format(name
, lineno
, arg
, fixedbits
, fixedmask
,
677 undefmask
, fieldmask
, flds
, width
)
680 # Patterns can reference a format ...
682 # ... but not an argument simultaneously
684 error(lineno
, 'pattern specifies both format and argument set')
685 if fixedmask
& fmt
.fixedmask
:
686 error(lineno
, 'pattern fixed bits overlap format fixed bits')
687 if width
!= fmt
.width
:
688 error(lineno
, 'pattern uses format of different width')
689 fieldmask |
= fmt
.fieldmask
690 fixedbits |
= fmt
.fixedbits
691 fixedmask |
= fmt
.fixedmask
692 undefmask |
= fmt
.undefmask
694 (fmt
, flds
) = infer_format(arg
, fieldmask
, flds
, width
)
696 for f
in flds
.keys():
697 if f
not in arg
.fields
:
698 error(lineno
, 'field {0} not in argument set {1}'
699 .format(f
, arg
.name
))
700 if f
in fmt
.fields
.keys():
701 error(lineno
, 'field {0} set by format and pattern'.format(f
))
703 if f
not in flds
.keys() and f
not in fmt
.fields
.keys():
704 error(lineno
, 'field {0} not initialized'.format(f
))
705 pat
= Pattern(name
, lineno
, fmt
, fixedbits
, fixedmask
,
706 undefmask
, fieldmask
, flds
, width
)
708 allpatterns
.append(pat
)
710 # Validate the masks that we have assembled.
711 if fieldmask
& fixedmask
:
712 error(lineno
, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
713 .format(fieldmask
, fixedmask
))
714 if fieldmask
& undefmask
:
715 error(lineno
, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
716 .format(fieldmask
, undefmask
))
717 if fixedmask
& undefmask
:
718 error(lineno
, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
719 .format(fixedmask
, undefmask
))
721 allbits
= fieldmask | fixedmask | undefmask
722 if allbits
!= insnmask
:
723 error(lineno
, 'bits left unspecified (0x{0:08x})'
724 .format(allbits ^ insnmask
))
727 def build_multi_pattern(lineno
, pats
):
728 """Validate the Patterns going into a MultiPattern."""
733 error(lineno
, 'less than two patterns within braces')
738 # Collect fixed/undefmask for all of the children.
739 # Move the defining lineno back to that of the first child.
741 fixedmask
&= p
.fixedmask
742 undefmask
&= p
.undefmask
743 if p
.lineno
< lineno
:
750 elif width
!= p
.width
:
751 error(lineno
, 'width mismatch in patterns within braces')
756 error(lineno
, 'no overlap in patterns within braces')
759 thisbits
= p
.fixedbits
& fixedmask
760 if fixedbits
is None:
762 elif fixedbits
!= thisbits
:
763 fixedmask
&= ~
(fixedbits ^ thisbits
)
768 mp
= MultiPattern(lineno
, pats
, fixedbits
, fixedmask
, undefmask
, width
)
770 # end build_multi_pattern
773 """Parse all of the patterns within a file"""
777 # Read all of the lines of the file. Concatenate lines
778 # ending in backslash; discard empty lines and comments.
787 # Expand and strip spaces, to find indent.
789 line
= line
.expandtabs()
801 # Next line after continuation
804 # Allow completely blank lines.
808 # Empty line due to comment.
810 # Indentation must be correct, even for comment lines.
811 if indent
!= nesting
:
812 error(lineno
, 'indentation ', indent
, ' != ', nesting
)
814 start_lineno
= lineno
828 error(start_lineno
, 'mismatched close brace')
830 error(start_lineno
, 'extra tokens after close brace')
832 if indent
!= nesting
:
833 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
835 patterns
= saved_pats
.pop()
836 build_multi_pattern(lineno
, pats
)
840 # Everything else should have current indentation.
841 if indent
!= nesting
:
842 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
847 error(start_lineno
, 'extra tokens after open brace')
848 saved_pats
.append(patterns
)
854 # Determine the type of object needing to be parsed.
856 parse_field(start_lineno
, name
[1:], toks
)
858 parse_arguments(start_lineno
, name
[1:], toks
)
860 parse_generic(start_lineno
, True, name
[1:], toks
)
862 parse_generic(start_lineno
, False, name
, toks
)
868 """Class representing a node in a decode tree"""
870 def __init__(self
, fm
, tm
):
878 r
= '{0}{1:08x}'.format(ind
, self
.fixedmask
)
880 r
+= ' ' + self
.format
.name
882 for (b
, s
) in self
.subs
:
883 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
884 r
+= s
.str1(i
+ 4) + '\n'
891 def output_code(self
, i
, extracted
, outerbits
, outermask
):
894 # If we identified all nodes below have the same format,
895 # extract the fields now.
896 if not extracted
and self
.base
:
897 output(ind
, self
.base
.extract_name(),
898 '(ctx, &u.f_', self
.base
.base
.name
, ', insn);\n')
901 # Attempt to aid the compiler in producing compact switch statements.
902 # If the bits in the mask are contiguous, extract them.
903 sh
= is_contiguous(self
.thismask
)
905 # Propagate SH down into the local functions.
906 def str_switch(b
, sh
=sh
):
907 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
909 def str_case(b
, sh
=sh
):
910 return '0x{0:x}'.format(b
>> sh
)
913 return 'insn & 0x{0:08x}'.format(b
)
916 return '0x{0:08x}'.format(b
)
918 output(ind
, 'switch (', str_switch(self
.thismask
), ') {\n')
919 for b
, s
in sorted(self
.subs
):
920 assert (self
.thismask
& ~s
.fixedmask
) == 0
921 innermask
= outermask | self
.thismask
922 innerbits
= outerbits | b
923 output(ind
, 'case ', str_case(b
), ':\n')
925 str_match_bits(innerbits
, innermask
), ' */\n')
926 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
927 output(ind
, ' return false;\n')
932 def build_tree(pats
, outerbits
, outermask
):
933 # Find the intersection of all remaining fixedmask.
934 innermask
= ~outermask
& insnmask
936 innermask
&= i
.fixedmask
939 text
= 'overlapping patterns:'
941 text
+= '\n' + p
.file + ':' + str(p
.lineno
) + ': ' + str(p
)
942 error_with_file(pats
[0].file, pats
[0].lineno
, text
)
944 fullmask
= outermask | innermask
946 # Sort each element of pats into the bin selected by the mask.
949 fb
= i
.fixedbits
& innermask
955 # We must recurse if any bin has more than one element or if
956 # the single element in the bin has not been fully matched.
957 t
= Tree(fullmask
, innermask
)
959 for b
, l
in bins
.items():
961 if len(l
) > 1 or s
.fixedmask
& ~fullmask
!= 0:
962 s
= build_tree(l
, b | outerbits
, fullmask
)
963 t
.subs
.append((b
, s
))
970 """Class representing a node in a size decode tree"""
972 def __init__(self
, m
, w
):
980 r
= '{0}{1:08x}'.format(ind
, self
.mask
)
982 for (b
, s
) in self
.subs
:
983 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
984 r
+= s
.str1(i
+ 4) + '\n'
991 def output_code(self
, i
, extracted
, outerbits
, outermask
):
994 # If we need to load more bytes to test, do so now.
995 if extracted
< self
.width
:
996 output(ind
, 'insn = ', decode_function
,
997 '_load_bytes(ctx, insn, {0}, {1});\n'
998 .format(extracted
/ 8, self
.width
/ 8));
999 extracted
= self
.width
1001 # Attempt to aid the compiler in producing compact switch statements.
1002 # If the bits in the mask are contiguous, extract them.
1003 sh
= is_contiguous(self
.mask
)
1005 # Propagate SH down into the local functions.
1006 def str_switch(b
, sh
=sh
):
1007 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
1009 def str_case(b
, sh
=sh
):
1010 return '0x{0:x}'.format(b
>> sh
)
1013 return 'insn & 0x{0:08x}'.format(b
)
1016 return '0x{0:08x}'.format(b
)
1018 output(ind
, 'switch (', str_switch(self
.mask
), ') {\n')
1019 for b
, s
in sorted(self
.subs
):
1020 innermask
= outermask | self
.mask
1021 innerbits
= outerbits | b
1022 output(ind
, 'case ', str_case(b
), ':\n')
1024 str_match_bits(innerbits
, innermask
), ' */\n')
1025 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
1027 output(ind
, 'return insn;\n')
1031 """Class representing a leaf node in a size decode tree"""
1033 def __init__(self
, m
, w
):
1039 return '{0}{1:08x}'.format(ind
, self
.mask
)
1044 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1045 global decode_function
1048 # If we need to load more bytes, do so now.
1049 if extracted
< self
.width
:
1050 output(ind
, 'insn = ', decode_function
,
1051 '_load_bytes(ctx, insn, {0}, {1});\n'
1052 .format(extracted
/ 8, self
.width
/ 8));
1053 extracted
= self
.width
1054 output(ind
, 'return insn;\n')
1058 def build_size_tree(pats
, width
, outerbits
, outermask
):
1061 # Collect the mask of bits that are fixed in this width
1062 innermask
= 0xff << (insnwidth
- width
)
1063 innermask
&= ~outermask
1067 innermask
&= i
.fixedmask
1068 if minwidth
is None:
1070 elif minwidth
!= i
.width
:
1072 if minwidth
< i
.width
:
1076 return SizeLeaf(innermask
, minwidth
)
1079 if width
< minwidth
:
1080 return build_size_tree(pats
, width
+ 8, outerbits
, outermask
)
1084 pnames
.append(p
.name
+ ':' + p
.file + ':' + str(p
.lineno
))
1085 error_with_file(pats
[0].file, pats
[0].lineno
,
1086 'overlapping patterns size {0}:'.format(width
), pnames
)
1090 fb
= i
.fixedbits
& innermask
1096 fullmask
= outermask | innermask
1097 lens
= sorted(bins
.keys())
1100 return build_size_tree(bins
[b
], width
+ 8, b | outerbits
, fullmask
)
1102 r
= SizeTree(innermask
, width
)
1103 for b
, l
in bins
.items():
1104 s
= build_size_tree(l
, width
, b | outerbits
, fullmask
)
1105 r
.subs
.append((b
, s
))
1107 # end build_size_tree
1110 def prop_format(tree
):
1111 """Propagate Format objects into the decode tree"""
1113 # Depth first search.
1114 for (b
, s
) in tree
.subs
:
1115 if isinstance(s
, Tree
):
1118 # If all entries in SUBS have the same format, then
1119 # propagate that into the tree.
1121 for (b
, s
) in tree
.subs
:
1132 def prop_size(tree
):
1133 """Propagate minimum widths up the decode size tree"""
1135 if isinstance(tree
, SizeTree
):
1137 for (b
, s
) in tree
.subs
:
1138 width
= prop_size(s
)
1139 if min is None or min > width
:
1141 assert min >= tree
.width
1154 global translate_scope
1155 global translate_prefix
1162 global decode_function
1163 global variablewidth
1165 decode_scope
= 'static '
1167 long_opts
= ['decode=', 'translate=', 'output=', 'insnwidth=',
1168 'static-decode=', 'varinsnwidth=']
1170 (opts
, args
) = getopt
.getopt(sys
.argv
[1:], 'o:vw:', long_opts
)
1171 except getopt
.GetoptError
as err
:
1174 if o
in ('-o', '--output'):
1176 elif o
== '--decode':
1179 elif o
== '--static-decode':
1181 elif o
== '--translate':
1182 translate_prefix
= a
1183 translate_scope
= ''
1184 elif o
in ('-w', '--insnwidth', '--varinsnwidth'):
1185 if o
== '--varinsnwidth':
1186 variablewidth
= True
1189 insntype
= 'uint16_t'
1191 elif insnwidth
!= 32:
1192 error(0, 'cannot handle insns of width', insnwidth
)
1194 assert False, 'unhandled option'
1197 error(0, 'missing input file')
1198 for filename
in args
:
1199 input_file
= filename
1200 f
= open(filename
, 'r')
1205 stree
= build_size_tree(patterns
, 8, 0, 0)
1208 dtree
= build_tree(patterns
, 0, 0)
1212 output_fd
= open(output_file
, 'w')
1214 output_fd
= sys
.stdout
1217 for n
in sorted(arguments
.keys()):
1221 # A single translate function can be invoked for different patterns.
1222 # Make sure that the argument sets are the same, and declare the
1223 # function only once.
1225 for i
in allpatterns
:
1226 if i
.name
in out_pats
:
1227 p
= out_pats
[i
.name
]
1228 if i
.base
.base
!= p
.base
.base
:
1229 error(0, i
.name
, ' has conflicting argument sets')
1232 out_pats
[i
.name
] = i
1235 for n
in sorted(formats
.keys()):
1239 output(decode_scope
, 'bool ', decode_function
,
1240 '(DisasContext *ctx, ', insntype
, ' insn)\n{\n')
1244 if len(allpatterns
) != 0:
1245 output(i4
, 'union {\n')
1246 for n
in sorted(arguments
.keys()):
1248 output(i4
, i4
, f
.struct_name(), ' f_', f
.name
, ';\n')
1249 output(i4
, '} u;\n\n')
1250 dtree
.output_code(4, False, 0, 0)
1252 output(i4
, 'return false;\n')
1256 output('\n', decode_scope
, insntype
, ' ', decode_function
,
1257 '_load(DisasContext *ctx)\n{\n',
1258 ' ', insntype
, ' insn = 0;\n\n')
1259 stree
.output_code(4, 0, 0, 0)
1267 if __name__
== '__main__':