blob: ea313bcdeaf920f754232f74c0f697f7457f7dfb [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 Hendersondf630442020-05-16 11:19:45 -0700374class MultiPattern(General):
375 """Class representing a set of instruction patterns"""
376
377 def __init__(self, lineno, pats):
378 self.file = input_file
379 self.lineno = lineno
380 self.pats = pats
381 self.base = None
382 self.fixedbits = 0
383 self.fixedmask = 0
384 self.undefmask = 0
385 self.width = None
386
387 def __str__(self):
388 r = 'group'
389 if self.fixedbits is not None:
390 r += ' ' + str_match_bits(self.fixedbits, self.fixedmask)
391 return r
392
393 def output_decl(self):
394 for p in self.pats:
395 p.output_decl()
396# end MultiPattern
397
398
399class IncMultiPattern(MultiPattern):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800400 """Class representing an overlapping set of instruction patterns"""
401
Richard Henderson17560e92019-01-30 18:01:29 -0800402 def __init__(self, lineno, pats, fixb, fixm, udfm, w):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800403 self.file = input_file
404 self.lineno = lineno
405 self.pats = pats
406 self.base = None
407 self.fixedbits = fixb
408 self.fixedmask = fixm
409 self.undefmask = udfm
Richard Henderson17560e92019-01-30 18:01:29 -0800410 self.width = w
Richard Henderson0eff2df2019-02-23 11:35:36 -0800411
Richard Henderson0eff2df2019-02-23 11:35:36 -0800412 def output_code(self, i, extracted, outerbits, outermask):
413 global translate_prefix
414 ind = str_indent(i)
415 for p in self.pats:
416 if outermask != p.fixedmask:
417 innermask = p.fixedmask & ~outermask
418 innerbits = p.fixedbits & ~outermask
419 output(ind, 'if ((insn & ',
420 '0x{0:08x}) == 0x{1:08x}'.format(innermask, innerbits),
421 ') {\n')
422 output(ind, ' /* ',
423 str_match_bits(p.fixedbits, p.fixedmask), ' */\n')
424 p.output_code(i + 4, extracted, p.fixedbits, p.fixedmask)
425 output(ind, '}\n')
426 else:
427 p.output_code(i, extracted, p.fixedbits, p.fixedmask)
Richard Henderson040145c2020-05-16 10:50:43 -0700428#end IncMultiPattern
Richard Henderson0eff2df2019-02-23 11:35:36 -0800429
430
Richard Henderson568ae7e2017-12-07 12:44:09 -0800431def parse_field(lineno, name, toks):
432 """Parse one instruction field from TOKS at LINENO"""
433 global fields
434 global re_ident
435 global insnwidth
436
437 # A "simple" field will have only one entry;
438 # a "multifield" will have several.
439 subs = []
440 width = 0
441 func = None
442 for t in toks:
John Snow2d110c12020-05-13 23:52:30 -0400443 if re.fullmatch('!function=' + re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800444 if func:
445 error(lineno, 'duplicate function')
446 func = t.split('=')
447 func = func[1]
448 continue
449
John Snow2d110c12020-05-13 23:52:30 -0400450 if re.fullmatch('[0-9]+:s[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800451 # Signed field extract
452 subtoks = t.split(':s')
453 sign = True
John Snow2d110c12020-05-13 23:52:30 -0400454 elif re.fullmatch('[0-9]+:[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800455 # Unsigned field extract
456 subtoks = t.split(':')
457 sign = False
458 else:
459 error(lineno, 'invalid field token "{0}"'.format(t))
460 po = int(subtoks[0])
461 le = int(subtoks[1])
462 if po + le > insnwidth:
463 error(lineno, 'field {0} too large'.format(t))
464 f = Field(sign, po, le)
465 subs.append(f)
466 width += le
467
468 if width > insnwidth:
469 error(lineno, 'field too large')
Richard Henderson94597b62019-07-22 17:02:56 -0700470 if len(subs) == 0:
471 if func:
472 f = ParameterField(func)
473 else:
474 error(lineno, 'field with no value')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800475 else:
Richard Henderson94597b62019-07-22 17:02:56 -0700476 if len(subs) == 1:
477 f = subs[0]
478 else:
479 mask = 0
480 for s in subs:
481 if mask & s.mask:
482 error(lineno, 'field components overlap')
483 mask |= s.mask
484 f = MultiField(subs, mask)
485 if func:
486 f = FunctionField(func, f)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800487
488 if name in fields:
489 error(lineno, 'duplicate field', name)
490 fields[name] = f
491# end parse_field
492
493
494def parse_arguments(lineno, name, toks):
495 """Parse one argument set from TOKS at LINENO"""
496 global arguments
497 global re_ident
Richard Hendersonc6920792019-08-09 08:12:50 -0700498 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800499
500 flds = []
Richard Hendersonabd04f92018-10-23 10:26:25 +0100501 extern = False
Richard Henderson568ae7e2017-12-07 12:44:09 -0800502 for t in toks:
John Snow2d110c12020-05-13 23:52:30 -0400503 if re.fullmatch('!extern', t):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100504 extern = True
Richard Hendersonc6920792019-08-09 08:12:50 -0700505 anyextern = True
Richard Hendersonabd04f92018-10-23 10:26:25 +0100506 continue
John Snow2d110c12020-05-13 23:52:30 -0400507 if not re.fullmatch(re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800508 error(lineno, 'invalid argument set token "{0}"'.format(t))
509 if t in flds:
510 error(lineno, 'duplicate argument "{0}"'.format(t))
511 flds.append(t)
512
513 if name in arguments:
514 error(lineno, 'duplicate argument set', name)
Richard Hendersonabd04f92018-10-23 10:26:25 +0100515 arguments[name] = Arguments(name, flds, extern)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800516# end parse_arguments
517
518
519def lookup_field(lineno, name):
520 global fields
521 if name in fields:
522 return fields[name]
523 error(lineno, 'undefined field', name)
524
525
526def add_field(lineno, flds, new_name, f):
527 if new_name in flds:
528 error(lineno, 'duplicate field', new_name)
529 flds[new_name] = f
530 return flds
531
532
533def add_field_byname(lineno, flds, new_name, old_name):
534 return add_field(lineno, flds, new_name, lookup_field(lineno, old_name))
535
536
537def infer_argument_set(flds):
538 global arguments
Richard Hendersonabd04f92018-10-23 10:26:25 +0100539 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800540
541 for arg in arguments.values():
542 if eq_fields_for_args(flds, arg.fields):
543 return arg
544
Richard Hendersonabd04f92018-10-23 10:26:25 +0100545 name = decode_function + str(len(arguments))
546 arg = Arguments(name, flds.keys(), False)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800547 arguments[name] = arg
548 return arg
549
550
Richard Henderson17560e92019-01-30 18:01:29 -0800551def infer_format(arg, fieldmask, flds, width):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800552 global arguments
553 global formats
Richard Hendersonabd04f92018-10-23 10:26:25 +0100554 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800555
556 const_flds = {}
557 var_flds = {}
558 for n, c in flds.items():
559 if c is ConstField:
560 const_flds[n] = c
561 else:
562 var_flds[n] = c
563
564 # Look for an existing format with the same argument set and fields
565 for fmt in formats.values():
566 if arg and fmt.base != arg:
567 continue
568 if fieldmask != fmt.fieldmask:
569 continue
Richard Henderson17560e92019-01-30 18:01:29 -0800570 if width != fmt.width:
571 continue
Richard Henderson568ae7e2017-12-07 12:44:09 -0800572 if not eq_fields_for_fmts(flds, fmt.fields):
573 continue
574 return (fmt, const_flds)
575
Richard Hendersonabd04f92018-10-23 10:26:25 +0100576 name = decode_function + '_Fmt_' + str(len(formats))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800577 if not arg:
578 arg = infer_argument_set(flds)
579
Richard Henderson17560e92019-01-30 18:01:29 -0800580 fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800581 formats[name] = fmt
582
583 return (fmt, const_flds)
584# end infer_format
585
586
587def parse_generic(lineno, is_format, name, toks):
588 """Parse one instruction format from TOKS at LINENO"""
589 global fields
590 global arguments
591 global formats
592 global patterns
Richard Henderson0eff2df2019-02-23 11:35:36 -0800593 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -0800594 global re_ident
595 global insnwidth
596 global insnmask
Richard Henderson17560e92019-01-30 18:01:29 -0800597 global variablewidth
Richard Henderson568ae7e2017-12-07 12:44:09 -0800598
599 fixedmask = 0
600 fixedbits = 0
601 undefmask = 0
602 width = 0
603 flds = {}
604 arg = None
605 fmt = None
606 for t in toks:
607 # '&Foo' gives a format an explcit argument set.
608 if t[0] == '&':
609 tt = t[1:]
610 if arg:
611 error(lineno, 'multiple argument sets')
612 if tt in arguments:
613 arg = arguments[tt]
614 else:
615 error(lineno, 'undefined argument set', t)
616 continue
617
618 # '@Foo' gives a pattern an explicit format.
619 if t[0] == '@':
620 tt = t[1:]
621 if fmt:
622 error(lineno, 'multiple formats')
623 if tt in formats:
624 fmt = formats[tt]
625 else:
626 error(lineno, 'undefined format', t)
627 continue
628
629 # '%Foo' imports a field.
630 if t[0] == '%':
631 tt = t[1:]
632 flds = add_field_byname(lineno, flds, tt, tt)
633 continue
634
635 # 'Foo=%Bar' imports a field with a different name.
John Snow2d110c12020-05-13 23:52:30 -0400636 if re.fullmatch(re_ident + '=%' + re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800637 (fname, iname) = t.split('=%')
638 flds = add_field_byname(lineno, flds, fname, iname)
639 continue
640
641 # 'Foo=number' sets an argument field to a constant value
John Snow2d110c12020-05-13 23:52:30 -0400642 if re.fullmatch(re_ident + '=[+-]?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800643 (fname, value) = t.split('=')
644 value = int(value)
645 flds = add_field(lineno, flds, fname, ConstField(value))
646 continue
647
648 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
649 # required ones, or dont-cares.
John Snow2d110c12020-05-13 23:52:30 -0400650 if re.fullmatch('[01.-]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800651 shift = len(t)
652 fms = t.replace('0', '1')
653 fms = fms.replace('.', '0')
654 fms = fms.replace('-', '0')
655 fbs = t.replace('.', '0')
656 fbs = fbs.replace('-', '0')
657 ubm = t.replace('1', '0')
658 ubm = ubm.replace('.', '0')
659 ubm = ubm.replace('-', '1')
660 fms = int(fms, 2)
661 fbs = int(fbs, 2)
662 ubm = int(ubm, 2)
663 fixedbits = (fixedbits << shift) | fbs
664 fixedmask = (fixedmask << shift) | fms
665 undefmask = (undefmask << shift) | ubm
666 # Otherwise, fieldname:fieldwidth
John Snow2d110c12020-05-13 23:52:30 -0400667 elif re.fullmatch(re_ident + ':s?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800668 (fname, flen) = t.split(':')
669 sign = False
670 if flen[0] == 's':
671 sign = True
672 flen = flen[1:]
673 shift = int(flen, 10)
Richard Henderson2decfc92019-03-05 15:34:41 -0800674 if shift + width > insnwidth:
675 error(lineno, 'field {0} exceeds insnwidth'.format(fname))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800676 f = Field(sign, insnwidth - width - shift, shift)
677 flds = add_field(lineno, flds, fname, f)
678 fixedbits <<= shift
679 fixedmask <<= shift
680 undefmask <<= shift
681 else:
682 error(lineno, 'invalid token "{0}"'.format(t))
683 width += shift
684
Richard Henderson17560e92019-01-30 18:01:29 -0800685 if variablewidth and width < insnwidth and width % 8 == 0:
686 shift = insnwidth - width
687 fixedbits <<= shift
688 fixedmask <<= shift
689 undefmask <<= shift
690 undefmask |= (1 << shift) - 1
691
Richard Henderson568ae7e2017-12-07 12:44:09 -0800692 # We should have filled in all of the bits of the instruction.
Richard Henderson17560e92019-01-30 18:01:29 -0800693 elif not (is_format and width == 0) and width != insnwidth:
Richard Henderson568ae7e2017-12-07 12:44:09 -0800694 error(lineno, 'definition has {0} bits'.format(width))
695
696 # Do not check for fields overlaping fields; one valid usage
697 # is to be able to duplicate fields via import.
698 fieldmask = 0
699 for f in flds.values():
700 fieldmask |= f.mask
701
702 # Fix up what we've parsed to match either a format or a pattern.
703 if is_format:
704 # Formats cannot reference formats.
705 if fmt:
706 error(lineno, 'format referencing format')
707 # If an argument set is given, then there should be no fields
708 # without a place to store it.
709 if arg:
710 for f in flds.keys():
711 if f not in arg.fields:
712 error(lineno, 'field {0} not in argument set {1}'
713 .format(f, arg.name))
714 else:
715 arg = infer_argument_set(flds)
716 if name in formats:
717 error(lineno, 'duplicate format name', name)
718 fmt = Format(name, lineno, arg, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800719 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800720 formats[name] = fmt
721 else:
722 # Patterns can reference a format ...
723 if fmt:
724 # ... but not an argument simultaneously
725 if arg:
726 error(lineno, 'pattern specifies both format and argument set')
727 if fixedmask & fmt.fixedmask:
728 error(lineno, 'pattern fixed bits overlap format fixed bits')
Richard Henderson17560e92019-01-30 18:01:29 -0800729 if width != fmt.width:
730 error(lineno, 'pattern uses format of different width')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800731 fieldmask |= fmt.fieldmask
732 fixedbits |= fmt.fixedbits
733 fixedmask |= fmt.fixedmask
734 undefmask |= fmt.undefmask
735 else:
Richard Henderson17560e92019-01-30 18:01:29 -0800736 (fmt, flds) = infer_format(arg, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800737 arg = fmt.base
738 for f in flds.keys():
739 if f not in arg.fields:
740 error(lineno, 'field {0} not in argument set {1}'
741 .format(f, arg.name))
742 if f in fmt.fields.keys():
743 error(lineno, 'field {0} set by format and pattern'.format(f))
744 for f in arg.fields:
745 if f not in flds.keys() and f not in fmt.fields.keys():
746 error(lineno, 'field {0} not initialized'.format(f))
747 pat = Pattern(name, lineno, fmt, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800748 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800749 patterns.append(pat)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800750 allpatterns.append(pat)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800751
752 # Validate the masks that we have assembled.
753 if fieldmask & fixedmask:
754 error(lineno, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
755 .format(fieldmask, fixedmask))
756 if fieldmask & undefmask:
757 error(lineno, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
758 .format(fieldmask, undefmask))
759 if fixedmask & undefmask:
760 error(lineno, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
761 .format(fixedmask, undefmask))
762 if not is_format:
763 allbits = fieldmask | fixedmask | undefmask
764 if allbits != insnmask:
765 error(lineno, 'bits left unspecified (0x{0:08x})'
766 .format(allbits ^ insnmask))
767# end parse_general
768
Richard Henderson040145c2020-05-16 10:50:43 -0700769def build_incmulti_pattern(lineno, pats):
770 """Validate the Patterns going into a IncMultiPattern."""
Richard Henderson0eff2df2019-02-23 11:35:36 -0800771 global patterns
772 global insnmask
773
774 if len(pats) < 2:
775 error(lineno, 'less than two patterns within braces')
776
777 fixedmask = insnmask
778 undefmask = insnmask
779
780 # Collect fixed/undefmask for all of the children.
781 # Move the defining lineno back to that of the first child.
782 for p in pats:
783 fixedmask &= p.fixedmask
784 undefmask &= p.undefmask
785 if p.lineno < lineno:
786 lineno = p.lineno
787
Richard Henderson17560e92019-01-30 18:01:29 -0800788 width = None
789 for p in pats:
790 if width is None:
791 width = p.width
792 elif width != p.width:
793 error(lineno, 'width mismatch in patterns within braces')
794
Richard Henderson0eff2df2019-02-23 11:35:36 -0800795 repeat = True
796 while repeat:
797 if fixedmask == 0:
798 error(lineno, 'no overlap in patterns within braces')
799 fixedbits = None
800 for p in pats:
801 thisbits = p.fixedbits & fixedmask
802 if fixedbits is None:
803 fixedbits = thisbits
804 elif fixedbits != thisbits:
805 fixedmask &= ~(fixedbits ^ thisbits)
806 break
807 else:
808 repeat = False
809
Richard Henderson040145c2020-05-16 10:50:43 -0700810 mp = IncMultiPattern(lineno, pats, fixedbits, fixedmask, undefmask, width)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800811 patterns.append(mp)
Richard Henderson040145c2020-05-16 10:50:43 -0700812# end build_incmulti_pattern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800813
814def parse_file(f):
815 """Parse all of the patterns within a file"""
816
Richard Henderson0eff2df2019-02-23 11:35:36 -0800817 global patterns
818
Richard Henderson568ae7e2017-12-07 12:44:09 -0800819 # Read all of the lines of the file. Concatenate lines
820 # ending in backslash; discard empty lines and comments.
821 toks = []
822 lineno = 0
Richard Henderson0eff2df2019-02-23 11:35:36 -0800823 nesting = 0
824 saved_pats = []
825
Richard Henderson568ae7e2017-12-07 12:44:09 -0800826 for line in f:
827 lineno += 1
828
Richard Henderson0eff2df2019-02-23 11:35:36 -0800829 # Expand and strip spaces, to find indent.
830 line = line.rstrip()
831 line = line.expandtabs()
832 len1 = len(line)
833 line = line.lstrip()
834 len2 = len(line)
835
Richard Henderson568ae7e2017-12-07 12:44:09 -0800836 # Discard comments
837 end = line.find('#')
838 if end >= 0:
839 line = line[:end]
840
841 t = line.split()
842 if len(toks) != 0:
843 # Next line after continuation
844 toks.extend(t)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800845 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800846 # Allow completely blank lines.
847 if len1 == 0:
848 continue
849 indent = len1 - len2
850 # Empty line due to comment.
851 if len(t) == 0:
852 # Indentation must be correct, even for comment lines.
853 if indent != nesting:
854 error(lineno, 'indentation ', indent, ' != ', nesting)
855 continue
856 start_lineno = lineno
Richard Henderson568ae7e2017-12-07 12:44:09 -0800857 toks = t
858
859 # Continuation?
860 if toks[-1] == '\\':
861 toks.pop()
862 continue
863
Richard Henderson568ae7e2017-12-07 12:44:09 -0800864 name = toks[0]
865 del toks[0]
866
Richard Henderson0eff2df2019-02-23 11:35:36 -0800867 # End nesting?
868 if name == '}':
869 if nesting == 0:
870 error(start_lineno, 'mismatched close brace')
871 if len(toks) != 0:
872 error(start_lineno, 'extra tokens after close brace')
873 nesting -= 2
874 if indent != nesting:
875 error(start_lineno, 'indentation ', indent, ' != ', nesting)
876 pats = patterns
877 patterns = saved_pats.pop()
Richard Henderson040145c2020-05-16 10:50:43 -0700878 build_incmulti_pattern(lineno, pats)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800879 toks = []
880 continue
881
882 # Everything else should have current indentation.
883 if indent != nesting:
884 error(start_lineno, 'indentation ', indent, ' != ', nesting)
885
886 # Start nesting?
887 if name == '{':
888 if len(toks) != 0:
889 error(start_lineno, 'extra tokens after open brace')
890 saved_pats.append(patterns)
891 patterns = []
892 nesting += 2
893 toks = []
894 continue
895
Richard Henderson568ae7e2017-12-07 12:44:09 -0800896 # Determine the type of object needing to be parsed.
897 if name[0] == '%':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800898 parse_field(start_lineno, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800899 elif name[0] == '&':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800900 parse_arguments(start_lineno, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800901 elif name[0] == '@':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800902 parse_generic(start_lineno, True, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800903 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800904 parse_generic(start_lineno, False, name, toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800905 toks = []
906# end parse_file
907
908
909class Tree:
910 """Class representing a node in a decode tree"""
911
912 def __init__(self, fm, tm):
913 self.fixedmask = fm
914 self.thismask = tm
915 self.subs = []
916 self.base = None
917
918 def str1(self, i):
919 ind = str_indent(i)
920 r = '{0}{1:08x}'.format(ind, self.fixedmask)
921 if self.format:
922 r += ' ' + self.format.name
923 r += ' [\n'
924 for (b, s) in self.subs:
925 r += '{0} {1:08x}:\n'.format(ind, b)
926 r += s.str1(i + 4) + '\n'
927 r += ind + ']'
928 return r
929
930 def __str__(self):
931 return self.str1(0)
932
933 def output_code(self, i, extracted, outerbits, outermask):
934 ind = str_indent(i)
935
936 # If we identified all nodes below have the same format,
937 # extract the fields now.
938 if not extracted and self.base:
939 output(ind, self.base.extract_name(),
Richard Henderson451e4ff2019-03-20 19:21:31 -0700940 '(ctx, &u.f_', self.base.base.name, ', insn);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800941 extracted = True
942
943 # Attempt to aid the compiler in producing compact switch statements.
944 # If the bits in the mask are contiguous, extract them.
945 sh = is_contiguous(self.thismask)
946 if sh > 0:
947 # Propagate SH down into the local functions.
948 def str_switch(b, sh=sh):
949 return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh)
950
951 def str_case(b, sh=sh):
952 return '0x{0:x}'.format(b >> sh)
953 else:
954 def str_switch(b):
955 return 'insn & 0x{0:08x}'.format(b)
956
957 def str_case(b):
958 return '0x{0:08x}'.format(b)
959
960 output(ind, 'switch (', str_switch(self.thismask), ') {\n')
961 for b, s in sorted(self.subs):
962 assert (self.thismask & ~s.fixedmask) == 0
963 innermask = outermask | self.thismask
964 innerbits = outerbits | b
965 output(ind, 'case ', str_case(b), ':\n')
966 output(ind, ' /* ',
967 str_match_bits(innerbits, innermask), ' */\n')
968 s.output_code(i + 4, extracted, innerbits, innermask)
Richard Hendersoneb6b87f2019-02-23 08:57:46 -0800969 output(ind, ' return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800970 output(ind, '}\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800971# end Tree
972
973
974def build_tree(pats, outerbits, outermask):
975 # Find the intersection of all remaining fixedmask.
Philippe Mathieu-Daudé9b3186e2018-12-16 20:07:38 -0800976 innermask = ~outermask & insnmask
Richard Henderson568ae7e2017-12-07 12:44:09 -0800977 for i in pats:
978 innermask &= i.fixedmask
979
980 if innermask == 0:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800981 text = 'overlapping patterns:'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800982 for p in pats:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800983 text += '\n' + p.file + ':' + str(p.lineno) + ': ' + str(p)
984 error_with_file(pats[0].file, pats[0].lineno, text)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800985
986 fullmask = outermask | innermask
987
988 # Sort each element of pats into the bin selected by the mask.
989 bins = {}
990 for i in pats:
991 fb = i.fixedbits & innermask
992 if fb in bins:
993 bins[fb].append(i)
994 else:
995 bins[fb] = [i]
996
997 # We must recurse if any bin has more than one element or if
998 # the single element in the bin has not been fully matched.
999 t = Tree(fullmask, innermask)
1000
1001 for b, l in bins.items():
1002 s = l[0]
1003 if len(l) > 1 or s.fixedmask & ~fullmask != 0:
1004 s = build_tree(l, b | outerbits, fullmask)
1005 t.subs.append((b, s))
1006
1007 return t
1008# end build_tree
1009
1010
Richard Henderson70e07112019-01-31 11:34:11 -08001011class SizeTree:
1012 """Class representing a node in a size decode tree"""
1013
1014 def __init__(self, m, w):
1015 self.mask = m
1016 self.subs = []
1017 self.base = None
1018 self.width = w
1019
1020 def str1(self, i):
1021 ind = str_indent(i)
1022 r = '{0}{1:08x}'.format(ind, self.mask)
1023 r += ' [\n'
1024 for (b, s) in self.subs:
1025 r += '{0} {1:08x}:\n'.format(ind, b)
1026 r += s.str1(i + 4) + '\n'
1027 r += ind + ']'
1028 return r
1029
1030 def __str__(self):
1031 return self.str1(0)
1032
1033 def output_code(self, i, extracted, outerbits, outermask):
1034 ind = str_indent(i)
1035
1036 # If we need to load more bytes to test, do so now.
1037 if extracted < self.width:
1038 output(ind, 'insn = ', decode_function,
1039 '_load_bytes(ctx, insn, {0}, {1});\n'
Philippe Mathieu-Daudéb4123782020-03-30 14:13:45 +02001040 .format(extracted // 8, self.width // 8));
Richard Henderson70e07112019-01-31 11:34:11 -08001041 extracted = self.width
1042
1043 # Attempt to aid the compiler in producing compact switch statements.
1044 # If the bits in the mask are contiguous, extract them.
1045 sh = is_contiguous(self.mask)
1046 if sh > 0:
1047 # Propagate SH down into the local functions.
1048 def str_switch(b, sh=sh):
1049 return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh)
1050
1051 def str_case(b, sh=sh):
1052 return '0x{0:x}'.format(b >> sh)
1053 else:
1054 def str_switch(b):
1055 return 'insn & 0x{0:08x}'.format(b)
1056
1057 def str_case(b):
1058 return '0x{0:08x}'.format(b)
1059
1060 output(ind, 'switch (', str_switch(self.mask), ') {\n')
1061 for b, s in sorted(self.subs):
1062 innermask = outermask | self.mask
1063 innerbits = outerbits | b
1064 output(ind, 'case ', str_case(b), ':\n')
1065 output(ind, ' /* ',
1066 str_match_bits(innerbits, innermask), ' */\n')
1067 s.output_code(i + 4, extracted, innerbits, innermask)
1068 output(ind, '}\n')
1069 output(ind, 'return insn;\n')
1070# end SizeTree
1071
1072class SizeLeaf:
1073 """Class representing a leaf node in a size decode tree"""
1074
1075 def __init__(self, m, w):
1076 self.mask = m
1077 self.width = w
1078
1079 def str1(self, i):
1080 ind = str_indent(i)
1081 return '{0}{1:08x}'.format(ind, self.mask)
1082
1083 def __str__(self):
1084 return self.str1(0)
1085
1086 def output_code(self, i, extracted, outerbits, outermask):
1087 global decode_function
1088 ind = str_indent(i)
1089
1090 # If we need to load more bytes, do so now.
1091 if extracted < self.width:
1092 output(ind, 'insn = ', decode_function,
1093 '_load_bytes(ctx, insn, {0}, {1});\n'
Philippe Mathieu-Daudéb4123782020-03-30 14:13:45 +02001094 .format(extracted // 8, self.width // 8));
Richard Henderson70e07112019-01-31 11:34:11 -08001095 extracted = self.width
1096 output(ind, 'return insn;\n')
1097# end SizeLeaf
1098
1099
1100def build_size_tree(pats, width, outerbits, outermask):
1101 global insnwidth
1102
1103 # Collect the mask of bits that are fixed in this width
1104 innermask = 0xff << (insnwidth - width)
1105 innermask &= ~outermask
1106 minwidth = None
1107 onewidth = True
1108 for i in pats:
1109 innermask &= i.fixedmask
1110 if minwidth is None:
1111 minwidth = i.width
1112 elif minwidth != i.width:
1113 onewidth = False;
1114 if minwidth < i.width:
1115 minwidth = i.width
1116
1117 if onewidth:
1118 return SizeLeaf(innermask, minwidth)
1119
1120 if innermask == 0:
1121 if width < minwidth:
1122 return build_size_tree(pats, width + 8, outerbits, outermask)
1123
1124 pnames = []
1125 for p in pats:
1126 pnames.append(p.name + ':' + p.file + ':' + str(p.lineno))
1127 error_with_file(pats[0].file, pats[0].lineno,
1128 'overlapping patterns size {0}:'.format(width), pnames)
1129
1130 bins = {}
1131 for i in pats:
1132 fb = i.fixedbits & innermask
1133 if fb in bins:
1134 bins[fb].append(i)
1135 else:
1136 bins[fb] = [i]
1137
1138 fullmask = outermask | innermask
1139 lens = sorted(bins.keys())
1140 if len(lens) == 1:
1141 b = lens[0]
1142 return build_size_tree(bins[b], width + 8, b | outerbits, fullmask)
1143
1144 r = SizeTree(innermask, width)
1145 for b, l in bins.items():
1146 s = build_size_tree(l, width, b | outerbits, fullmask)
1147 r.subs.append((b, s))
1148 return r
1149# end build_size_tree
1150
1151
Richard Henderson568ae7e2017-12-07 12:44:09 -08001152def prop_format(tree):
1153 """Propagate Format objects into the decode tree"""
1154
1155 # Depth first search.
1156 for (b, s) in tree.subs:
1157 if isinstance(s, Tree):
1158 prop_format(s)
1159
1160 # If all entries in SUBS have the same format, then
1161 # propagate that into the tree.
1162 f = None
1163 for (b, s) in tree.subs:
1164 if f is None:
1165 f = s.base
1166 if f is None:
1167 return
1168 if f is not s.base:
1169 return
1170 tree.base = f
1171# end prop_format
1172
1173
Richard Henderson70e07112019-01-31 11:34:11 -08001174def prop_size(tree):
1175 """Propagate minimum widths up the decode size tree"""
1176
1177 if isinstance(tree, SizeTree):
1178 min = None
1179 for (b, s) in tree.subs:
1180 width = prop_size(s)
1181 if min is None or min > width:
1182 min = width
1183 assert min >= tree.width
1184 tree.width = min
1185 else:
1186 min = tree.width
1187 return min
1188# end prop_size
1189
1190
Richard Henderson568ae7e2017-12-07 12:44:09 -08001191def main():
1192 global arguments
1193 global formats
1194 global patterns
Richard Henderson0eff2df2019-02-23 11:35:36 -08001195 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -08001196 global translate_scope
1197 global translate_prefix
1198 global output_fd
1199 global output_file
1200 global input_file
1201 global insnwidth
1202 global insntype
Bastian Koppelmann83d7c402018-03-19 12:58:46 +01001203 global insnmask
Richard Hendersonabd04f92018-10-23 10:26:25 +01001204 global decode_function
Richard Henderson17560e92019-01-30 18:01:29 -08001205 global variablewidth
Richard Hendersonc6920792019-08-09 08:12:50 -07001206 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -08001207
Richard Henderson568ae7e2017-12-07 12:44:09 -08001208 decode_scope = 'static '
1209
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001210 long_opts = ['decode=', 'translate=', 'output=', 'insnwidth=',
Richard Henderson17560e92019-01-30 18:01:29 -08001211 'static-decode=', 'varinsnwidth=']
Richard Henderson568ae7e2017-12-07 12:44:09 -08001212 try:
Richard Henderson17560e92019-01-30 18:01:29 -08001213 (opts, args) = getopt.getopt(sys.argv[1:], 'o:vw:', long_opts)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001214 except getopt.GetoptError as err:
1215 error(0, err)
1216 for o, a in opts:
1217 if o in ('-o', '--output'):
1218 output_file = a
1219 elif o == '--decode':
1220 decode_function = a
1221 decode_scope = ''
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001222 elif o == '--static-decode':
1223 decode_function = a
Richard Henderson568ae7e2017-12-07 12:44:09 -08001224 elif o == '--translate':
1225 translate_prefix = a
1226 translate_scope = ''
Richard Henderson17560e92019-01-30 18:01:29 -08001227 elif o in ('-w', '--insnwidth', '--varinsnwidth'):
1228 if o == '--varinsnwidth':
1229 variablewidth = True
Richard Henderson568ae7e2017-12-07 12:44:09 -08001230 insnwidth = int(a)
1231 if insnwidth == 16:
1232 insntype = 'uint16_t'
1233 insnmask = 0xffff
1234 elif insnwidth != 32:
1235 error(0, 'cannot handle insns of width', insnwidth)
1236 else:
1237 assert False, 'unhandled option'
1238
1239 if len(args) < 1:
1240 error(0, 'missing input file')
Richard Henderson6699ae62018-10-26 14:59:43 +01001241 for filename in args:
1242 input_file = filename
1243 f = open(filename, 'r')
1244 parse_file(f)
1245 f.close()
Richard Henderson568ae7e2017-12-07 12:44:09 -08001246
Richard Henderson70e07112019-01-31 11:34:11 -08001247 if variablewidth:
1248 stree = build_size_tree(patterns, 8, 0, 0)
1249 prop_size(stree)
1250
1251 dtree = build_tree(patterns, 0, 0)
1252 prop_format(dtree)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001253
1254 if output_file:
1255 output_fd = open(output_file, 'w')
1256 else:
1257 output_fd = sys.stdout
1258
1259 output_autogen()
1260 for n in sorted(arguments.keys()):
1261 f = arguments[n]
1262 f.output_def()
1263
1264 # A single translate function can be invoked for different patterns.
1265 # Make sure that the argument sets are the same, and declare the
1266 # function only once.
Richard Hendersonc6920792019-08-09 08:12:50 -07001267 #
1268 # If we're sharing formats, we're likely also sharing trans_* functions,
1269 # but we can't tell which ones. Prevent issues from the compiler by
1270 # suppressing redundant declaration warnings.
1271 if anyextern:
1272 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1273 "# pragma GCC diagnostic push\n",
1274 "# pragma GCC diagnostic ignored \"-Wredundant-decls\"\n",
1275 "# ifdef __clang__\n"
1276 "# pragma GCC diagnostic ignored \"-Wtypedef-redefinition\"\n",
1277 "# endif\n",
1278 "#endif\n\n")
1279
Richard Henderson568ae7e2017-12-07 12:44:09 -08001280 out_pats = {}
Richard Henderson0eff2df2019-02-23 11:35:36 -08001281 for i in allpatterns:
Richard Henderson568ae7e2017-12-07 12:44:09 -08001282 if i.name in out_pats:
1283 p = out_pats[i.name]
1284 if i.base.base != p.base.base:
1285 error(0, i.name, ' has conflicting argument sets')
1286 else:
1287 i.output_decl()
1288 out_pats[i.name] = i
1289 output('\n')
1290
Richard Hendersonc6920792019-08-09 08:12:50 -07001291 if anyextern:
1292 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1293 "# pragma GCC diagnostic pop\n",
1294 "#endif\n\n")
1295
Richard Henderson568ae7e2017-12-07 12:44:09 -08001296 for n in sorted(formats.keys()):
1297 f = formats[n]
1298 f.output_extract()
1299
1300 output(decode_scope, 'bool ', decode_function,
1301 '(DisasContext *ctx, ', insntype, ' insn)\n{\n')
1302
1303 i4 = str_indent(4)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001304
Richard Henderson82bfac12019-02-27 21:37:32 -08001305 if len(allpatterns) != 0:
1306 output(i4, 'union {\n')
1307 for n in sorted(arguments.keys()):
1308 f = arguments[n]
1309 output(i4, i4, f.struct_name(), ' f_', f.name, ';\n')
1310 output(i4, '} u;\n\n')
Richard Henderson70e07112019-01-31 11:34:11 -08001311 dtree.output_code(4, False, 0, 0)
Richard Henderson82bfac12019-02-27 21:37:32 -08001312
Richard Hendersoneb6b87f2019-02-23 08:57:46 -08001313 output(i4, 'return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001314 output('}\n')
1315
Richard Henderson70e07112019-01-31 11:34:11 -08001316 if variablewidth:
1317 output('\n', decode_scope, insntype, ' ', decode_function,
1318 '_load(DisasContext *ctx)\n{\n',
1319 ' ', insntype, ' insn = 0;\n\n')
1320 stree.output_code(4, 0, 0, 0)
1321 output('}\n')
1322
Richard Henderson568ae7e2017-12-07 12:44:09 -08001323 if output_file:
1324 output_fd.close()
1325# end main
1326
1327
1328if __name__ == '__main__':
1329 main()