blob: b559db3086f039e233cefcc5c20bd5a9a3c2075c [file] [log] [blame]
Philippe Mathieu-Daudé3d004a32020-01-30 17:32:25 +01001#!/usr/bin/env python3
Richard Henderson568ae7e2017-12-07 12:44:09 -08002# Copyright (c) 2018 Linaro Limited
3#
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.
8#
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.
13#
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/>.
16#
17
18#
19# Generate a decoding tree from a specification file.
Richard Henderson3fdbf5d2019-02-23 13:00:10 -080020# See the syntax and semantics in docs/devel/decodetree.rst.
Richard Henderson568ae7e2017-12-07 12:44:09 -080021#
22
Richard Henderson568ae7e2017-12-07 12:44:09 -080023import os
24import re
25import sys
26import getopt
Richard Henderson568ae7e2017-12-07 12:44:09 -080027
28insnwidth = 32
29insnmask = 0xffffffff
Richard Henderson17560e92019-01-30 18:01:29 -080030variablewidth = False
Richard Henderson568ae7e2017-12-07 12:44:09 -080031fields = {}
32arguments = {}
33formats = {}
34patterns = []
Richard Henderson0eff2df2019-02-23 11:35:36 -080035allpatterns = []
Richard Hendersonc6920792019-08-09 08:12:50 -070036anyextern = False
Richard Henderson568ae7e2017-12-07 12:44:09 -080037
38translate_prefix = 'trans'
39translate_scope = 'static '
40input_file = ''
41output_file = None
42output_fd = None
43insntype = 'uint32_t'
Richard Hendersonabd04f92018-10-23 10:26:25 +010044decode_function = 'decode'
Richard Henderson568ae7e2017-12-07 12:44:09 -080045
46re_ident = '[a-zA-Z][a-zA-Z0-9_]*'
47
48
Richard Henderson6699ae62018-10-26 14:59:43 +010049def error_with_file(file, lineno, *args):
Richard Henderson568ae7e2017-12-07 12:44:09 -080050 """Print an error message from file:line and args and exit."""
51 global output_file
52 global output_fd
53
Richard Henderson2fd51b12020-05-15 14:48:54 -070054 prefix = ''
55 if file:
56 prefix += '{0}:'.format(file)
Richard Henderson568ae7e2017-12-07 12:44:09 -080057 if lineno:
Richard Henderson2fd51b12020-05-15 14:48:54 -070058 prefix += '{0}:'.format(lineno)
59 if prefix:
60 prefix += ' '
61 print(prefix, end='error: ', file=sys.stderr)
62 print(*args, file=sys.stderr)
63
Richard Henderson568ae7e2017-12-07 12:44:09 -080064 if output_file and output_fd:
65 output_fd.close()
66 os.remove(output_file)
67 exit(1)
Richard Henderson2fd51b12020-05-15 14:48:54 -070068# end error_with_file
69
Richard Henderson568ae7e2017-12-07 12:44:09 -080070
Richard Henderson6699ae62018-10-26 14:59:43 +010071def error(lineno, *args):
Richard Henderson2fd51b12020-05-15 14:48:54 -070072 error_with_file(input_file, lineno, *args)
73# end error
74
Richard Henderson568ae7e2017-12-07 12:44:09 -080075
76def output(*args):
77 global output_fd
78 for a in args:
79 output_fd.write(a)
80
81
Richard Henderson568ae7e2017-12-07 12:44:09 -080082def output_autogen():
83 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
84
85
86def str_indent(c):
87 """Return a string with C spaces"""
88 return ' ' * c
89
90
91def str_fields(fields):
92 """Return a string uniquely identifing FIELDS"""
93 r = ''
94 for n in sorted(fields.keys()):
95 r += '_' + n
96 return r[1:]
97
98
99def str_match_bits(bits, mask):
100 """Return a string pretty-printing BITS/MASK"""
101 global insnwidth
102
103 i = 1 << (insnwidth - 1)
104 space = 0x01010100
105 r = ''
106 while i != 0:
107 if i & mask:
108 if i & bits:
109 r += '1'
110 else:
111 r += '0'
112 else:
113 r += '.'
114 if i & space:
115 r += ' '
116 i >>= 1
117 return r
118
119
120def is_pow2(x):
121 """Return true iff X is equal to a power of 2."""
122 return (x & (x - 1)) == 0
123
124
125def ctz(x):
126 """Return the number of times 2 factors into X."""
127 r = 0
128 while ((x >> r) & 1) == 0:
129 r += 1
130 return r
131
132
133def is_contiguous(bits):
134 shift = ctz(bits)
135 if is_pow2((bits >> shift) + 1):
136 return shift
137 else:
138 return -1
139
140
141def eq_fields_for_args(flds_a, flds_b):
142 if len(flds_a) != len(flds_b):
143 return False
144 for k, a in flds_a.items():
145 if k not in flds_b:
146 return False
147 return True
148
149
150def eq_fields_for_fmts(flds_a, flds_b):
151 if len(flds_a) != len(flds_b):
152 return False
153 for k, a in flds_a.items():
154 if k not in flds_b:
155 return False
156 b = flds_b[k]
157 if a.__class__ != b.__class__ or a != b:
158 return False
159 return True
160
161
162class Field:
163 """Class representing a simple instruction field"""
164 def __init__(self, sign, pos, len):
165 self.sign = sign
166 self.pos = pos
167 self.len = len
168 self.mask = ((1 << len) - 1) << pos
169
170 def __str__(self):
171 if self.sign:
172 s = 's'
173 else:
174 s = ''
Cleber Rosacbcdf1a2018-10-04 12:18:50 -0400175 return str(self.pos) + ':' + s + str(self.len)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800176
177 def str_extract(self):
178 if self.sign:
179 extr = 'sextract32'
180 else:
181 extr = 'extract32'
182 return '{0}(insn, {1}, {2})'.format(extr, self.pos, self.len)
183
184 def __eq__(self, other):
Richard Henderson2c7d4422019-06-11 16:39:41 +0100185 return self.sign == other.sign and self.mask == other.mask
Richard Henderson568ae7e2017-12-07 12:44:09 -0800186
187 def __ne__(self, other):
188 return not self.__eq__(other)
189# end Field
190
191
192class MultiField:
193 """Class representing a compound instruction field"""
194 def __init__(self, subs, mask):
195 self.subs = subs
196 self.sign = subs[0].sign
197 self.mask = mask
198
199 def __str__(self):
200 return str(self.subs)
201
202 def str_extract(self):
203 ret = '0'
204 pos = 0
205 for f in reversed(self.subs):
206 if pos == 0:
207 ret = f.str_extract()
208 else:
209 ret = 'deposit32({0}, {1}, {2}, {3})' \
210 .format(ret, pos, 32 - pos, f.str_extract())
211 pos += f.len
212 return ret
213
214 def __ne__(self, other):
215 if len(self.subs) != len(other.subs):
216 return True
217 for a, b in zip(self.subs, other.subs):
218 if a.__class__ != b.__class__ or a != b:
219 return True
220 return False
221
222 def __eq__(self, other):
223 return not self.__ne__(other)
224# end MultiField
225
226
227class ConstField:
228 """Class representing an argument field with constant value"""
229 def __init__(self, value):
230 self.value = value
231 self.mask = 0
232 self.sign = value < 0
233
234 def __str__(self):
235 return str(self.value)
236
237 def str_extract(self):
238 return str(self.value)
239
240 def __cmp__(self, other):
241 return self.value - other.value
242# end ConstField
243
244
245class FunctionField:
Richard Henderson94597b62019-07-22 17:02:56 -0700246 """Class representing a field passed through a function"""
Richard Henderson568ae7e2017-12-07 12:44:09 -0800247 def __init__(self, func, base):
248 self.mask = base.mask
249 self.sign = base.sign
250 self.base = base
251 self.func = func
252
253 def __str__(self):
254 return self.func + '(' + str(self.base) + ')'
255
256 def str_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700257 return self.func + '(ctx, ' + self.base.str_extract() + ')'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800258
259 def __eq__(self, other):
260 return self.func == other.func and self.base == other.base
261
262 def __ne__(self, other):
263 return not self.__eq__(other)
264# end FunctionField
265
266
Richard Henderson94597b62019-07-22 17:02:56 -0700267class ParameterField:
268 """Class representing a pseudo-field read from a function"""
269 def __init__(self, func):
270 self.mask = 0
271 self.sign = 0
272 self.func = func
273
274 def __str__(self):
275 return self.func
276
277 def str_extract(self):
278 return self.func + '(ctx)'
279
280 def __eq__(self, other):
281 return self.func == other.func
282
283 def __ne__(self, other):
284 return not self.__eq__(other)
285# end ParameterField
286
287
Richard Henderson568ae7e2017-12-07 12:44:09 -0800288class Arguments:
289 """Class representing the extracted fields of a format"""
Richard Hendersonabd04f92018-10-23 10:26:25 +0100290 def __init__(self, nm, flds, extern):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800291 self.name = nm
Richard Hendersonabd04f92018-10-23 10:26:25 +0100292 self.extern = extern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800293 self.fields = sorted(flds)
294
295 def __str__(self):
296 return self.name + ' ' + str(self.fields)
297
298 def struct_name(self):
299 return 'arg_' + self.name
300
301 def output_def(self):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100302 if not self.extern:
303 output('typedef struct {\n')
304 for n in self.fields:
305 output(' int ', n, ';\n')
306 output('} ', self.struct_name(), ';\n\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800307# end Arguments
308
309
310class General:
311 """Common code between instruction formats and instruction patterns"""
Richard Henderson17560e92019-01-30 18:01:29 -0800312 def __init__(self, name, lineno, base, fixb, fixm, udfm, fldm, flds, w):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800313 self.name = name
Richard Henderson6699ae62018-10-26 14:59:43 +0100314 self.file = input_file
Richard Henderson568ae7e2017-12-07 12:44:09 -0800315 self.lineno = lineno
316 self.base = base
317 self.fixedbits = fixb
318 self.fixedmask = fixm
319 self.undefmask = udfm
320 self.fieldmask = fldm
321 self.fields = flds
Richard Henderson17560e92019-01-30 18:01:29 -0800322 self.width = w
Richard Henderson568ae7e2017-12-07 12:44:09 -0800323
324 def __str__(self):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800325 return self.name + ' ' + str_match_bits(self.fixedbits, self.fixedmask)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800326
327 def str1(self, i):
328 return str_indent(i) + self.__str__()
329# end General
330
331
332class Format(General):
333 """Class representing an instruction format"""
334
335 def extract_name(self):
Richard Henderson71ecf792019-02-28 14:45:50 -0800336 global decode_function
337 return decode_function + '_extract_' + self.name
Richard Henderson568ae7e2017-12-07 12:44:09 -0800338
339 def output_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700340 output('static void ', self.extract_name(), '(DisasContext *ctx, ',
Richard Henderson568ae7e2017-12-07 12:44:09 -0800341 self.base.struct_name(), ' *a, ', insntype, ' insn)\n{\n')
342 for n, f in self.fields.items():
343 output(' a->', n, ' = ', f.str_extract(), ';\n')
344 output('}\n\n')
345# end Format
346
347
348class Pattern(General):
349 """Class representing an instruction pattern"""
350
351 def output_decl(self):
352 global translate_scope
353 global translate_prefix
354 output('typedef ', self.base.base.struct_name(),
355 ' arg_', self.name, ';\n')
Richard Henderson76805592018-03-02 10:45:35 +0000356 output(translate_scope, 'bool ', translate_prefix, '_', self.name,
Richard Henderson3a7be552018-10-23 11:05:27 +0100357 '(DisasContext *ctx, arg_', self.name, ' *a);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800358
359 def output_code(self, i, extracted, outerbits, outermask):
360 global translate_prefix
361 ind = str_indent(i)
362 arg = self.base.base.name
Richard Henderson6699ae62018-10-26 14:59:43 +0100363 output(ind, '/* ', self.file, ':', str(self.lineno), ' */\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800364 if not extracted:
Richard Henderson451e4ff2019-03-20 19:21:31 -0700365 output(ind, self.base.extract_name(),
366 '(ctx, &u.f_', arg, ', insn);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800367 for n, f in self.fields.items():
368 output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n')
Richard Hendersoneb6b87f2019-02-23 08:57:46 -0800369 output(ind, 'if (', translate_prefix, '_', self.name,
370 '(ctx, &u.f_', arg, ')) return true;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800371# end Pattern
372
373
Richard Henderson0eff2df2019-02-23 11:35:36 -0800374class MultiPattern(General):
375 """Class representing an overlapping set of instruction patterns"""
376
Richard Henderson17560e92019-01-30 18:01:29 -0800377 def __init__(self, lineno, pats, fixb, fixm, udfm, w):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800378 self.file = input_file
379 self.lineno = lineno
380 self.pats = pats
381 self.base = None
382 self.fixedbits = fixb
383 self.fixedmask = fixm
384 self.undefmask = udfm
Richard Henderson17560e92019-01-30 18:01:29 -0800385 self.width = w
Richard Henderson0eff2df2019-02-23 11:35:36 -0800386
387 def __str__(self):
388 r = "{"
389 for p in self.pats:
390 r = r + ' ' + str(p)
391 return r + "}"
392
393 def output_decl(self):
394 for p in self.pats:
395 p.output_decl()
396
397 def output_code(self, i, extracted, outerbits, outermask):
398 global translate_prefix
399 ind = str_indent(i)
400 for p in self.pats:
401 if outermask != p.fixedmask:
402 innermask = p.fixedmask & ~outermask
403 innerbits = p.fixedbits & ~outermask
404 output(ind, 'if ((insn & ',
405 '0x{0:08x}) == 0x{1:08x}'.format(innermask, innerbits),
406 ') {\n')
407 output(ind, ' /* ',
408 str_match_bits(p.fixedbits, p.fixedmask), ' */\n')
409 p.output_code(i + 4, extracted, p.fixedbits, p.fixedmask)
410 output(ind, '}\n')
411 else:
412 p.output_code(i, extracted, p.fixedbits, p.fixedmask)
413#end MultiPattern
414
415
Richard Henderson568ae7e2017-12-07 12:44:09 -0800416def parse_field(lineno, name, toks):
417 """Parse one instruction field from TOKS at LINENO"""
418 global fields
419 global re_ident
420 global insnwidth
421
422 # A "simple" field will have only one entry;
423 # a "multifield" will have several.
424 subs = []
425 width = 0
426 func = None
427 for t in toks:
John Snow2d110c12020-05-13 23:52:30 -0400428 if re.fullmatch('!function=' + re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800429 if func:
430 error(lineno, 'duplicate function')
431 func = t.split('=')
432 func = func[1]
433 continue
434
John Snow2d110c12020-05-13 23:52:30 -0400435 if re.fullmatch('[0-9]+:s[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800436 # Signed field extract
437 subtoks = t.split(':s')
438 sign = True
John Snow2d110c12020-05-13 23:52:30 -0400439 elif re.fullmatch('[0-9]+:[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800440 # Unsigned field extract
441 subtoks = t.split(':')
442 sign = False
443 else:
444 error(lineno, 'invalid field token "{0}"'.format(t))
445 po = int(subtoks[0])
446 le = int(subtoks[1])
447 if po + le > insnwidth:
448 error(lineno, 'field {0} too large'.format(t))
449 f = Field(sign, po, le)
450 subs.append(f)
451 width += le
452
453 if width > insnwidth:
454 error(lineno, 'field too large')
Richard Henderson94597b62019-07-22 17:02:56 -0700455 if len(subs) == 0:
456 if func:
457 f = ParameterField(func)
458 else:
459 error(lineno, 'field with no value')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800460 else:
Richard Henderson94597b62019-07-22 17:02:56 -0700461 if len(subs) == 1:
462 f = subs[0]
463 else:
464 mask = 0
465 for s in subs:
466 if mask & s.mask:
467 error(lineno, 'field components overlap')
468 mask |= s.mask
469 f = MultiField(subs, mask)
470 if func:
471 f = FunctionField(func, f)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800472
473 if name in fields:
474 error(lineno, 'duplicate field', name)
475 fields[name] = f
476# end parse_field
477
478
479def parse_arguments(lineno, name, toks):
480 """Parse one argument set from TOKS at LINENO"""
481 global arguments
482 global re_ident
Richard Hendersonc6920792019-08-09 08:12:50 -0700483 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800484
485 flds = []
Richard Hendersonabd04f92018-10-23 10:26:25 +0100486 extern = False
Richard Henderson568ae7e2017-12-07 12:44:09 -0800487 for t in toks:
John Snow2d110c12020-05-13 23:52:30 -0400488 if re.fullmatch('!extern', t):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100489 extern = True
Richard Hendersonc6920792019-08-09 08:12:50 -0700490 anyextern = True
Richard Hendersonabd04f92018-10-23 10:26:25 +0100491 continue
John Snow2d110c12020-05-13 23:52:30 -0400492 if not re.fullmatch(re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800493 error(lineno, 'invalid argument set token "{0}"'.format(t))
494 if t in flds:
495 error(lineno, 'duplicate argument "{0}"'.format(t))
496 flds.append(t)
497
498 if name in arguments:
499 error(lineno, 'duplicate argument set', name)
Richard Hendersonabd04f92018-10-23 10:26:25 +0100500 arguments[name] = Arguments(name, flds, extern)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800501# end parse_arguments
502
503
504def lookup_field(lineno, name):
505 global fields
506 if name in fields:
507 return fields[name]
508 error(lineno, 'undefined field', name)
509
510
511def add_field(lineno, flds, new_name, f):
512 if new_name in flds:
513 error(lineno, 'duplicate field', new_name)
514 flds[new_name] = f
515 return flds
516
517
518def add_field_byname(lineno, flds, new_name, old_name):
519 return add_field(lineno, flds, new_name, lookup_field(lineno, old_name))
520
521
522def infer_argument_set(flds):
523 global arguments
Richard Hendersonabd04f92018-10-23 10:26:25 +0100524 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800525
526 for arg in arguments.values():
527 if eq_fields_for_args(flds, arg.fields):
528 return arg
529
Richard Hendersonabd04f92018-10-23 10:26:25 +0100530 name = decode_function + str(len(arguments))
531 arg = Arguments(name, flds.keys(), False)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800532 arguments[name] = arg
533 return arg
534
535
Richard Henderson17560e92019-01-30 18:01:29 -0800536def infer_format(arg, fieldmask, flds, width):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800537 global arguments
538 global formats
Richard Hendersonabd04f92018-10-23 10:26:25 +0100539 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800540
541 const_flds = {}
542 var_flds = {}
543 for n, c in flds.items():
544 if c is ConstField:
545 const_flds[n] = c
546 else:
547 var_flds[n] = c
548
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:
552 continue
553 if fieldmask != fmt.fieldmask:
554 continue
Richard Henderson17560e92019-01-30 18:01:29 -0800555 if width != fmt.width:
556 continue
Richard Henderson568ae7e2017-12-07 12:44:09 -0800557 if not eq_fields_for_fmts(flds, fmt.fields):
558 continue
559 return (fmt, const_flds)
560
Richard Hendersonabd04f92018-10-23 10:26:25 +0100561 name = decode_function + '_Fmt_' + str(len(formats))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800562 if not arg:
563 arg = infer_argument_set(flds)
564
Richard Henderson17560e92019-01-30 18:01:29 -0800565 fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800566 formats[name] = fmt
567
568 return (fmt, const_flds)
569# end infer_format
570
571
572def parse_generic(lineno, is_format, name, toks):
573 """Parse one instruction format from TOKS at LINENO"""
574 global fields
575 global arguments
576 global formats
577 global patterns
Richard Henderson0eff2df2019-02-23 11:35:36 -0800578 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -0800579 global re_ident
580 global insnwidth
581 global insnmask
Richard Henderson17560e92019-01-30 18:01:29 -0800582 global variablewidth
Richard Henderson568ae7e2017-12-07 12:44:09 -0800583
584 fixedmask = 0
585 fixedbits = 0
586 undefmask = 0
587 width = 0
588 flds = {}
589 arg = None
590 fmt = None
591 for t in toks:
592 # '&Foo' gives a format an explcit argument set.
593 if t[0] == '&':
594 tt = t[1:]
595 if arg:
596 error(lineno, 'multiple argument sets')
597 if tt in arguments:
598 arg = arguments[tt]
599 else:
600 error(lineno, 'undefined argument set', t)
601 continue
602
603 # '@Foo' gives a pattern an explicit format.
604 if t[0] == '@':
605 tt = t[1:]
606 if fmt:
607 error(lineno, 'multiple formats')
608 if tt in formats:
609 fmt = formats[tt]
610 else:
611 error(lineno, 'undefined format', t)
612 continue
613
614 # '%Foo' imports a field.
615 if t[0] == '%':
616 tt = t[1:]
617 flds = add_field_byname(lineno, flds, tt, tt)
618 continue
619
620 # 'Foo=%Bar' imports a field with a different name.
John Snow2d110c12020-05-13 23:52:30 -0400621 if re.fullmatch(re_ident + '=%' + re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800622 (fname, iname) = t.split('=%')
623 flds = add_field_byname(lineno, flds, fname, iname)
624 continue
625
626 # 'Foo=number' sets an argument field to a constant value
John Snow2d110c12020-05-13 23:52:30 -0400627 if re.fullmatch(re_ident + '=[+-]?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800628 (fname, value) = t.split('=')
629 value = int(value)
630 flds = add_field(lineno, flds, fname, ConstField(value))
631 continue
632
633 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
634 # required ones, or dont-cares.
John Snow2d110c12020-05-13 23:52:30 -0400635 if re.fullmatch('[01.-]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800636 shift = len(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')
645 fms = int(fms, 2)
646 fbs = int(fbs, 2)
647 ubm = int(ubm, 2)
648 fixedbits = (fixedbits << shift) | fbs
649 fixedmask = (fixedmask << shift) | fms
650 undefmask = (undefmask << shift) | ubm
651 # Otherwise, fieldname:fieldwidth
John Snow2d110c12020-05-13 23:52:30 -0400652 elif re.fullmatch(re_ident + ':s?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800653 (fname, flen) = t.split(':')
654 sign = False
655 if flen[0] == 's':
656 sign = True
657 flen = flen[1:]
658 shift = int(flen, 10)
Richard Henderson2decfc92019-03-05 15:34:41 -0800659 if shift + width > insnwidth:
660 error(lineno, 'field {0} exceeds insnwidth'.format(fname))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800661 f = Field(sign, insnwidth - width - shift, shift)
662 flds = add_field(lineno, flds, fname, f)
663 fixedbits <<= shift
664 fixedmask <<= shift
665 undefmask <<= shift
666 else:
667 error(lineno, 'invalid token "{0}"'.format(t))
668 width += shift
669
Richard Henderson17560e92019-01-30 18:01:29 -0800670 if variablewidth and width < insnwidth and width % 8 == 0:
671 shift = insnwidth - width
672 fixedbits <<= shift
673 fixedmask <<= shift
674 undefmask <<= shift
675 undefmask |= (1 << shift) - 1
676
Richard Henderson568ae7e2017-12-07 12:44:09 -0800677 # We should have filled in all of the bits of the instruction.
Richard Henderson17560e92019-01-30 18:01:29 -0800678 elif not (is_format and width == 0) and width != insnwidth:
Richard Henderson568ae7e2017-12-07 12:44:09 -0800679 error(lineno, 'definition has {0} bits'.format(width))
680
681 # Do not check for fields overlaping fields; one valid usage
682 # is to be able to duplicate fields via import.
683 fieldmask = 0
684 for f in flds.values():
685 fieldmask |= f.mask
686
687 # Fix up what we've parsed to match either a format or a pattern.
688 if is_format:
689 # Formats cannot reference formats.
690 if fmt:
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.
694 if arg:
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))
699 else:
700 arg = infer_argument_set(flds)
701 if name in formats:
702 error(lineno, 'duplicate format name', name)
703 fmt = Format(name, lineno, arg, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800704 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800705 formats[name] = fmt
706 else:
707 # Patterns can reference a format ...
708 if fmt:
709 # ... but not an argument simultaneously
710 if arg:
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')
Richard Henderson17560e92019-01-30 18:01:29 -0800714 if width != fmt.width:
715 error(lineno, 'pattern uses format of different width')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800716 fieldmask |= fmt.fieldmask
717 fixedbits |= fmt.fixedbits
718 fixedmask |= fmt.fixedmask
719 undefmask |= fmt.undefmask
720 else:
Richard Henderson17560e92019-01-30 18:01:29 -0800721 (fmt, flds) = infer_format(arg, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800722 arg = fmt.base
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))
729 for f in arg.fields:
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,
Richard Henderson17560e92019-01-30 18:01:29 -0800733 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800734 patterns.append(pat)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800735 allpatterns.append(pat)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800736
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))
747 if not is_format:
748 allbits = fieldmask | fixedmask | undefmask
749 if allbits != insnmask:
750 error(lineno, 'bits left unspecified (0x{0:08x})'
751 .format(allbits ^ insnmask))
752# end parse_general
753
Richard Henderson0eff2df2019-02-23 11:35:36 -0800754def build_multi_pattern(lineno, pats):
755 """Validate the Patterns going into a MultiPattern."""
756 global patterns
757 global insnmask
758
759 if len(pats) < 2:
760 error(lineno, 'less than two patterns within braces')
761
762 fixedmask = insnmask
763 undefmask = insnmask
764
765 # Collect fixed/undefmask for all of the children.
766 # Move the defining lineno back to that of the first child.
767 for p in pats:
768 fixedmask &= p.fixedmask
769 undefmask &= p.undefmask
770 if p.lineno < lineno:
771 lineno = p.lineno
772
Richard Henderson17560e92019-01-30 18:01:29 -0800773 width = None
774 for p in pats:
775 if width is None:
776 width = p.width
777 elif width != p.width:
778 error(lineno, 'width mismatch in patterns within braces')
779
Richard Henderson0eff2df2019-02-23 11:35:36 -0800780 repeat = True
781 while repeat:
782 if fixedmask == 0:
783 error(lineno, 'no overlap in patterns within braces')
784 fixedbits = None
785 for p in pats:
786 thisbits = p.fixedbits & fixedmask
787 if fixedbits is None:
788 fixedbits = thisbits
789 elif fixedbits != thisbits:
790 fixedmask &= ~(fixedbits ^ thisbits)
791 break
792 else:
793 repeat = False
794
Richard Henderson17560e92019-01-30 18:01:29 -0800795 mp = MultiPattern(lineno, pats, fixedbits, fixedmask, undefmask, width)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800796 patterns.append(mp)
797# end build_multi_pattern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800798
799def parse_file(f):
800 """Parse all of the patterns within a file"""
801
Richard Henderson0eff2df2019-02-23 11:35:36 -0800802 global patterns
803
Richard Henderson568ae7e2017-12-07 12:44:09 -0800804 # Read all of the lines of the file. Concatenate lines
805 # ending in backslash; discard empty lines and comments.
806 toks = []
807 lineno = 0
Richard Henderson0eff2df2019-02-23 11:35:36 -0800808 nesting = 0
809 saved_pats = []
810
Richard Henderson568ae7e2017-12-07 12:44:09 -0800811 for line in f:
812 lineno += 1
813
Richard Henderson0eff2df2019-02-23 11:35:36 -0800814 # Expand and strip spaces, to find indent.
815 line = line.rstrip()
816 line = line.expandtabs()
817 len1 = len(line)
818 line = line.lstrip()
819 len2 = len(line)
820
Richard Henderson568ae7e2017-12-07 12:44:09 -0800821 # Discard comments
822 end = line.find('#')
823 if end >= 0:
824 line = line[:end]
825
826 t = line.split()
827 if len(toks) != 0:
828 # Next line after continuation
829 toks.extend(t)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800830 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800831 # Allow completely blank lines.
832 if len1 == 0:
833 continue
834 indent = len1 - len2
835 # Empty line due to comment.
836 if len(t) == 0:
837 # Indentation must be correct, even for comment lines.
838 if indent != nesting:
839 error(lineno, 'indentation ', indent, ' != ', nesting)
840 continue
841 start_lineno = lineno
Richard Henderson568ae7e2017-12-07 12:44:09 -0800842 toks = t
843
844 # Continuation?
845 if toks[-1] == '\\':
846 toks.pop()
847 continue
848
Richard Henderson568ae7e2017-12-07 12:44:09 -0800849 name = toks[0]
850 del toks[0]
851
Richard Henderson0eff2df2019-02-23 11:35:36 -0800852 # End nesting?
853 if name == '}':
854 if nesting == 0:
855 error(start_lineno, 'mismatched close brace')
856 if len(toks) != 0:
857 error(start_lineno, 'extra tokens after close brace')
858 nesting -= 2
859 if indent != nesting:
860 error(start_lineno, 'indentation ', indent, ' != ', nesting)
861 pats = patterns
862 patterns = saved_pats.pop()
863 build_multi_pattern(lineno, pats)
864 toks = []
865 continue
866
867 # Everything else should have current indentation.
868 if indent != nesting:
869 error(start_lineno, 'indentation ', indent, ' != ', nesting)
870
871 # Start nesting?
872 if name == '{':
873 if len(toks) != 0:
874 error(start_lineno, 'extra tokens after open brace')
875 saved_pats.append(patterns)
876 patterns = []
877 nesting += 2
878 toks = []
879 continue
880
Richard Henderson568ae7e2017-12-07 12:44:09 -0800881 # Determine the type of object needing to be parsed.
882 if name[0] == '%':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800883 parse_field(start_lineno, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800884 elif name[0] == '&':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800885 parse_arguments(start_lineno, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800886 elif name[0] == '@':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800887 parse_generic(start_lineno, True, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800888 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800889 parse_generic(start_lineno, False, name, toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800890 toks = []
891# end parse_file
892
893
894class Tree:
895 """Class representing a node in a decode tree"""
896
897 def __init__(self, fm, tm):
898 self.fixedmask = fm
899 self.thismask = tm
900 self.subs = []
901 self.base = None
902
903 def str1(self, i):
904 ind = str_indent(i)
905 r = '{0}{1:08x}'.format(ind, self.fixedmask)
906 if self.format:
907 r += ' ' + self.format.name
908 r += ' [\n'
909 for (b, s) in self.subs:
910 r += '{0} {1:08x}:\n'.format(ind, b)
911 r += s.str1(i + 4) + '\n'
912 r += ind + ']'
913 return r
914
915 def __str__(self):
916 return self.str1(0)
917
918 def output_code(self, i, extracted, outerbits, outermask):
919 ind = str_indent(i)
920
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(),
Richard Henderson451e4ff2019-03-20 19:21:31 -0700925 '(ctx, &u.f_', self.base.base.name, ', insn);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800926 extracted = True
927
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)
931 if sh > 0:
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)
935
936 def str_case(b, sh=sh):
937 return '0x{0:x}'.format(b >> sh)
938 else:
939 def str_switch(b):
940 return 'insn & 0x{0:08x}'.format(b)
941
942 def str_case(b):
943 return '0x{0:08x}'.format(b)
944
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')
951 output(ind, ' /* ',
952 str_match_bits(innerbits, innermask), ' */\n')
953 s.output_code(i + 4, extracted, innerbits, innermask)
Richard Hendersoneb6b87f2019-02-23 08:57:46 -0800954 output(ind, ' return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800955 output(ind, '}\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800956# end Tree
957
958
959def build_tree(pats, outerbits, outermask):
960 # Find the intersection of all remaining fixedmask.
Philippe Mathieu-Daudé9b3186e2018-12-16 20:07:38 -0800961 innermask = ~outermask & insnmask
Richard Henderson568ae7e2017-12-07 12:44:09 -0800962 for i in pats:
963 innermask &= i.fixedmask
964
965 if innermask == 0:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800966 text = 'overlapping patterns:'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800967 for p in pats:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800968 text += '\n' + p.file + ':' + str(p.lineno) + ': ' + str(p)
969 error_with_file(pats[0].file, pats[0].lineno, text)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800970
971 fullmask = outermask | innermask
972
973 # Sort each element of pats into the bin selected by the mask.
974 bins = {}
975 for i in pats:
976 fb = i.fixedbits & innermask
977 if fb in bins:
978 bins[fb].append(i)
979 else:
980 bins[fb] = [i]
981
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)
985
986 for b, l in bins.items():
987 s = l[0]
988 if len(l) > 1 or s.fixedmask & ~fullmask != 0:
989 s = build_tree(l, b | outerbits, fullmask)
990 t.subs.append((b, s))
991
992 return t
993# end build_tree
994
995
Richard Henderson70e07112019-01-31 11:34:11 -0800996class SizeTree:
997 """Class representing a node in a size decode tree"""
998
999 def __init__(self, m, w):
1000 self.mask = m
1001 self.subs = []
1002 self.base = None
1003 self.width = w
1004
1005 def str1(self, i):
1006 ind = str_indent(i)
1007 r = '{0}{1:08x}'.format(ind, self.mask)
1008 r += ' [\n'
1009 for (b, s) in self.subs:
1010 r += '{0} {1:08x}:\n'.format(ind, b)
1011 r += s.str1(i + 4) + '\n'
1012 r += ind + ']'
1013 return r
1014
1015 def __str__(self):
1016 return self.str1(0)
1017
1018 def output_code(self, i, extracted, outerbits, outermask):
1019 ind = str_indent(i)
1020
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'
Philippe Mathieu-Daudéb4123782020-03-30 14:13:45 +02001025 .format(extracted // 8, self.width // 8));
Richard Henderson70e07112019-01-31 11:34:11 -08001026 extracted = self.width
1027
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)
1031 if sh > 0:
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)
1035
1036 def str_case(b, sh=sh):
1037 return '0x{0:x}'.format(b >> sh)
1038 else:
1039 def str_switch(b):
1040 return 'insn & 0x{0:08x}'.format(b)
1041
1042 def str_case(b):
1043 return '0x{0:08x}'.format(b)
1044
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')
1050 output(ind, ' /* ',
1051 str_match_bits(innerbits, innermask), ' */\n')
1052 s.output_code(i + 4, extracted, innerbits, innermask)
1053 output(ind, '}\n')
1054 output(ind, 'return insn;\n')
1055# end SizeTree
1056
1057class SizeLeaf:
1058 """Class representing a leaf node in a size decode tree"""
1059
1060 def __init__(self, m, w):
1061 self.mask = m
1062 self.width = w
1063
1064 def str1(self, i):
1065 ind = str_indent(i)
1066 return '{0}{1:08x}'.format(ind, self.mask)
1067
1068 def __str__(self):
1069 return self.str1(0)
1070
1071 def output_code(self, i, extracted, outerbits, outermask):
1072 global decode_function
1073 ind = str_indent(i)
1074
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'
Philippe Mathieu-Daudéb4123782020-03-30 14:13:45 +02001079 .format(extracted // 8, self.width // 8));
Richard Henderson70e07112019-01-31 11:34:11 -08001080 extracted = self.width
1081 output(ind, 'return insn;\n')
1082# end SizeLeaf
1083
1084
1085def build_size_tree(pats, width, outerbits, outermask):
1086 global insnwidth
1087
1088 # Collect the mask of bits that are fixed in this width
1089 innermask = 0xff << (insnwidth - width)
1090 innermask &= ~outermask
1091 minwidth = None
1092 onewidth = True
1093 for i in pats:
1094 innermask &= i.fixedmask
1095 if minwidth is None:
1096 minwidth = i.width
1097 elif minwidth != i.width:
1098 onewidth = False;
1099 if minwidth < i.width:
1100 minwidth = i.width
1101
1102 if onewidth:
1103 return SizeLeaf(innermask, minwidth)
1104
1105 if innermask == 0:
1106 if width < minwidth:
1107 return build_size_tree(pats, width + 8, outerbits, outermask)
1108
1109 pnames = []
1110 for p in pats:
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)
1114
1115 bins = {}
1116 for i in pats:
1117 fb = i.fixedbits & innermask
1118 if fb in bins:
1119 bins[fb].append(i)
1120 else:
1121 bins[fb] = [i]
1122
1123 fullmask = outermask | innermask
1124 lens = sorted(bins.keys())
1125 if len(lens) == 1:
1126 b = lens[0]
1127 return build_size_tree(bins[b], width + 8, b | outerbits, fullmask)
1128
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))
1133 return r
1134# end build_size_tree
1135
1136
Richard Henderson568ae7e2017-12-07 12:44:09 -08001137def prop_format(tree):
1138 """Propagate Format objects into the decode tree"""
1139
1140 # Depth first search.
1141 for (b, s) in tree.subs:
1142 if isinstance(s, Tree):
1143 prop_format(s)
1144
1145 # If all entries in SUBS have the same format, then
1146 # propagate that into the tree.
1147 f = None
1148 for (b, s) in tree.subs:
1149 if f is None:
1150 f = s.base
1151 if f is None:
1152 return
1153 if f is not s.base:
1154 return
1155 tree.base = f
1156# end prop_format
1157
1158
Richard Henderson70e07112019-01-31 11:34:11 -08001159def prop_size(tree):
1160 """Propagate minimum widths up the decode size tree"""
1161
1162 if isinstance(tree, SizeTree):
1163 min = None
1164 for (b, s) in tree.subs:
1165 width = prop_size(s)
1166 if min is None or min > width:
1167 min = width
1168 assert min >= tree.width
1169 tree.width = min
1170 else:
1171 min = tree.width
1172 return min
1173# end prop_size
1174
1175
Richard Henderson568ae7e2017-12-07 12:44:09 -08001176def main():
1177 global arguments
1178 global formats
1179 global patterns
Richard Henderson0eff2df2019-02-23 11:35:36 -08001180 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -08001181 global translate_scope
1182 global translate_prefix
1183 global output_fd
1184 global output_file
1185 global input_file
1186 global insnwidth
1187 global insntype
Bastian Koppelmann83d7c402018-03-19 12:58:46 +01001188 global insnmask
Richard Hendersonabd04f92018-10-23 10:26:25 +01001189 global decode_function
Richard Henderson17560e92019-01-30 18:01:29 -08001190 global variablewidth
Richard Hendersonc6920792019-08-09 08:12:50 -07001191 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -08001192
Richard Henderson568ae7e2017-12-07 12:44:09 -08001193 decode_scope = 'static '
1194
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001195 long_opts = ['decode=', 'translate=', 'output=', 'insnwidth=',
Richard Henderson17560e92019-01-30 18:01:29 -08001196 'static-decode=', 'varinsnwidth=']
Richard Henderson568ae7e2017-12-07 12:44:09 -08001197 try:
Richard Henderson17560e92019-01-30 18:01:29 -08001198 (opts, args) = getopt.getopt(sys.argv[1:], 'o:vw:', long_opts)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001199 except getopt.GetoptError as err:
1200 error(0, err)
1201 for o, a in opts:
1202 if o in ('-o', '--output'):
1203 output_file = a
1204 elif o == '--decode':
1205 decode_function = a
1206 decode_scope = ''
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001207 elif o == '--static-decode':
1208 decode_function = a
Richard Henderson568ae7e2017-12-07 12:44:09 -08001209 elif o == '--translate':
1210 translate_prefix = a
1211 translate_scope = ''
Richard Henderson17560e92019-01-30 18:01:29 -08001212 elif o in ('-w', '--insnwidth', '--varinsnwidth'):
1213 if o == '--varinsnwidth':
1214 variablewidth = True
Richard Henderson568ae7e2017-12-07 12:44:09 -08001215 insnwidth = int(a)
1216 if insnwidth == 16:
1217 insntype = 'uint16_t'
1218 insnmask = 0xffff
1219 elif insnwidth != 32:
1220 error(0, 'cannot handle insns of width', insnwidth)
1221 else:
1222 assert False, 'unhandled option'
1223
1224 if len(args) < 1:
1225 error(0, 'missing input file')
Richard Henderson6699ae62018-10-26 14:59:43 +01001226 for filename in args:
1227 input_file = filename
1228 f = open(filename, 'r')
1229 parse_file(f)
1230 f.close()
Richard Henderson568ae7e2017-12-07 12:44:09 -08001231
Richard Henderson70e07112019-01-31 11:34:11 -08001232 if variablewidth:
1233 stree = build_size_tree(patterns, 8, 0, 0)
1234 prop_size(stree)
1235
1236 dtree = build_tree(patterns, 0, 0)
1237 prop_format(dtree)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001238
1239 if output_file:
1240 output_fd = open(output_file, 'w')
1241 else:
1242 output_fd = sys.stdout
1243
1244 output_autogen()
1245 for n in sorted(arguments.keys()):
1246 f = arguments[n]
1247 f.output_def()
1248
1249 # A single translate function can be invoked for different patterns.
1250 # Make sure that the argument sets are the same, and declare the
1251 # function only once.
Richard Hendersonc6920792019-08-09 08:12:50 -07001252 #
1253 # If we're sharing formats, we're likely also sharing trans_* functions,
1254 # but we can't tell which ones. Prevent issues from the compiler by
1255 # suppressing redundant declaration warnings.
1256 if anyextern:
1257 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1258 "# pragma GCC diagnostic push\n",
1259 "# pragma GCC diagnostic ignored \"-Wredundant-decls\"\n",
1260 "# ifdef __clang__\n"
1261 "# pragma GCC diagnostic ignored \"-Wtypedef-redefinition\"\n",
1262 "# endif\n",
1263 "#endif\n\n")
1264
Richard Henderson568ae7e2017-12-07 12:44:09 -08001265 out_pats = {}
Richard Henderson0eff2df2019-02-23 11:35:36 -08001266 for i in allpatterns:
Richard Henderson568ae7e2017-12-07 12:44:09 -08001267 if i.name in out_pats:
1268 p = out_pats[i.name]
1269 if i.base.base != p.base.base:
1270 error(0, i.name, ' has conflicting argument sets')
1271 else:
1272 i.output_decl()
1273 out_pats[i.name] = i
1274 output('\n')
1275
Richard Hendersonc6920792019-08-09 08:12:50 -07001276 if anyextern:
1277 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1278 "# pragma GCC diagnostic pop\n",
1279 "#endif\n\n")
1280
Richard Henderson568ae7e2017-12-07 12:44:09 -08001281 for n in sorted(formats.keys()):
1282 f = formats[n]
1283 f.output_extract()
1284
1285 output(decode_scope, 'bool ', decode_function,
1286 '(DisasContext *ctx, ', insntype, ' insn)\n{\n')
1287
1288 i4 = str_indent(4)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001289
Richard Henderson82bfac12019-02-27 21:37:32 -08001290 if len(allpatterns) != 0:
1291 output(i4, 'union {\n')
1292 for n in sorted(arguments.keys()):
1293 f = arguments[n]
1294 output(i4, i4, f.struct_name(), ' f_', f.name, ';\n')
1295 output(i4, '} u;\n\n')
Richard Henderson70e07112019-01-31 11:34:11 -08001296 dtree.output_code(4, False, 0, 0)
Richard Henderson82bfac12019-02-27 21:37:32 -08001297
Richard Hendersoneb6b87f2019-02-23 08:57:46 -08001298 output(i4, 'return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001299 output('}\n')
1300
Richard Henderson70e07112019-01-31 11:34:11 -08001301 if variablewidth:
1302 output('\n', decode_scope, insntype, ' ', decode_function,
1303 '_load(DisasContext *ctx)\n{\n',
1304 ' ', insntype, ' insn = 0;\n\n')
1305 stree.output_code(4, 0, 0, 0)
1306 output('}\n')
1307
Richard Henderson568ae7e2017-12-07 12:44:09 -08001308 if output_file:
1309 output_fd.close()
1310# end main
1311
1312
1313if __name__ == '__main__':
1314 main()