blob: e2640cc79b9b6fe2a04099c4e2ab1745de5c2dd6 [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
Chetan Pantd6ea4232020-10-23 12:33:53 +00007# version 2.1 of the License, or (at your option) any later version.
Richard Henderson568ae7e2017-12-07 12:44:09 -08008#
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
Philippe Mathieu-Daudé4caceca2021-01-10 01:02:40 +010023import io
Richard Henderson568ae7e2017-12-07 12:44:09 -080024import os
25import re
26import sys
27import getopt
Richard Henderson568ae7e2017-12-07 12:44:09 -080028
29insnwidth = 32
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +000030bitop_width = 32
Richard Henderson568ae7e2017-12-07 12:44:09 -080031insnmask = 0xffffffff
Richard Henderson17560e92019-01-30 18:01:29 -080032variablewidth = False
Richard Henderson568ae7e2017-12-07 12:44:09 -080033fields = {}
34arguments = {}
35formats = {}
Richard Henderson0eff2df2019-02-23 11:35:36 -080036allpatterns = []
Richard Hendersonc6920792019-08-09 08:12:50 -070037anyextern = False
Richard Henderson9b5acc52023-05-25 18:04:05 -070038testforerror = False
Richard Henderson568ae7e2017-12-07 12:44:09 -080039
40translate_prefix = 'trans'
41translate_scope = 'static '
42input_file = ''
43output_file = None
44output_fd = None
45insntype = 'uint32_t'
Richard Hendersonabd04f92018-10-23 10:26:25 +010046decode_function = 'decode'
Richard Henderson568ae7e2017-12-07 12:44:09 -080047
Richard Hendersonacfdd232020-09-03 12:23:34 -070048# An identifier for C.
49re_C_ident = '[a-zA-Z][a-zA-Z0-9_]*'
Richard Henderson568ae7e2017-12-07 12:44:09 -080050
Richard Hendersonacfdd232020-09-03 12:23:34 -070051# Identifiers for Arguments, Fields, Formats and Patterns.
52re_arg_ident = '&[a-zA-Z0-9_]*'
53re_fld_ident = '%[a-zA-Z0-9_]*'
54re_fmt_ident = '@[a-zA-Z0-9_]*'
55re_pat_ident = '[a-zA-Z0-9_]*'
Richard Henderson568ae7e2017-12-07 12:44:09 -080056
Richard Henderson6699ae62018-10-26 14:59:43 +010057def error_with_file(file, lineno, *args):
Richard Henderson568ae7e2017-12-07 12:44:09 -080058 """Print an error message from file:line and args and exit."""
59 global output_file
60 global output_fd
61
Richard Henderson2fd51b12020-05-15 14:48:54 -070062 prefix = ''
63 if file:
Richard Henderson9f6e2b42021-04-28 16:37:02 -070064 prefix += f'{file}:'
Richard Henderson568ae7e2017-12-07 12:44:09 -080065 if lineno:
Richard Henderson9f6e2b42021-04-28 16:37:02 -070066 prefix += f'{lineno}:'
Richard Henderson2fd51b12020-05-15 14:48:54 -070067 if prefix:
68 prefix += ' '
69 print(prefix, end='error: ', file=sys.stderr)
70 print(*args, file=sys.stderr)
71
Richard Henderson568ae7e2017-12-07 12:44:09 -080072 if output_file and output_fd:
73 output_fd.close()
74 os.remove(output_file)
Richard Henderson9b5acc52023-05-25 18:04:05 -070075 exit(0 if testforerror else 1)
Richard Henderson2fd51b12020-05-15 14:48:54 -070076# end error_with_file
77
Richard Henderson568ae7e2017-12-07 12:44:09 -080078
Richard Henderson6699ae62018-10-26 14:59:43 +010079def error(lineno, *args):
Richard Henderson2fd51b12020-05-15 14:48:54 -070080 error_with_file(input_file, lineno, *args)
81# end error
82
Richard Henderson568ae7e2017-12-07 12:44:09 -080083
84def output(*args):
85 global output_fd
86 for a in args:
87 output_fd.write(a)
88
89
Richard Henderson568ae7e2017-12-07 12:44:09 -080090def output_autogen():
91 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
92
93
94def str_indent(c):
95 """Return a string with C spaces"""
96 return ' ' * c
97
98
99def str_fields(fields):
zhaolichang65fdb3c2020-09-17 15:50:23 +0800100 """Return a string uniquely identifying FIELDS"""
Richard Henderson568ae7e2017-12-07 12:44:09 -0800101 r = ''
102 for n in sorted(fields.keys()):
103 r += '_' + n
104 return r[1:]
105
106
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700107def whex(val):
108 """Return a hex string for val padded for insnwidth"""
109 global insnwidth
110 return f'0x{val:0{insnwidth // 4}x}'
111
112
113def whexC(val):
114 """Return a hex string for val padded for insnwidth,
115 and with the proper suffix for a C constant."""
116 suffix = ''
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000117 if val >= 0x100000000:
118 suffix = 'ull'
119 elif val >= 0x80000000:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700120 suffix = 'u'
121 return whex(val) + suffix
122
123
Richard Henderson568ae7e2017-12-07 12:44:09 -0800124def str_match_bits(bits, mask):
125 """Return a string pretty-printing BITS/MASK"""
126 global insnwidth
127
128 i = 1 << (insnwidth - 1)
129 space = 0x01010100
130 r = ''
131 while i != 0:
132 if i & mask:
133 if i & bits:
134 r += '1'
135 else:
136 r += '0'
137 else:
138 r += '.'
139 if i & space:
140 r += ' '
141 i >>= 1
142 return r
143
144
145def is_pow2(x):
146 """Return true iff X is equal to a power of 2."""
147 return (x & (x - 1)) == 0
148
149
150def ctz(x):
151 """Return the number of times 2 factors into X."""
Richard Hendersonb44b3442020-05-16 13:15:02 -0700152 assert x != 0
Richard Henderson568ae7e2017-12-07 12:44:09 -0800153 r = 0
154 while ((x >> r) & 1) == 0:
155 r += 1
156 return r
157
158
159def is_contiguous(bits):
Richard Hendersonb44b3442020-05-16 13:15:02 -0700160 if bits == 0:
161 return -1
Richard Henderson568ae7e2017-12-07 12:44:09 -0800162 shift = ctz(bits)
163 if is_pow2((bits >> shift) + 1):
164 return shift
165 else:
166 return -1
167
168
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700169def eq_fields_for_args(flds_a, arg):
170 if len(flds_a) != len(arg.fields):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800171 return False
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700172 # Only allow inference on default types
173 for t in arg.types:
174 if t != 'int':
175 return False
Richard Henderson568ae7e2017-12-07 12:44:09 -0800176 for k, a in flds_a.items():
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700177 if k not in arg.fields:
Richard Henderson568ae7e2017-12-07 12:44:09 -0800178 return False
179 return True
180
181
182def eq_fields_for_fmts(flds_a, flds_b):
183 if len(flds_a) != len(flds_b):
184 return False
185 for k, a in flds_a.items():
186 if k not in flds_b:
187 return False
188 b = flds_b[k]
189 if a.__class__ != b.__class__ or a != b:
190 return False
191 return True
192
193
194class Field:
195 """Class representing a simple instruction field"""
196 def __init__(self, sign, pos, len):
197 self.sign = sign
198 self.pos = pos
199 self.len = len
200 self.mask = ((1 << len) - 1) << pos
201
202 def __str__(self):
203 if self.sign:
204 s = 's'
205 else:
206 s = ''
Cleber Rosacbcdf1a2018-10-04 12:18:50 -0400207 return str(self.pos) + ':' + s + str(self.len)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800208
209 def str_extract(self):
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000210 global bitop_width
211 s = 's' if self.sign else ''
212 return f'{s}extract{bitop_width}(insn, {self.pos}, {self.len})'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800213
214 def __eq__(self, other):
Richard Henderson2c7d4422019-06-11 16:39:41 +0100215 return self.sign == other.sign and self.mask == other.mask
Richard Henderson568ae7e2017-12-07 12:44:09 -0800216
217 def __ne__(self, other):
218 return not self.__eq__(other)
219# end Field
220
221
222class MultiField:
223 """Class representing a compound instruction field"""
224 def __init__(self, subs, mask):
225 self.subs = subs
226 self.sign = subs[0].sign
227 self.mask = mask
228
229 def __str__(self):
230 return str(self.subs)
231
232 def str_extract(self):
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000233 global bitop_width
Richard Henderson568ae7e2017-12-07 12:44:09 -0800234 ret = '0'
235 pos = 0
236 for f in reversed(self.subs):
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700237 ext = f.str_extract()
Richard Henderson568ae7e2017-12-07 12:44:09 -0800238 if pos == 0:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700239 ret = ext
Richard Henderson568ae7e2017-12-07 12:44:09 -0800240 else:
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000241 ret = f'deposit{bitop_width}({ret}, {pos}, {bitop_width - pos}, {ext})'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800242 pos += f.len
243 return ret
244
245 def __ne__(self, other):
246 if len(self.subs) != len(other.subs):
247 return True
248 for a, b in zip(self.subs, other.subs):
249 if a.__class__ != b.__class__ or a != b:
250 return True
251 return False
252
253 def __eq__(self, other):
254 return not self.__ne__(other)
255# end MultiField
256
257
258class ConstField:
259 """Class representing an argument field with constant value"""
260 def __init__(self, value):
261 self.value = value
262 self.mask = 0
263 self.sign = value < 0
264
265 def __str__(self):
266 return str(self.value)
267
268 def str_extract(self):
269 return str(self.value)
270
271 def __cmp__(self, other):
272 return self.value - other.value
273# end ConstField
274
275
276class FunctionField:
Richard Henderson94597b62019-07-22 17:02:56 -0700277 """Class representing a field passed through a function"""
Richard Henderson568ae7e2017-12-07 12:44:09 -0800278 def __init__(self, func, base):
279 self.mask = base.mask
280 self.sign = base.sign
281 self.base = base
282 self.func = func
283
284 def __str__(self):
285 return self.func + '(' + str(self.base) + ')'
286
287 def str_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700288 return self.func + '(ctx, ' + self.base.str_extract() + ')'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800289
290 def __eq__(self, other):
291 return self.func == other.func and self.base == other.base
292
293 def __ne__(self, other):
294 return not self.__eq__(other)
295# end FunctionField
296
297
Richard Henderson94597b62019-07-22 17:02:56 -0700298class ParameterField:
299 """Class representing a pseudo-field read from a function"""
300 def __init__(self, func):
301 self.mask = 0
302 self.sign = 0
303 self.func = func
304
305 def __str__(self):
306 return self.func
307
308 def str_extract(self):
309 return self.func + '(ctx)'
310
311 def __eq__(self, other):
312 return self.func == other.func
313
314 def __ne__(self, other):
315 return not self.__eq__(other)
316# end ParameterField
317
318
Richard Henderson568ae7e2017-12-07 12:44:09 -0800319class Arguments:
320 """Class representing the extracted fields of a format"""
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700321 def __init__(self, nm, flds, types, extern):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800322 self.name = nm
Richard Hendersonabd04f92018-10-23 10:26:25 +0100323 self.extern = extern
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700324 self.fields = flds
325 self.types = types
Richard Henderson568ae7e2017-12-07 12:44:09 -0800326
327 def __str__(self):
328 return self.name + ' ' + str(self.fields)
329
330 def struct_name(self):
331 return 'arg_' + self.name
332
333 def output_def(self):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100334 if not self.extern:
335 output('typedef struct {\n')
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700336 for (n, t) in zip(self.fields, self.types):
337 output(f' {t} {n};\n')
Richard Hendersonabd04f92018-10-23 10:26:25 +0100338 output('} ', self.struct_name(), ';\n\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800339# end Arguments
340
341
342class General:
343 """Common code between instruction formats and instruction patterns"""
Richard Henderson17560e92019-01-30 18:01:29 -0800344 def __init__(self, name, lineno, base, fixb, fixm, udfm, fldm, flds, w):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800345 self.name = name
Richard Henderson6699ae62018-10-26 14:59:43 +0100346 self.file = input_file
Richard Henderson568ae7e2017-12-07 12:44:09 -0800347 self.lineno = lineno
348 self.base = base
349 self.fixedbits = fixb
350 self.fixedmask = fixm
351 self.undefmask = udfm
352 self.fieldmask = fldm
353 self.fields = flds
Richard Henderson17560e92019-01-30 18:01:29 -0800354 self.width = w
Richard Henderson568ae7e2017-12-07 12:44:09 -0800355
356 def __str__(self):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800357 return self.name + ' ' + str_match_bits(self.fixedbits, self.fixedmask)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800358
359 def str1(self, i):
360 return str_indent(i) + self.__str__()
361# end General
362
363
364class Format(General):
365 """Class representing an instruction format"""
366
367 def extract_name(self):
Richard Henderson71ecf792019-02-28 14:45:50 -0800368 global decode_function
369 return decode_function + '_extract_' + self.name
Richard Henderson568ae7e2017-12-07 12:44:09 -0800370
371 def output_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700372 output('static void ', self.extract_name(), '(DisasContext *ctx, ',
Richard Henderson568ae7e2017-12-07 12:44:09 -0800373 self.base.struct_name(), ' *a, ', insntype, ' insn)\n{\n')
374 for n, f in self.fields.items():
375 output(' a->', n, ' = ', f.str_extract(), ';\n')
376 output('}\n\n')
377# end Format
378
379
380class Pattern(General):
381 """Class representing an instruction pattern"""
382
383 def output_decl(self):
384 global translate_scope
385 global translate_prefix
386 output('typedef ', self.base.base.struct_name(),
387 ' arg_', self.name, ';\n')
Richard Henderson76805592018-03-02 10:45:35 +0000388 output(translate_scope, 'bool ', translate_prefix, '_', self.name,
Richard Henderson3a7be552018-10-23 11:05:27 +0100389 '(DisasContext *ctx, arg_', self.name, ' *a);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800390
391 def output_code(self, i, extracted, outerbits, outermask):
392 global translate_prefix
393 ind = str_indent(i)
394 arg = self.base.base.name
Richard Henderson6699ae62018-10-26 14:59:43 +0100395 output(ind, '/* ', self.file, ':', str(self.lineno), ' */\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800396 if not extracted:
Richard Henderson451e4ff2019-03-20 19:21:31 -0700397 output(ind, self.base.extract_name(),
398 '(ctx, &u.f_', arg, ', insn);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800399 for n, f in self.fields.items():
400 output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n')
Richard Hendersoneb6b87f2019-02-23 08:57:46 -0800401 output(ind, 'if (', translate_prefix, '_', self.name,
402 '(ctx, &u.f_', arg, ')) return true;\n')
Richard Henderson08561fc2020-05-17 10:14:11 -0700403
404 # Normal patterns do not have children.
405 def build_tree(self):
406 return
407 def prop_masks(self):
408 return
409 def prop_format(self):
410 return
411 def prop_width(self):
412 return
413
Richard Henderson568ae7e2017-12-07 12:44:09 -0800414# end Pattern
415
416
Richard Hendersondf630442020-05-16 11:19:45 -0700417class MultiPattern(General):
418 """Class representing a set of instruction patterns"""
419
Richard Henderson08561fc2020-05-17 10:14:11 -0700420 def __init__(self, lineno):
Richard Hendersondf630442020-05-16 11:19:45 -0700421 self.file = input_file
422 self.lineno = lineno
Richard Henderson08561fc2020-05-17 10:14:11 -0700423 self.pats = []
Richard Hendersondf630442020-05-16 11:19:45 -0700424 self.base = None
425 self.fixedbits = 0
426 self.fixedmask = 0
427 self.undefmask = 0
428 self.width = None
429
430 def __str__(self):
431 r = 'group'
432 if self.fixedbits is not None:
433 r += ' ' + str_match_bits(self.fixedbits, self.fixedmask)
434 return r
435
436 def output_decl(self):
437 for p in self.pats:
438 p.output_decl()
Richard Henderson08561fc2020-05-17 10:14:11 -0700439
440 def prop_masks(self):
441 global insnmask
442
443 fixedmask = insnmask
444 undefmask = insnmask
445
446 # Collect fixedmask/undefmask for all of the children.
447 for p in self.pats:
448 p.prop_masks()
449 fixedmask &= p.fixedmask
450 undefmask &= p.undefmask
451
452 # Widen fixedmask until all fixedbits match
453 repeat = True
454 fixedbits = 0
455 while repeat and fixedmask != 0:
456 fixedbits = None
457 for p in self.pats:
458 thisbits = p.fixedbits & fixedmask
459 if fixedbits is None:
460 fixedbits = thisbits
461 elif fixedbits != thisbits:
462 fixedmask &= ~(fixedbits ^ thisbits)
463 break
464 else:
465 repeat = False
466
467 self.fixedbits = fixedbits
468 self.fixedmask = fixedmask
469 self.undefmask = undefmask
470
471 def build_tree(self):
472 for p in self.pats:
473 p.build_tree()
474
475 def prop_format(self):
476 for p in self.pats:
Richard Henderson2fd2eb52023-05-25 18:45:43 -0700477 p.prop_format()
Richard Henderson08561fc2020-05-17 10:14:11 -0700478
479 def prop_width(self):
480 width = None
481 for p in self.pats:
482 p.prop_width()
483 if width is None:
484 width = p.width
485 elif width != p.width:
486 error_with_file(self.file, self.lineno,
487 'width mismatch in patterns within braces')
488 self.width = width
489
Richard Hendersondf630442020-05-16 11:19:45 -0700490# end MultiPattern
491
492
493class IncMultiPattern(MultiPattern):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800494 """Class representing an overlapping set of instruction patterns"""
495
Richard Henderson0eff2df2019-02-23 11:35:36 -0800496 def output_code(self, i, extracted, outerbits, outermask):
497 global translate_prefix
498 ind = str_indent(i)
499 for p in self.pats:
500 if outermask != p.fixedmask:
501 innermask = p.fixedmask & ~outermask
502 innerbits = p.fixedbits & ~outermask
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700503 output(ind, f'if ((insn & {whexC(innermask)}) == {whexC(innerbits)}) {{\n')
504 output(ind, f' /* {str_match_bits(p.fixedbits, p.fixedmask)} */\n')
Richard Henderson0eff2df2019-02-23 11:35:36 -0800505 p.output_code(i + 4, extracted, p.fixedbits, p.fixedmask)
506 output(ind, '}\n')
507 else:
508 p.output_code(i, extracted, p.fixedbits, p.fixedmask)
Richard Henderson040145c2020-05-16 10:50:43 -0700509#end IncMultiPattern
Richard Henderson0eff2df2019-02-23 11:35:36 -0800510
511
Richard Henderson08561fc2020-05-17 10:14:11 -0700512class Tree:
513 """Class representing a node in a decode tree"""
514
515 def __init__(self, fm, tm):
516 self.fixedmask = fm
517 self.thismask = tm
518 self.subs = []
519 self.base = None
520
521 def str1(self, i):
522 ind = str_indent(i)
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700523 r = ind + whex(self.fixedmask)
Richard Henderson08561fc2020-05-17 10:14:11 -0700524 if self.format:
525 r += ' ' + self.format.name
526 r += ' [\n'
527 for (b, s) in self.subs:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700528 r += ind + f' {whex(b)}:\n'
Richard Henderson08561fc2020-05-17 10:14:11 -0700529 r += s.str1(i + 4) + '\n'
530 r += ind + ']'
531 return r
532
533 def __str__(self):
534 return self.str1(0)
535
536 def output_code(self, i, extracted, outerbits, outermask):
537 ind = str_indent(i)
538
539 # If we identified all nodes below have the same format,
540 # extract the fields now.
541 if not extracted and self.base:
542 output(ind, self.base.extract_name(),
543 '(ctx, &u.f_', self.base.base.name, ', insn);\n')
544 extracted = True
545
546 # Attempt to aid the compiler in producing compact switch statements.
547 # If the bits in the mask are contiguous, extract them.
548 sh = is_contiguous(self.thismask)
549 if sh > 0:
550 # Propagate SH down into the local functions.
551 def str_switch(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700552 return f'(insn >> {sh}) & {b >> sh:#x}'
Richard Henderson08561fc2020-05-17 10:14:11 -0700553
554 def str_case(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700555 return hex(b >> sh)
Richard Henderson08561fc2020-05-17 10:14:11 -0700556 else:
557 def str_switch(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700558 return f'insn & {whexC(b)}'
Richard Henderson08561fc2020-05-17 10:14:11 -0700559
560 def str_case(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700561 return whexC(b)
Richard Henderson08561fc2020-05-17 10:14:11 -0700562
563 output(ind, 'switch (', str_switch(self.thismask), ') {\n')
564 for b, s in sorted(self.subs):
565 assert (self.thismask & ~s.fixedmask) == 0
566 innermask = outermask | self.thismask
567 innerbits = outerbits | b
568 output(ind, 'case ', str_case(b), ':\n')
569 output(ind, ' /* ',
570 str_match_bits(innerbits, innermask), ' */\n')
571 s.output_code(i + 4, extracted, innerbits, innermask)
Peter Maydell514101c2020-10-19 16:12:52 +0100572 output(ind, ' break;\n')
Richard Henderson08561fc2020-05-17 10:14:11 -0700573 output(ind, '}\n')
574# end Tree
575
576
577class ExcMultiPattern(MultiPattern):
578 """Class representing a non-overlapping set of instruction patterns"""
579
580 def output_code(self, i, extracted, outerbits, outermask):
581 # Defer everything to our decomposed Tree node
582 self.tree.output_code(i, extracted, outerbits, outermask)
583
584 @staticmethod
585 def __build_tree(pats, outerbits, outermask):
586 # Find the intersection of all remaining fixedmask.
587 innermask = ~outermask & insnmask
588 for i in pats:
589 innermask &= i.fixedmask
590
591 if innermask == 0:
592 # Edge condition: One pattern covers the entire insnmask
593 if len(pats) == 1:
594 t = Tree(outermask, innermask)
595 t.subs.append((0, pats[0]))
596 return t
597
598 text = 'overlapping patterns:'
599 for p in pats:
600 text += '\n' + p.file + ':' + str(p.lineno) + ': ' + str(p)
601 error_with_file(pats[0].file, pats[0].lineno, text)
602
603 fullmask = outermask | innermask
604
605 # Sort each element of pats into the bin selected by the mask.
606 bins = {}
607 for i in pats:
608 fb = i.fixedbits & innermask
609 if fb in bins:
610 bins[fb].append(i)
611 else:
612 bins[fb] = [i]
613
614 # We must recurse if any bin has more than one element or if
615 # the single element in the bin has not been fully matched.
616 t = Tree(fullmask, innermask)
617
618 for b, l in bins.items():
619 s = l[0]
620 if len(l) > 1 or s.fixedmask & ~fullmask != 0:
621 s = ExcMultiPattern.__build_tree(l, b | outerbits, fullmask)
622 t.subs.append((b, s))
623
624 return t
625
626 def build_tree(self):
Richard Henderson2fd2eb52023-05-25 18:45:43 -0700627 super().build_tree()
Richard Henderson08561fc2020-05-17 10:14:11 -0700628 self.tree = self.__build_tree(self.pats, self.fixedbits,
629 self.fixedmask)
630
631 @staticmethod
632 def __prop_format(tree):
633 """Propagate Format objects into the decode tree"""
634
635 # Depth first search.
636 for (b, s) in tree.subs:
637 if isinstance(s, Tree):
638 ExcMultiPattern.__prop_format(s)
639
640 # If all entries in SUBS have the same format, then
641 # propagate that into the tree.
642 f = None
643 for (b, s) in tree.subs:
644 if f is None:
645 f = s.base
646 if f is None:
647 return
648 if f is not s.base:
649 return
650 tree.base = f
651
652 def prop_format(self):
653 super().prop_format()
654 self.__prop_format(self.tree)
655
656# end ExcMultiPattern
657
658
Richard Henderson568ae7e2017-12-07 12:44:09 -0800659def parse_field(lineno, name, toks):
660 """Parse one instruction field from TOKS at LINENO"""
661 global fields
Richard Henderson568ae7e2017-12-07 12:44:09 -0800662 global insnwidth
663
664 # A "simple" field will have only one entry;
665 # a "multifield" will have several.
666 subs = []
667 width = 0
668 func = None
669 for t in toks:
Richard Hendersonacfdd232020-09-03 12:23:34 -0700670 if re.match('^!function=', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800671 if func:
672 error(lineno, 'duplicate function')
673 func = t.split('=')
674 func = func[1]
675 continue
676
John Snow2d110c12020-05-13 23:52:30 -0400677 if re.fullmatch('[0-9]+:s[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800678 # Signed field extract
679 subtoks = t.split(':s')
680 sign = True
John Snow2d110c12020-05-13 23:52:30 -0400681 elif re.fullmatch('[0-9]+:[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800682 # Unsigned field extract
683 subtoks = t.split(':')
684 sign = False
685 else:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700686 error(lineno, f'invalid field token "{t}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800687 po = int(subtoks[0])
688 le = int(subtoks[1])
689 if po + le > insnwidth:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700690 error(lineno, f'field {t} too large')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800691 f = Field(sign, po, le)
692 subs.append(f)
693 width += le
694
695 if width > insnwidth:
696 error(lineno, 'field too large')
Richard Henderson94597b62019-07-22 17:02:56 -0700697 if len(subs) == 0:
698 if func:
699 f = ParameterField(func)
700 else:
701 error(lineno, 'field with no value')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800702 else:
Richard Henderson94597b62019-07-22 17:02:56 -0700703 if len(subs) == 1:
704 f = subs[0]
705 else:
706 mask = 0
707 for s in subs:
708 if mask & s.mask:
709 error(lineno, 'field components overlap')
710 mask |= s.mask
711 f = MultiField(subs, mask)
712 if func:
713 f = FunctionField(func, f)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800714
715 if name in fields:
716 error(lineno, 'duplicate field', name)
717 fields[name] = f
718# end parse_field
719
720
721def parse_arguments(lineno, name, toks):
722 """Parse one argument set from TOKS at LINENO"""
723 global arguments
Richard Hendersonacfdd232020-09-03 12:23:34 -0700724 global re_C_ident
Richard Hendersonc6920792019-08-09 08:12:50 -0700725 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800726
727 flds = []
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700728 types = []
Richard Hendersonabd04f92018-10-23 10:26:25 +0100729 extern = False
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700730 for n in toks:
731 if re.fullmatch('!extern', n):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100732 extern = True
Richard Hendersonc6920792019-08-09 08:12:50 -0700733 anyextern = True
Richard Hendersonabd04f92018-10-23 10:26:25 +0100734 continue
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700735 if re.fullmatch(re_C_ident + ':' + re_C_ident, n):
736 (n, t) = n.split(':')
737 elif re.fullmatch(re_C_ident, n):
738 t = 'int'
739 else:
740 error(lineno, f'invalid argument set token "{n}"')
741 if n in flds:
742 error(lineno, f'duplicate argument "{n}"')
743 flds.append(n)
744 types.append(t)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800745
746 if name in arguments:
747 error(lineno, 'duplicate argument set', name)
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700748 arguments[name] = Arguments(name, flds, types, extern)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800749# end parse_arguments
750
751
752def lookup_field(lineno, name):
753 global fields
754 if name in fields:
755 return fields[name]
756 error(lineno, 'undefined field', name)
757
758
759def add_field(lineno, flds, new_name, f):
760 if new_name in flds:
761 error(lineno, 'duplicate field', new_name)
762 flds[new_name] = f
763 return flds
764
765
766def add_field_byname(lineno, flds, new_name, old_name):
767 return add_field(lineno, flds, new_name, lookup_field(lineno, old_name))
768
769
770def infer_argument_set(flds):
771 global arguments
Richard Hendersonabd04f92018-10-23 10:26:25 +0100772 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800773
774 for arg in arguments.values():
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700775 if eq_fields_for_args(flds, arg):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800776 return arg
777
Richard Hendersonabd04f92018-10-23 10:26:25 +0100778 name = decode_function + str(len(arguments))
Richard Hendersonaf93cca2021-04-29 10:03:59 -0700779 arg = Arguments(name, flds.keys(), ['int'] * len(flds), False)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800780 arguments[name] = arg
781 return arg
782
783
Richard Henderson17560e92019-01-30 18:01:29 -0800784def infer_format(arg, fieldmask, flds, width):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800785 global arguments
786 global formats
Richard Hendersonabd04f92018-10-23 10:26:25 +0100787 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800788
789 const_flds = {}
790 var_flds = {}
791 for n, c in flds.items():
792 if c is ConstField:
793 const_flds[n] = c
794 else:
795 var_flds[n] = c
796
797 # Look for an existing format with the same argument set and fields
798 for fmt in formats.values():
799 if arg and fmt.base != arg:
800 continue
801 if fieldmask != fmt.fieldmask:
802 continue
Richard Henderson17560e92019-01-30 18:01:29 -0800803 if width != fmt.width:
804 continue
Richard Henderson568ae7e2017-12-07 12:44:09 -0800805 if not eq_fields_for_fmts(flds, fmt.fields):
806 continue
807 return (fmt, const_flds)
808
Richard Hendersonabd04f92018-10-23 10:26:25 +0100809 name = decode_function + '_Fmt_' + str(len(formats))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800810 if not arg:
811 arg = infer_argument_set(flds)
812
Richard Henderson17560e92019-01-30 18:01:29 -0800813 fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800814 formats[name] = fmt
815
816 return (fmt, const_flds)
817# end infer_format
818
819
Richard Henderson08561fc2020-05-17 10:14:11 -0700820def parse_generic(lineno, parent_pat, name, toks):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800821 """Parse one instruction format from TOKS at LINENO"""
822 global fields
823 global arguments
824 global formats
Richard Henderson0eff2df2019-02-23 11:35:36 -0800825 global allpatterns
Richard Hendersonacfdd232020-09-03 12:23:34 -0700826 global re_arg_ident
827 global re_fld_ident
828 global re_fmt_ident
829 global re_C_ident
Richard Henderson568ae7e2017-12-07 12:44:09 -0800830 global insnwidth
831 global insnmask
Richard Henderson17560e92019-01-30 18:01:29 -0800832 global variablewidth
Richard Henderson568ae7e2017-12-07 12:44:09 -0800833
Richard Henderson08561fc2020-05-17 10:14:11 -0700834 is_format = parent_pat is None
835
Richard Henderson568ae7e2017-12-07 12:44:09 -0800836 fixedmask = 0
837 fixedbits = 0
838 undefmask = 0
839 width = 0
840 flds = {}
841 arg = None
842 fmt = None
843 for t in toks:
zhaolichang65fdb3c2020-09-17 15:50:23 +0800844 # '&Foo' gives a format an explicit argument set.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700845 if re.fullmatch(re_arg_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800846 tt = t[1:]
847 if arg:
848 error(lineno, 'multiple argument sets')
849 if tt in arguments:
850 arg = arguments[tt]
851 else:
852 error(lineno, 'undefined argument set', t)
853 continue
854
855 # '@Foo' gives a pattern an explicit format.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700856 if re.fullmatch(re_fmt_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800857 tt = t[1:]
858 if fmt:
859 error(lineno, 'multiple formats')
860 if tt in formats:
861 fmt = formats[tt]
862 else:
863 error(lineno, 'undefined format', t)
864 continue
865
866 # '%Foo' imports a field.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700867 if re.fullmatch(re_fld_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800868 tt = t[1:]
869 flds = add_field_byname(lineno, flds, tt, tt)
870 continue
871
872 # 'Foo=%Bar' imports a field with a different name.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700873 if re.fullmatch(re_C_ident + '=' + re_fld_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800874 (fname, iname) = t.split('=%')
875 flds = add_field_byname(lineno, flds, fname, iname)
876 continue
877
878 # 'Foo=number' sets an argument field to a constant value
Richard Hendersonacfdd232020-09-03 12:23:34 -0700879 if re.fullmatch(re_C_ident + '=[+-]?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800880 (fname, value) = t.split('=')
881 value = int(value)
882 flds = add_field(lineno, flds, fname, ConstField(value))
883 continue
884
885 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
886 # required ones, or dont-cares.
John Snow2d110c12020-05-13 23:52:30 -0400887 if re.fullmatch('[01.-]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800888 shift = len(t)
889 fms = t.replace('0', '1')
890 fms = fms.replace('.', '0')
891 fms = fms.replace('-', '0')
892 fbs = t.replace('.', '0')
893 fbs = fbs.replace('-', '0')
894 ubm = t.replace('1', '0')
895 ubm = ubm.replace('.', '0')
896 ubm = ubm.replace('-', '1')
897 fms = int(fms, 2)
898 fbs = int(fbs, 2)
899 ubm = int(ubm, 2)
900 fixedbits = (fixedbits << shift) | fbs
901 fixedmask = (fixedmask << shift) | fms
902 undefmask = (undefmask << shift) | ubm
903 # Otherwise, fieldname:fieldwidth
Richard Hendersonacfdd232020-09-03 12:23:34 -0700904 elif re.fullmatch(re_C_ident + ':s?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800905 (fname, flen) = t.split(':')
906 sign = False
907 if flen[0] == 's':
908 sign = True
909 flen = flen[1:]
910 shift = int(flen, 10)
Richard Henderson2decfc92019-03-05 15:34:41 -0800911 if shift + width > insnwidth:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700912 error(lineno, f'field {fname} exceeds insnwidth')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800913 f = Field(sign, insnwidth - width - shift, shift)
914 flds = add_field(lineno, flds, fname, f)
915 fixedbits <<= shift
916 fixedmask <<= shift
917 undefmask <<= shift
918 else:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700919 error(lineno, f'invalid token "{t}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800920 width += shift
921
Richard Henderson17560e92019-01-30 18:01:29 -0800922 if variablewidth and width < insnwidth and width % 8 == 0:
923 shift = insnwidth - width
924 fixedbits <<= shift
925 fixedmask <<= shift
926 undefmask <<= shift
927 undefmask |= (1 << shift) - 1
928
Richard Henderson568ae7e2017-12-07 12:44:09 -0800929 # We should have filled in all of the bits of the instruction.
Richard Henderson17560e92019-01-30 18:01:29 -0800930 elif not (is_format and width == 0) and width != insnwidth:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700931 error(lineno, f'definition has {width} bits')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800932
zhaolichang65fdb3c2020-09-17 15:50:23 +0800933 # Do not check for fields overlapping fields; one valid usage
Richard Henderson568ae7e2017-12-07 12:44:09 -0800934 # is to be able to duplicate fields via import.
935 fieldmask = 0
936 for f in flds.values():
937 fieldmask |= f.mask
938
939 # Fix up what we've parsed to match either a format or a pattern.
940 if is_format:
941 # Formats cannot reference formats.
942 if fmt:
943 error(lineno, 'format referencing format')
944 # If an argument set is given, then there should be no fields
945 # without a place to store it.
946 if arg:
947 for f in flds.keys():
948 if f not in arg.fields:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700949 error(lineno, f'field {f} not in argument set {arg.name}')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800950 else:
951 arg = infer_argument_set(flds)
952 if name in formats:
953 error(lineno, 'duplicate format name', name)
954 fmt = Format(name, lineno, arg, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800955 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800956 formats[name] = fmt
957 else:
958 # Patterns can reference a format ...
959 if fmt:
960 # ... but not an argument simultaneously
961 if arg:
962 error(lineno, 'pattern specifies both format and argument set')
963 if fixedmask & fmt.fixedmask:
964 error(lineno, 'pattern fixed bits overlap format fixed bits')
Richard Henderson17560e92019-01-30 18:01:29 -0800965 if width != fmt.width:
966 error(lineno, 'pattern uses format of different width')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800967 fieldmask |= fmt.fieldmask
968 fixedbits |= fmt.fixedbits
969 fixedmask |= fmt.fixedmask
970 undefmask |= fmt.undefmask
971 else:
Richard Henderson17560e92019-01-30 18:01:29 -0800972 (fmt, flds) = infer_format(arg, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800973 arg = fmt.base
974 for f in flds.keys():
975 if f not in arg.fields:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700976 error(lineno, f'field {f} not in argument set {arg.name}')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800977 if f in fmt.fields.keys():
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700978 error(lineno, f'field {f} set by format and pattern')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800979 for f in arg.fields:
980 if f not in flds.keys() and f not in fmt.fields.keys():
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700981 error(lineno, f'field {f} not initialized')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800982 pat = Pattern(name, lineno, fmt, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800983 undefmask, fieldmask, flds, width)
Richard Henderson08561fc2020-05-17 10:14:11 -0700984 parent_pat.pats.append(pat)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800985 allpatterns.append(pat)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800986
987 # Validate the masks that we have assembled.
988 if fieldmask & fixedmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700989 error(lineno, 'fieldmask overlaps fixedmask ',
990 f'({whex(fieldmask)} & {whex(fixedmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800991 if fieldmask & undefmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700992 error(lineno, 'fieldmask overlaps undefmask ',
993 f'({whex(fieldmask)} & {whex(undefmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800994 if fixedmask & undefmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700995 error(lineno, 'fixedmask overlaps undefmask ',
996 f'({whex(fixedmask)} & {whex(undefmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800997 if not is_format:
998 allbits = fieldmask | fixedmask | undefmask
999 if allbits != insnmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001000 error(lineno, 'bits left unspecified ',
1001 f'({whex(allbits ^ insnmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001002# end parse_general
1003
Richard Henderson0eff2df2019-02-23 11:35:36 -08001004
Richard Henderson08561fc2020-05-17 10:14:11 -07001005def parse_file(f, parent_pat):
Richard Henderson568ae7e2017-12-07 12:44:09 -08001006 """Parse all of the patterns within a file"""
Richard Hendersonacfdd232020-09-03 12:23:34 -07001007 global re_arg_ident
1008 global re_fld_ident
1009 global re_fmt_ident
1010 global re_pat_ident
Richard Henderson568ae7e2017-12-07 12:44:09 -08001011
1012 # Read all of the lines of the file. Concatenate lines
1013 # ending in backslash; discard empty lines and comments.
1014 toks = []
1015 lineno = 0
Richard Henderson0eff2df2019-02-23 11:35:36 -08001016 nesting = 0
Richard Henderson08561fc2020-05-17 10:14:11 -07001017 nesting_pats = []
Richard Henderson0eff2df2019-02-23 11:35:36 -08001018
Richard Henderson568ae7e2017-12-07 12:44:09 -08001019 for line in f:
1020 lineno += 1
1021
Richard Henderson0eff2df2019-02-23 11:35:36 -08001022 # Expand and strip spaces, to find indent.
1023 line = line.rstrip()
1024 line = line.expandtabs()
1025 len1 = len(line)
1026 line = line.lstrip()
1027 len2 = len(line)
1028
Richard Henderson568ae7e2017-12-07 12:44:09 -08001029 # Discard comments
1030 end = line.find('#')
1031 if end >= 0:
1032 line = line[:end]
1033
1034 t = line.split()
1035 if len(toks) != 0:
1036 # Next line after continuation
1037 toks.extend(t)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001038 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -08001039 # Allow completely blank lines.
1040 if len1 == 0:
1041 continue
1042 indent = len1 - len2
1043 # Empty line due to comment.
1044 if len(t) == 0:
1045 # Indentation must be correct, even for comment lines.
1046 if indent != nesting:
1047 error(lineno, 'indentation ', indent, ' != ', nesting)
1048 continue
1049 start_lineno = lineno
Richard Henderson568ae7e2017-12-07 12:44:09 -08001050 toks = t
1051
1052 # Continuation?
1053 if toks[-1] == '\\':
1054 toks.pop()
1055 continue
1056
Richard Henderson568ae7e2017-12-07 12:44:09 -08001057 name = toks[0]
1058 del toks[0]
1059
Richard Henderson0eff2df2019-02-23 11:35:36 -08001060 # End nesting?
Richard Henderson067e8b02020-05-18 08:45:32 -07001061 if name == '}' or name == ']':
Richard Henderson0eff2df2019-02-23 11:35:36 -08001062 if len(toks) != 0:
1063 error(start_lineno, 'extra tokens after close brace')
Richard Henderson08561fc2020-05-17 10:14:11 -07001064
Richard Henderson067e8b02020-05-18 08:45:32 -07001065 # Make sure { } and [ ] nest properly.
1066 if (name == '}') != isinstance(parent_pat, IncMultiPattern):
1067 error(lineno, 'mismatched close brace')
1068
Richard Henderson08561fc2020-05-17 10:14:11 -07001069 try:
1070 parent_pat = nesting_pats.pop()
1071 except:
Richard Henderson067e8b02020-05-18 08:45:32 -07001072 error(lineno, 'extra close brace')
Richard Henderson08561fc2020-05-17 10:14:11 -07001073
Richard Henderson0eff2df2019-02-23 11:35:36 -08001074 nesting -= 2
1075 if indent != nesting:
Richard Henderson08561fc2020-05-17 10:14:11 -07001076 error(lineno, 'indentation ', indent, ' != ', nesting)
1077
Richard Henderson0eff2df2019-02-23 11:35:36 -08001078 toks = []
1079 continue
1080
1081 # Everything else should have current indentation.
1082 if indent != nesting:
1083 error(start_lineno, 'indentation ', indent, ' != ', nesting)
1084
1085 # Start nesting?
Richard Henderson067e8b02020-05-18 08:45:32 -07001086 if name == '{' or name == '[':
Richard Henderson0eff2df2019-02-23 11:35:36 -08001087 if len(toks) != 0:
1088 error(start_lineno, 'extra tokens after open brace')
Richard Henderson08561fc2020-05-17 10:14:11 -07001089
Richard Henderson067e8b02020-05-18 08:45:32 -07001090 if name == '{':
1091 nested_pat = IncMultiPattern(start_lineno)
1092 else:
1093 nested_pat = ExcMultiPattern(start_lineno)
Richard Henderson08561fc2020-05-17 10:14:11 -07001094 parent_pat.pats.append(nested_pat)
1095 nesting_pats.append(parent_pat)
1096 parent_pat = nested_pat
1097
Richard Henderson0eff2df2019-02-23 11:35:36 -08001098 nesting += 2
1099 toks = []
1100 continue
1101
Richard Henderson568ae7e2017-12-07 12:44:09 -08001102 # Determine the type of object needing to be parsed.
Richard Hendersonacfdd232020-09-03 12:23:34 -07001103 if re.fullmatch(re_fld_ident, name):
Richard Henderson0eff2df2019-02-23 11:35:36 -08001104 parse_field(start_lineno, name[1:], toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001105 elif re.fullmatch(re_arg_ident, name):
Richard Henderson0eff2df2019-02-23 11:35:36 -08001106 parse_arguments(start_lineno, name[1:], toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001107 elif re.fullmatch(re_fmt_ident, name):
Richard Henderson08561fc2020-05-17 10:14:11 -07001108 parse_generic(start_lineno, None, name[1:], toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001109 elif re.fullmatch(re_pat_ident, name):
Richard Henderson08561fc2020-05-17 10:14:11 -07001110 parse_generic(start_lineno, parent_pat, name, toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001111 else:
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001112 error(lineno, f'invalid token "{name}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001113 toks = []
Richard Henderson067e8b02020-05-18 08:45:32 -07001114
1115 if nesting != 0:
1116 error(lineno, 'missing close brace')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001117# end parse_file
1118
1119
Richard Henderson70e07112019-01-31 11:34:11 -08001120class SizeTree:
1121 """Class representing a node in a size decode tree"""
1122
1123 def __init__(self, m, w):
1124 self.mask = m
1125 self.subs = []
1126 self.base = None
1127 self.width = w
1128
1129 def str1(self, i):
1130 ind = str_indent(i)
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001131 r = ind + whex(self.mask) + ' [\n'
Richard Henderson70e07112019-01-31 11:34:11 -08001132 for (b, s) in self.subs:
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001133 r += ind + f' {whex(b)}:\n'
Richard Henderson70e07112019-01-31 11:34:11 -08001134 r += s.str1(i + 4) + '\n'
1135 r += ind + ']'
1136 return r
1137
1138 def __str__(self):
1139 return self.str1(0)
1140
1141 def output_code(self, i, extracted, outerbits, outermask):
1142 ind = str_indent(i)
1143
1144 # If we need to load more bytes to test, do so now.
1145 if extracted < self.width:
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001146 output(ind, f'insn = {decode_function}_load_bytes',
1147 f'(ctx, insn, {extracted // 8}, {self.width // 8});\n')
Richard Henderson70e07112019-01-31 11:34:11 -08001148 extracted = self.width
1149
1150 # Attempt to aid the compiler in producing compact switch statements.
1151 # If the bits in the mask are contiguous, extract them.
1152 sh = is_contiguous(self.mask)
1153 if sh > 0:
1154 # Propagate SH down into the local functions.
1155 def str_switch(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001156 return f'(insn >> {sh}) & {b >> sh:#x}'
Richard Henderson70e07112019-01-31 11:34:11 -08001157
1158 def str_case(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001159 return hex(b >> sh)
Richard Henderson70e07112019-01-31 11:34:11 -08001160 else:
1161 def str_switch(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001162 return f'insn & {whexC(b)}'
Richard Henderson70e07112019-01-31 11:34:11 -08001163
1164 def str_case(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001165 return whexC(b)
Richard Henderson70e07112019-01-31 11:34:11 -08001166
1167 output(ind, 'switch (', str_switch(self.mask), ') {\n')
1168 for b, s in sorted(self.subs):
1169 innermask = outermask | self.mask
1170 innerbits = outerbits | b
1171 output(ind, 'case ', str_case(b), ':\n')
1172 output(ind, ' /* ',
1173 str_match_bits(innerbits, innermask), ' */\n')
1174 s.output_code(i + 4, extracted, innerbits, innermask)
1175 output(ind, '}\n')
1176 output(ind, 'return insn;\n')
1177# end SizeTree
1178
1179class SizeLeaf:
1180 """Class representing a leaf node in a size decode tree"""
1181
1182 def __init__(self, m, w):
1183 self.mask = m
1184 self.width = w
1185
1186 def str1(self, i):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001187 return str_indent(i) + whex(self.mask)
Richard Henderson70e07112019-01-31 11:34:11 -08001188
1189 def __str__(self):
1190 return self.str1(0)
1191
1192 def output_code(self, i, extracted, outerbits, outermask):
1193 global decode_function
1194 ind = str_indent(i)
1195
1196 # If we need to load more bytes, do so now.
1197 if extracted < self.width:
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001198 output(ind, f'insn = {decode_function}_load_bytes',
1199 f'(ctx, insn, {extracted // 8}, {self.width // 8});\n')
Richard Henderson70e07112019-01-31 11:34:11 -08001200 extracted = self.width
1201 output(ind, 'return insn;\n')
1202# end SizeLeaf
1203
1204
1205def build_size_tree(pats, width, outerbits, outermask):
1206 global insnwidth
1207
1208 # Collect the mask of bits that are fixed in this width
1209 innermask = 0xff << (insnwidth - width)
1210 innermask &= ~outermask
1211 minwidth = None
1212 onewidth = True
1213 for i in pats:
1214 innermask &= i.fixedmask
1215 if minwidth is None:
1216 minwidth = i.width
1217 elif minwidth != i.width:
1218 onewidth = False;
1219 if minwidth < i.width:
1220 minwidth = i.width
1221
1222 if onewidth:
1223 return SizeLeaf(innermask, minwidth)
1224
1225 if innermask == 0:
1226 if width < minwidth:
1227 return build_size_tree(pats, width + 8, outerbits, outermask)
1228
1229 pnames = []
1230 for p in pats:
1231 pnames.append(p.name + ':' + p.file + ':' + str(p.lineno))
1232 error_with_file(pats[0].file, pats[0].lineno,
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001233 f'overlapping patterns size {width}:', pnames)
Richard Henderson70e07112019-01-31 11:34:11 -08001234
1235 bins = {}
1236 for i in pats:
1237 fb = i.fixedbits & innermask
1238 if fb in bins:
1239 bins[fb].append(i)
1240 else:
1241 bins[fb] = [i]
1242
1243 fullmask = outermask | innermask
1244 lens = sorted(bins.keys())
1245 if len(lens) == 1:
1246 b = lens[0]
1247 return build_size_tree(bins[b], width + 8, b | outerbits, fullmask)
1248
1249 r = SizeTree(innermask, width)
1250 for b, l in bins.items():
1251 s = build_size_tree(l, width, b | outerbits, fullmask)
1252 r.subs.append((b, s))
1253 return r
1254# end build_size_tree
1255
1256
Richard Henderson70e07112019-01-31 11:34:11 -08001257def prop_size(tree):
1258 """Propagate minimum widths up the decode size tree"""
1259
1260 if isinstance(tree, SizeTree):
1261 min = None
1262 for (b, s) in tree.subs:
1263 width = prop_size(s)
1264 if min is None or min > width:
1265 min = width
1266 assert min >= tree.width
1267 tree.width = min
1268 else:
1269 min = tree.width
1270 return min
1271# end prop_size
1272
1273
Richard Henderson568ae7e2017-12-07 12:44:09 -08001274def main():
1275 global arguments
1276 global formats
Richard Henderson0eff2df2019-02-23 11:35:36 -08001277 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -08001278 global translate_scope
1279 global translate_prefix
1280 global output_fd
1281 global output_file
1282 global input_file
1283 global insnwidth
1284 global insntype
Bastian Koppelmann83d7c402018-03-19 12:58:46 +01001285 global insnmask
Richard Hendersonabd04f92018-10-23 10:26:25 +01001286 global decode_function
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +00001287 global bitop_width
Richard Henderson17560e92019-01-30 18:01:29 -08001288 global variablewidth
Richard Hendersonc6920792019-08-09 08:12:50 -07001289 global anyextern
Richard Henderson9b5acc52023-05-25 18:04:05 -07001290 global testforerror
Richard Henderson568ae7e2017-12-07 12:44:09 -08001291
Richard Henderson568ae7e2017-12-07 12:44:09 -08001292 decode_scope = 'static '
1293
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001294 long_opts = ['decode=', 'translate=', 'output=', 'insnwidth=',
Richard Henderson9b5acc52023-05-25 18:04:05 -07001295 'static-decode=', 'varinsnwidth=', 'test-for-error']
Richard Henderson568ae7e2017-12-07 12:44:09 -08001296 try:
Paolo Bonziniabff1ab2020-08-07 12:10:23 +02001297 (opts, args) = getopt.gnu_getopt(sys.argv[1:], 'o:vw:', long_opts)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001298 except getopt.GetoptError as err:
1299 error(0, err)
1300 for o, a in opts:
1301 if o in ('-o', '--output'):
1302 output_file = a
1303 elif o == '--decode':
1304 decode_function = a
1305 decode_scope = ''
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001306 elif o == '--static-decode':
1307 decode_function = a
Richard Henderson568ae7e2017-12-07 12:44:09 -08001308 elif o == '--translate':
1309 translate_prefix = a
1310 translate_scope = ''
Richard Henderson17560e92019-01-30 18:01:29 -08001311 elif o in ('-w', '--insnwidth', '--varinsnwidth'):
1312 if o == '--varinsnwidth':
1313 variablewidth = True
Richard Henderson568ae7e2017-12-07 12:44:09 -08001314 insnwidth = int(a)
1315 if insnwidth == 16:
1316 insntype = 'uint16_t'
1317 insnmask = 0xffff
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +00001318 elif insnwidth == 64:
1319 insntype = 'uint64_t'
1320 insnmask = 0xffffffffffffffff
1321 bitop_width = 64
Richard Henderson568ae7e2017-12-07 12:44:09 -08001322 elif insnwidth != 32:
1323 error(0, 'cannot handle insns of width', insnwidth)
Richard Henderson9b5acc52023-05-25 18:04:05 -07001324 elif o == '--test-for-error':
1325 testforerror = True
Richard Henderson568ae7e2017-12-07 12:44:09 -08001326 else:
1327 assert False, 'unhandled option'
1328
1329 if len(args) < 1:
1330 error(0, 'missing input file')
Richard Henderson08561fc2020-05-17 10:14:11 -07001331
1332 toppat = ExcMultiPattern(0)
1333
Richard Henderson6699ae62018-10-26 14:59:43 +01001334 for filename in args:
1335 input_file = filename
Philippe Mathieu-Daudé4caceca2021-01-10 01:02:40 +01001336 f = open(filename, 'rt', encoding='utf-8')
Richard Henderson08561fc2020-05-17 10:14:11 -07001337 parse_file(f, toppat)
Richard Henderson6699ae62018-10-26 14:59:43 +01001338 f.close()
Richard Henderson568ae7e2017-12-07 12:44:09 -08001339
Richard Henderson08561fc2020-05-17 10:14:11 -07001340 # We do not want to compute masks for toppat, because those masks
1341 # are used as a starting point for build_tree. For toppat, we must
1342 # insist that decode begins from naught.
1343 for i in toppat.pats:
1344 i.prop_masks()
Richard Henderson70e07112019-01-31 11:34:11 -08001345
Richard Henderson08561fc2020-05-17 10:14:11 -07001346 toppat.build_tree()
1347 toppat.prop_format()
1348
1349 if variablewidth:
1350 for i in toppat.pats:
1351 i.prop_width()
1352 stree = build_size_tree(toppat.pats, 8, 0, 0)
1353 prop_size(stree)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001354
1355 if output_file:
Philippe Mathieu-Daudé4caceca2021-01-10 01:02:40 +01001356 output_fd = open(output_file, 'wt', encoding='utf-8')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001357 else:
Philippe Mathieu-Daudé4caceca2021-01-10 01:02:40 +01001358 output_fd = io.TextIOWrapper(sys.stdout.buffer,
1359 encoding=sys.stdout.encoding,
1360 errors="ignore")
Richard Henderson568ae7e2017-12-07 12:44:09 -08001361
1362 output_autogen()
1363 for n in sorted(arguments.keys()):
1364 f = arguments[n]
1365 f.output_def()
1366
1367 # A single translate function can be invoked for different patterns.
1368 # Make sure that the argument sets are the same, and declare the
1369 # function only once.
Richard Hendersonc6920792019-08-09 08:12:50 -07001370 #
1371 # If we're sharing formats, we're likely also sharing trans_* functions,
1372 # but we can't tell which ones. Prevent issues from the compiler by
1373 # suppressing redundant declaration warnings.
1374 if anyextern:
Thomas Huth7aa12aa2020-07-08 20:19:44 +02001375 output("#pragma GCC diagnostic push\n",
1376 "#pragma GCC diagnostic ignored \"-Wredundant-decls\"\n",
1377 "#ifdef __clang__\n"
Richard Hendersonc6920792019-08-09 08:12:50 -07001378 "# pragma GCC diagnostic ignored \"-Wtypedef-redefinition\"\n",
Richard Hendersonc6920792019-08-09 08:12:50 -07001379 "#endif\n\n")
1380
Richard Henderson568ae7e2017-12-07 12:44:09 -08001381 out_pats = {}
Richard Henderson0eff2df2019-02-23 11:35:36 -08001382 for i in allpatterns:
Richard Henderson568ae7e2017-12-07 12:44:09 -08001383 if i.name in out_pats:
1384 p = out_pats[i.name]
1385 if i.base.base != p.base.base:
1386 error(0, i.name, ' has conflicting argument sets')
1387 else:
1388 i.output_decl()
1389 out_pats[i.name] = i
1390 output('\n')
1391
Richard Hendersonc6920792019-08-09 08:12:50 -07001392 if anyextern:
Thomas Huth7aa12aa2020-07-08 20:19:44 +02001393 output("#pragma GCC diagnostic pop\n\n")
Richard Hendersonc6920792019-08-09 08:12:50 -07001394
Richard Henderson568ae7e2017-12-07 12:44:09 -08001395 for n in sorted(formats.keys()):
1396 f = formats[n]
1397 f.output_extract()
1398
1399 output(decode_scope, 'bool ', decode_function,
1400 '(DisasContext *ctx, ', insntype, ' insn)\n{\n')
1401
1402 i4 = str_indent(4)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001403
Richard Henderson82bfac12019-02-27 21:37:32 -08001404 if len(allpatterns) != 0:
1405 output(i4, 'union {\n')
1406 for n in sorted(arguments.keys()):
1407 f = arguments[n]
1408 output(i4, i4, f.struct_name(), ' f_', f.name, ';\n')
1409 output(i4, '} u;\n\n')
Richard Henderson08561fc2020-05-17 10:14:11 -07001410 toppat.output_code(4, False, 0, 0)
Richard Henderson82bfac12019-02-27 21:37:32 -08001411
Richard Hendersoneb6b87f2019-02-23 08:57:46 -08001412 output(i4, 'return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001413 output('}\n')
1414
Richard Henderson70e07112019-01-31 11:34:11 -08001415 if variablewidth:
1416 output('\n', decode_scope, insntype, ' ', decode_function,
1417 '_load(DisasContext *ctx)\n{\n',
1418 ' ', insntype, ' insn = 0;\n\n')
1419 stree.output_code(4, 0, 0, 0)
1420 output('}\n')
1421
Richard Henderson568ae7e2017-12-07 12:44:09 -08001422 if output_file:
1423 output_fd.close()
Richard Henderson9b5acc52023-05-25 18:04:05 -07001424 exit(1 if testforerror else 0)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001425# end main
1426
1427
1428if __name__ == '__main__':
1429 main()