blob: f85da45ee37d53b6e481e7e7843735942e4b2ce2 [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 Henderson568ae7e2017-12-07 12:44:09 -080038
39translate_prefix = 'trans'
40translate_scope = 'static '
41input_file = ''
42output_file = None
43output_fd = None
44insntype = 'uint32_t'
Richard Hendersonabd04f92018-10-23 10:26:25 +010045decode_function = 'decode'
Richard Henderson568ae7e2017-12-07 12:44:09 -080046
Richard Hendersonacfdd232020-09-03 12:23:34 -070047# An identifier for C.
48re_C_ident = '[a-zA-Z][a-zA-Z0-9_]*'
Richard Henderson568ae7e2017-12-07 12:44:09 -080049
Richard Hendersonacfdd232020-09-03 12:23:34 -070050# Identifiers for Arguments, Fields, Formats and Patterns.
51re_arg_ident = '&[a-zA-Z0-9_]*'
52re_fld_ident = '%[a-zA-Z0-9_]*'
53re_fmt_ident = '@[a-zA-Z0-9_]*'
54re_pat_ident = '[a-zA-Z0-9_]*'
Richard Henderson568ae7e2017-12-07 12:44:09 -080055
Richard Henderson6699ae62018-10-26 14:59:43 +010056def error_with_file(file, lineno, *args):
Richard Henderson568ae7e2017-12-07 12:44:09 -080057 """Print an error message from file:line and args and exit."""
58 global output_file
59 global output_fd
60
Richard Henderson2fd51b12020-05-15 14:48:54 -070061 prefix = ''
62 if file:
Richard Henderson9f6e2b42021-04-28 16:37:02 -070063 prefix += f'{file}:'
Richard Henderson568ae7e2017-12-07 12:44:09 -080064 if lineno:
Richard Henderson9f6e2b42021-04-28 16:37:02 -070065 prefix += f'{lineno}:'
Richard Henderson2fd51b12020-05-15 14:48:54 -070066 if prefix:
67 prefix += ' '
68 print(prefix, end='error: ', file=sys.stderr)
69 print(*args, file=sys.stderr)
70
Richard Henderson568ae7e2017-12-07 12:44:09 -080071 if output_file and output_fd:
72 output_fd.close()
73 os.remove(output_file)
74 exit(1)
Richard Henderson2fd51b12020-05-15 14:48:54 -070075# end error_with_file
76
Richard Henderson568ae7e2017-12-07 12:44:09 -080077
Richard Henderson6699ae62018-10-26 14:59:43 +010078def error(lineno, *args):
Richard Henderson2fd51b12020-05-15 14:48:54 -070079 error_with_file(input_file, lineno, *args)
80# end error
81
Richard Henderson568ae7e2017-12-07 12:44:09 -080082
83def output(*args):
84 global output_fd
85 for a in args:
86 output_fd.write(a)
87
88
Richard Henderson568ae7e2017-12-07 12:44:09 -080089def output_autogen():
90 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
91
92
93def str_indent(c):
94 """Return a string with C spaces"""
95 return ' ' * c
96
97
98def str_fields(fields):
zhaolichang65fdb3c2020-09-17 15:50:23 +080099 """Return a string uniquely identifying FIELDS"""
Richard Henderson568ae7e2017-12-07 12:44:09 -0800100 r = ''
101 for n in sorted(fields.keys()):
102 r += '_' + n
103 return r[1:]
104
105
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700106def whex(val):
107 """Return a hex string for val padded for insnwidth"""
108 global insnwidth
109 return f'0x{val:0{insnwidth // 4}x}'
110
111
112def whexC(val):
113 """Return a hex string for val padded for insnwidth,
114 and with the proper suffix for a C constant."""
115 suffix = ''
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000116 if val >= 0x100000000:
117 suffix = 'ull'
118 elif val >= 0x80000000:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700119 suffix = 'u'
120 return whex(val) + suffix
121
122
Richard Henderson568ae7e2017-12-07 12:44:09 -0800123def str_match_bits(bits, mask):
124 """Return a string pretty-printing BITS/MASK"""
125 global insnwidth
126
127 i = 1 << (insnwidth - 1)
128 space = 0x01010100
129 r = ''
130 while i != 0:
131 if i & mask:
132 if i & bits:
133 r += '1'
134 else:
135 r += '0'
136 else:
137 r += '.'
138 if i & space:
139 r += ' '
140 i >>= 1
141 return r
142
143
144def is_pow2(x):
145 """Return true iff X is equal to a power of 2."""
146 return (x & (x - 1)) == 0
147
148
149def ctz(x):
150 """Return the number of times 2 factors into X."""
Richard Hendersonb44b3442020-05-16 13:15:02 -0700151 assert x != 0
Richard Henderson568ae7e2017-12-07 12:44:09 -0800152 r = 0
153 while ((x >> r) & 1) == 0:
154 r += 1
155 return r
156
157
158def is_contiguous(bits):
Richard Hendersonb44b3442020-05-16 13:15:02 -0700159 if bits == 0:
160 return -1
Richard Henderson568ae7e2017-12-07 12:44:09 -0800161 shift = ctz(bits)
162 if is_pow2((bits >> shift) + 1):
163 return shift
164 else:
165 return -1
166
167
168def eq_fields_for_args(flds_a, flds_b):
169 if len(flds_a) != len(flds_b):
170 return False
171 for k, a in flds_a.items():
172 if k not in flds_b:
173 return False
174 return True
175
176
177def eq_fields_for_fmts(flds_a, flds_b):
178 if len(flds_a) != len(flds_b):
179 return False
180 for k, a in flds_a.items():
181 if k not in flds_b:
182 return False
183 b = flds_b[k]
184 if a.__class__ != b.__class__ or a != b:
185 return False
186 return True
187
188
189class Field:
190 """Class representing a simple instruction field"""
191 def __init__(self, sign, pos, len):
192 self.sign = sign
193 self.pos = pos
194 self.len = len
195 self.mask = ((1 << len) - 1) << pos
196
197 def __str__(self):
198 if self.sign:
199 s = 's'
200 else:
201 s = ''
Cleber Rosacbcdf1a2018-10-04 12:18:50 -0400202 return str(self.pos) + ':' + s + str(self.len)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800203
204 def str_extract(self):
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000205 global bitop_width
206 s = 's' if self.sign else ''
207 return f'{s}extract{bitop_width}(insn, {self.pos}, {self.len})'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800208
209 def __eq__(self, other):
Richard Henderson2c7d4422019-06-11 16:39:41 +0100210 return self.sign == other.sign and self.mask == other.mask
Richard Henderson568ae7e2017-12-07 12:44:09 -0800211
212 def __ne__(self, other):
213 return not self.__eq__(other)
214# end Field
215
216
217class MultiField:
218 """Class representing a compound instruction field"""
219 def __init__(self, subs, mask):
220 self.subs = subs
221 self.sign = subs[0].sign
222 self.mask = mask
223
224 def __str__(self):
225 return str(self.subs)
226
227 def str_extract(self):
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000228 global bitop_width
Richard Henderson568ae7e2017-12-07 12:44:09 -0800229 ret = '0'
230 pos = 0
231 for f in reversed(self.subs):
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700232 ext = f.str_extract()
Richard Henderson568ae7e2017-12-07 12:44:09 -0800233 if pos == 0:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700234 ret = ext
Richard Henderson568ae7e2017-12-07 12:44:09 -0800235 else:
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +0000236 ret = f'deposit{bitop_width}({ret}, {pos}, {bitop_width - pos}, {ext})'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800237 pos += f.len
238 return ret
239
240 def __ne__(self, other):
241 if len(self.subs) != len(other.subs):
242 return True
243 for a, b in zip(self.subs, other.subs):
244 if a.__class__ != b.__class__ or a != b:
245 return True
246 return False
247
248 def __eq__(self, other):
249 return not self.__ne__(other)
250# end MultiField
251
252
253class ConstField:
254 """Class representing an argument field with constant value"""
255 def __init__(self, value):
256 self.value = value
257 self.mask = 0
258 self.sign = value < 0
259
260 def __str__(self):
261 return str(self.value)
262
263 def str_extract(self):
264 return str(self.value)
265
266 def __cmp__(self, other):
267 return self.value - other.value
268# end ConstField
269
270
271class FunctionField:
Richard Henderson94597b62019-07-22 17:02:56 -0700272 """Class representing a field passed through a function"""
Richard Henderson568ae7e2017-12-07 12:44:09 -0800273 def __init__(self, func, base):
274 self.mask = base.mask
275 self.sign = base.sign
276 self.base = base
277 self.func = func
278
279 def __str__(self):
280 return self.func + '(' + str(self.base) + ')'
281
282 def str_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700283 return self.func + '(ctx, ' + self.base.str_extract() + ')'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800284
285 def __eq__(self, other):
286 return self.func == other.func and self.base == other.base
287
288 def __ne__(self, other):
289 return not self.__eq__(other)
290# end FunctionField
291
292
Richard Henderson94597b62019-07-22 17:02:56 -0700293class ParameterField:
294 """Class representing a pseudo-field read from a function"""
295 def __init__(self, func):
296 self.mask = 0
297 self.sign = 0
298 self.func = func
299
300 def __str__(self):
301 return self.func
302
303 def str_extract(self):
304 return self.func + '(ctx)'
305
306 def __eq__(self, other):
307 return self.func == other.func
308
309 def __ne__(self, other):
310 return not self.__eq__(other)
311# end ParameterField
312
313
Richard Henderson568ae7e2017-12-07 12:44:09 -0800314class Arguments:
315 """Class representing the extracted fields of a format"""
Richard Hendersonabd04f92018-10-23 10:26:25 +0100316 def __init__(self, nm, flds, extern):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800317 self.name = nm
Richard Hendersonabd04f92018-10-23 10:26:25 +0100318 self.extern = extern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800319 self.fields = sorted(flds)
320
321 def __str__(self):
322 return self.name + ' ' + str(self.fields)
323
324 def struct_name(self):
325 return 'arg_' + self.name
326
327 def output_def(self):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100328 if not self.extern:
329 output('typedef struct {\n')
330 for n in self.fields:
331 output(' int ', n, ';\n')
332 output('} ', self.struct_name(), ';\n\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800333# end Arguments
334
335
336class General:
337 """Common code between instruction formats and instruction patterns"""
Richard Henderson17560e92019-01-30 18:01:29 -0800338 def __init__(self, name, lineno, base, fixb, fixm, udfm, fldm, flds, w):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800339 self.name = name
Richard Henderson6699ae62018-10-26 14:59:43 +0100340 self.file = input_file
Richard Henderson568ae7e2017-12-07 12:44:09 -0800341 self.lineno = lineno
342 self.base = base
343 self.fixedbits = fixb
344 self.fixedmask = fixm
345 self.undefmask = udfm
346 self.fieldmask = fldm
347 self.fields = flds
Richard Henderson17560e92019-01-30 18:01:29 -0800348 self.width = w
Richard Henderson568ae7e2017-12-07 12:44:09 -0800349
350 def __str__(self):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800351 return self.name + ' ' + str_match_bits(self.fixedbits, self.fixedmask)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800352
353 def str1(self, i):
354 return str_indent(i) + self.__str__()
355# end General
356
357
358class Format(General):
359 """Class representing an instruction format"""
360
361 def extract_name(self):
Richard Henderson71ecf792019-02-28 14:45:50 -0800362 global decode_function
363 return decode_function + '_extract_' + self.name
Richard Henderson568ae7e2017-12-07 12:44:09 -0800364
365 def output_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700366 output('static void ', self.extract_name(), '(DisasContext *ctx, ',
Richard Henderson568ae7e2017-12-07 12:44:09 -0800367 self.base.struct_name(), ' *a, ', insntype, ' insn)\n{\n')
368 for n, f in self.fields.items():
369 output(' a->', n, ' = ', f.str_extract(), ';\n')
370 output('}\n\n')
371# end Format
372
373
374class Pattern(General):
375 """Class representing an instruction pattern"""
376
377 def output_decl(self):
378 global translate_scope
379 global translate_prefix
380 output('typedef ', self.base.base.struct_name(),
381 ' arg_', self.name, ';\n')
Richard Henderson76805592018-03-02 10:45:35 +0000382 output(translate_scope, 'bool ', translate_prefix, '_', self.name,
Richard Henderson3a7be552018-10-23 11:05:27 +0100383 '(DisasContext *ctx, arg_', self.name, ' *a);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800384
385 def output_code(self, i, extracted, outerbits, outermask):
386 global translate_prefix
387 ind = str_indent(i)
388 arg = self.base.base.name
Richard Henderson6699ae62018-10-26 14:59:43 +0100389 output(ind, '/* ', self.file, ':', str(self.lineno), ' */\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800390 if not extracted:
Richard Henderson451e4ff2019-03-20 19:21:31 -0700391 output(ind, self.base.extract_name(),
392 '(ctx, &u.f_', arg, ', insn);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800393 for n, f in self.fields.items():
394 output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n')
Richard Hendersoneb6b87f2019-02-23 08:57:46 -0800395 output(ind, 'if (', translate_prefix, '_', self.name,
396 '(ctx, &u.f_', arg, ')) return true;\n')
Richard Henderson08561fc2020-05-17 10:14:11 -0700397
398 # Normal patterns do not have children.
399 def build_tree(self):
400 return
401 def prop_masks(self):
402 return
403 def prop_format(self):
404 return
405 def prop_width(self):
406 return
407
Richard Henderson568ae7e2017-12-07 12:44:09 -0800408# end Pattern
409
410
Richard Hendersondf630442020-05-16 11:19:45 -0700411class MultiPattern(General):
412 """Class representing a set of instruction patterns"""
413
Richard Henderson08561fc2020-05-17 10:14:11 -0700414 def __init__(self, lineno):
Richard Hendersondf630442020-05-16 11:19:45 -0700415 self.file = input_file
416 self.lineno = lineno
Richard Henderson08561fc2020-05-17 10:14:11 -0700417 self.pats = []
Richard Hendersondf630442020-05-16 11:19:45 -0700418 self.base = None
419 self.fixedbits = 0
420 self.fixedmask = 0
421 self.undefmask = 0
422 self.width = None
423
424 def __str__(self):
425 r = 'group'
426 if self.fixedbits is not None:
427 r += ' ' + str_match_bits(self.fixedbits, self.fixedmask)
428 return r
429
430 def output_decl(self):
431 for p in self.pats:
432 p.output_decl()
Richard Henderson08561fc2020-05-17 10:14:11 -0700433
434 def prop_masks(self):
435 global insnmask
436
437 fixedmask = insnmask
438 undefmask = insnmask
439
440 # Collect fixedmask/undefmask for all of the children.
441 for p in self.pats:
442 p.prop_masks()
443 fixedmask &= p.fixedmask
444 undefmask &= p.undefmask
445
446 # Widen fixedmask until all fixedbits match
447 repeat = True
448 fixedbits = 0
449 while repeat and fixedmask != 0:
450 fixedbits = None
451 for p in self.pats:
452 thisbits = p.fixedbits & fixedmask
453 if fixedbits is None:
454 fixedbits = thisbits
455 elif fixedbits != thisbits:
456 fixedmask &= ~(fixedbits ^ thisbits)
457 break
458 else:
459 repeat = False
460
461 self.fixedbits = fixedbits
462 self.fixedmask = fixedmask
463 self.undefmask = undefmask
464
465 def build_tree(self):
466 for p in self.pats:
467 p.build_tree()
468
469 def prop_format(self):
470 for p in self.pats:
471 p.build_tree()
472
473 def prop_width(self):
474 width = None
475 for p in self.pats:
476 p.prop_width()
477 if width is None:
478 width = p.width
479 elif width != p.width:
480 error_with_file(self.file, self.lineno,
481 'width mismatch in patterns within braces')
482 self.width = width
483
Richard Hendersondf630442020-05-16 11:19:45 -0700484# end MultiPattern
485
486
487class IncMultiPattern(MultiPattern):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800488 """Class representing an overlapping set of instruction patterns"""
489
Richard Henderson0eff2df2019-02-23 11:35:36 -0800490 def output_code(self, i, extracted, outerbits, outermask):
491 global translate_prefix
492 ind = str_indent(i)
493 for p in self.pats:
494 if outermask != p.fixedmask:
495 innermask = p.fixedmask & ~outermask
496 innerbits = p.fixedbits & ~outermask
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700497 output(ind, f'if ((insn & {whexC(innermask)}) == {whexC(innerbits)}) {{\n')
498 output(ind, f' /* {str_match_bits(p.fixedbits, p.fixedmask)} */\n')
Richard Henderson0eff2df2019-02-23 11:35:36 -0800499 p.output_code(i + 4, extracted, p.fixedbits, p.fixedmask)
500 output(ind, '}\n')
501 else:
502 p.output_code(i, extracted, p.fixedbits, p.fixedmask)
Richard Henderson040145c2020-05-16 10:50:43 -0700503#end IncMultiPattern
Richard Henderson0eff2df2019-02-23 11:35:36 -0800504
505
Richard Henderson08561fc2020-05-17 10:14:11 -0700506class Tree:
507 """Class representing a node in a decode tree"""
508
509 def __init__(self, fm, tm):
510 self.fixedmask = fm
511 self.thismask = tm
512 self.subs = []
513 self.base = None
514
515 def str1(self, i):
516 ind = str_indent(i)
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700517 r = ind + whex(self.fixedmask)
Richard Henderson08561fc2020-05-17 10:14:11 -0700518 if self.format:
519 r += ' ' + self.format.name
520 r += ' [\n'
521 for (b, s) in self.subs:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700522 r += ind + f' {whex(b)}:\n'
Richard Henderson08561fc2020-05-17 10:14:11 -0700523 r += s.str1(i + 4) + '\n'
524 r += ind + ']'
525 return r
526
527 def __str__(self):
528 return self.str1(0)
529
530 def output_code(self, i, extracted, outerbits, outermask):
531 ind = str_indent(i)
532
533 # If we identified all nodes below have the same format,
534 # extract the fields now.
535 if not extracted and self.base:
536 output(ind, self.base.extract_name(),
537 '(ctx, &u.f_', self.base.base.name, ', insn);\n')
538 extracted = True
539
540 # Attempt to aid the compiler in producing compact switch statements.
541 # If the bits in the mask are contiguous, extract them.
542 sh = is_contiguous(self.thismask)
543 if sh > 0:
544 # Propagate SH down into the local functions.
545 def str_switch(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700546 return f'(insn >> {sh}) & {b >> sh:#x}'
Richard Henderson08561fc2020-05-17 10:14:11 -0700547
548 def str_case(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700549 return hex(b >> sh)
Richard Henderson08561fc2020-05-17 10:14:11 -0700550 else:
551 def str_switch(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700552 return f'insn & {whexC(b)}'
Richard Henderson08561fc2020-05-17 10:14:11 -0700553
554 def str_case(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700555 return whexC(b)
Richard Henderson08561fc2020-05-17 10:14:11 -0700556
557 output(ind, 'switch (', str_switch(self.thismask), ') {\n')
558 for b, s in sorted(self.subs):
559 assert (self.thismask & ~s.fixedmask) == 0
560 innermask = outermask | self.thismask
561 innerbits = outerbits | b
562 output(ind, 'case ', str_case(b), ':\n')
563 output(ind, ' /* ',
564 str_match_bits(innerbits, innermask), ' */\n')
565 s.output_code(i + 4, extracted, innerbits, innermask)
Peter Maydell514101c2020-10-19 16:12:52 +0100566 output(ind, ' break;\n')
Richard Henderson08561fc2020-05-17 10:14:11 -0700567 output(ind, '}\n')
568# end Tree
569
570
571class ExcMultiPattern(MultiPattern):
572 """Class representing a non-overlapping set of instruction patterns"""
573
574 def output_code(self, i, extracted, outerbits, outermask):
575 # Defer everything to our decomposed Tree node
576 self.tree.output_code(i, extracted, outerbits, outermask)
577
578 @staticmethod
579 def __build_tree(pats, outerbits, outermask):
580 # Find the intersection of all remaining fixedmask.
581 innermask = ~outermask & insnmask
582 for i in pats:
583 innermask &= i.fixedmask
584
585 if innermask == 0:
586 # Edge condition: One pattern covers the entire insnmask
587 if len(pats) == 1:
588 t = Tree(outermask, innermask)
589 t.subs.append((0, pats[0]))
590 return t
591
592 text = 'overlapping patterns:'
593 for p in pats:
594 text += '\n' + p.file + ':' + str(p.lineno) + ': ' + str(p)
595 error_with_file(pats[0].file, pats[0].lineno, text)
596
597 fullmask = outermask | innermask
598
599 # Sort each element of pats into the bin selected by the mask.
600 bins = {}
601 for i in pats:
602 fb = i.fixedbits & innermask
603 if fb in bins:
604 bins[fb].append(i)
605 else:
606 bins[fb] = [i]
607
608 # We must recurse if any bin has more than one element or if
609 # the single element in the bin has not been fully matched.
610 t = Tree(fullmask, innermask)
611
612 for b, l in bins.items():
613 s = l[0]
614 if len(l) > 1 or s.fixedmask & ~fullmask != 0:
615 s = ExcMultiPattern.__build_tree(l, b | outerbits, fullmask)
616 t.subs.append((b, s))
617
618 return t
619
620 def build_tree(self):
621 super().prop_format()
622 self.tree = self.__build_tree(self.pats, self.fixedbits,
623 self.fixedmask)
624
625 @staticmethod
626 def __prop_format(tree):
627 """Propagate Format objects into the decode tree"""
628
629 # Depth first search.
630 for (b, s) in tree.subs:
631 if isinstance(s, Tree):
632 ExcMultiPattern.__prop_format(s)
633
634 # If all entries in SUBS have the same format, then
635 # propagate that into the tree.
636 f = None
637 for (b, s) in tree.subs:
638 if f is None:
639 f = s.base
640 if f is None:
641 return
642 if f is not s.base:
643 return
644 tree.base = f
645
646 def prop_format(self):
647 super().prop_format()
648 self.__prop_format(self.tree)
649
650# end ExcMultiPattern
651
652
Richard Henderson568ae7e2017-12-07 12:44:09 -0800653def parse_field(lineno, name, toks):
654 """Parse one instruction field from TOKS at LINENO"""
655 global fields
Richard Henderson568ae7e2017-12-07 12:44:09 -0800656 global insnwidth
657
658 # A "simple" field will have only one entry;
659 # a "multifield" will have several.
660 subs = []
661 width = 0
662 func = None
663 for t in toks:
Richard Hendersonacfdd232020-09-03 12:23:34 -0700664 if re.match('^!function=', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800665 if func:
666 error(lineno, 'duplicate function')
667 func = t.split('=')
668 func = func[1]
669 continue
670
John Snow2d110c12020-05-13 23:52:30 -0400671 if re.fullmatch('[0-9]+:s[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800672 # Signed field extract
673 subtoks = t.split(':s')
674 sign = True
John Snow2d110c12020-05-13 23:52:30 -0400675 elif re.fullmatch('[0-9]+:[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800676 # Unsigned field extract
677 subtoks = t.split(':')
678 sign = False
679 else:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700680 error(lineno, f'invalid field token "{t}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800681 po = int(subtoks[0])
682 le = int(subtoks[1])
683 if po + le > insnwidth:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700684 error(lineno, f'field {t} too large')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800685 f = Field(sign, po, le)
686 subs.append(f)
687 width += le
688
689 if width > insnwidth:
690 error(lineno, 'field too large')
Richard Henderson94597b62019-07-22 17:02:56 -0700691 if len(subs) == 0:
692 if func:
693 f = ParameterField(func)
694 else:
695 error(lineno, 'field with no value')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800696 else:
Richard Henderson94597b62019-07-22 17:02:56 -0700697 if len(subs) == 1:
698 f = subs[0]
699 else:
700 mask = 0
701 for s in subs:
702 if mask & s.mask:
703 error(lineno, 'field components overlap')
704 mask |= s.mask
705 f = MultiField(subs, mask)
706 if func:
707 f = FunctionField(func, f)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800708
709 if name in fields:
710 error(lineno, 'duplicate field', name)
711 fields[name] = f
712# end parse_field
713
714
715def parse_arguments(lineno, name, toks):
716 """Parse one argument set from TOKS at LINENO"""
717 global arguments
Richard Hendersonacfdd232020-09-03 12:23:34 -0700718 global re_C_ident
Richard Hendersonc6920792019-08-09 08:12:50 -0700719 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800720
721 flds = []
Richard Hendersonabd04f92018-10-23 10:26:25 +0100722 extern = False
Richard Henderson568ae7e2017-12-07 12:44:09 -0800723 for t in toks:
John Snow2d110c12020-05-13 23:52:30 -0400724 if re.fullmatch('!extern', t):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100725 extern = True
Richard Hendersonc6920792019-08-09 08:12:50 -0700726 anyextern = True
Richard Hendersonabd04f92018-10-23 10:26:25 +0100727 continue
Richard Hendersonacfdd232020-09-03 12:23:34 -0700728 if not re.fullmatch(re_C_ident, t):
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700729 error(lineno, f'invalid argument set token "{t}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800730 if t in flds:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700731 error(lineno, f'duplicate argument "{t}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800732 flds.append(t)
733
734 if name in arguments:
735 error(lineno, 'duplicate argument set', name)
Richard Hendersonabd04f92018-10-23 10:26:25 +0100736 arguments[name] = Arguments(name, flds, extern)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800737# end parse_arguments
738
739
740def lookup_field(lineno, name):
741 global fields
742 if name in fields:
743 return fields[name]
744 error(lineno, 'undefined field', name)
745
746
747def add_field(lineno, flds, new_name, f):
748 if new_name in flds:
749 error(lineno, 'duplicate field', new_name)
750 flds[new_name] = f
751 return flds
752
753
754def add_field_byname(lineno, flds, new_name, old_name):
755 return add_field(lineno, flds, new_name, lookup_field(lineno, old_name))
756
757
758def infer_argument_set(flds):
759 global arguments
Richard Hendersonabd04f92018-10-23 10:26:25 +0100760 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800761
762 for arg in arguments.values():
763 if eq_fields_for_args(flds, arg.fields):
764 return arg
765
Richard Hendersonabd04f92018-10-23 10:26:25 +0100766 name = decode_function + str(len(arguments))
767 arg = Arguments(name, flds.keys(), False)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800768 arguments[name] = arg
769 return arg
770
771
Richard Henderson17560e92019-01-30 18:01:29 -0800772def infer_format(arg, fieldmask, flds, width):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800773 global arguments
774 global formats
Richard Hendersonabd04f92018-10-23 10:26:25 +0100775 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800776
777 const_flds = {}
778 var_flds = {}
779 for n, c in flds.items():
780 if c is ConstField:
781 const_flds[n] = c
782 else:
783 var_flds[n] = c
784
785 # Look for an existing format with the same argument set and fields
786 for fmt in formats.values():
787 if arg and fmt.base != arg:
788 continue
789 if fieldmask != fmt.fieldmask:
790 continue
Richard Henderson17560e92019-01-30 18:01:29 -0800791 if width != fmt.width:
792 continue
Richard Henderson568ae7e2017-12-07 12:44:09 -0800793 if not eq_fields_for_fmts(flds, fmt.fields):
794 continue
795 return (fmt, const_flds)
796
Richard Hendersonabd04f92018-10-23 10:26:25 +0100797 name = decode_function + '_Fmt_' + str(len(formats))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800798 if not arg:
799 arg = infer_argument_set(flds)
800
Richard Henderson17560e92019-01-30 18:01:29 -0800801 fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800802 formats[name] = fmt
803
804 return (fmt, const_flds)
805# end infer_format
806
807
Richard Henderson08561fc2020-05-17 10:14:11 -0700808def parse_generic(lineno, parent_pat, name, toks):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800809 """Parse one instruction format from TOKS at LINENO"""
810 global fields
811 global arguments
812 global formats
Richard Henderson0eff2df2019-02-23 11:35:36 -0800813 global allpatterns
Richard Hendersonacfdd232020-09-03 12:23:34 -0700814 global re_arg_ident
815 global re_fld_ident
816 global re_fmt_ident
817 global re_C_ident
Richard Henderson568ae7e2017-12-07 12:44:09 -0800818 global insnwidth
819 global insnmask
Richard Henderson17560e92019-01-30 18:01:29 -0800820 global variablewidth
Richard Henderson568ae7e2017-12-07 12:44:09 -0800821
Richard Henderson08561fc2020-05-17 10:14:11 -0700822 is_format = parent_pat is None
823
Richard Henderson568ae7e2017-12-07 12:44:09 -0800824 fixedmask = 0
825 fixedbits = 0
826 undefmask = 0
827 width = 0
828 flds = {}
829 arg = None
830 fmt = None
831 for t in toks:
zhaolichang65fdb3c2020-09-17 15:50:23 +0800832 # '&Foo' gives a format an explicit argument set.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700833 if re.fullmatch(re_arg_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800834 tt = t[1:]
835 if arg:
836 error(lineno, 'multiple argument sets')
837 if tt in arguments:
838 arg = arguments[tt]
839 else:
840 error(lineno, 'undefined argument set', t)
841 continue
842
843 # '@Foo' gives a pattern an explicit format.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700844 if re.fullmatch(re_fmt_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800845 tt = t[1:]
846 if fmt:
847 error(lineno, 'multiple formats')
848 if tt in formats:
849 fmt = formats[tt]
850 else:
851 error(lineno, 'undefined format', t)
852 continue
853
854 # '%Foo' imports a field.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700855 if re.fullmatch(re_fld_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800856 tt = t[1:]
857 flds = add_field_byname(lineno, flds, tt, tt)
858 continue
859
860 # 'Foo=%Bar' imports a field with a different name.
Richard Hendersonacfdd232020-09-03 12:23:34 -0700861 if re.fullmatch(re_C_ident + '=' + re_fld_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800862 (fname, iname) = t.split('=%')
863 flds = add_field_byname(lineno, flds, fname, iname)
864 continue
865
866 # 'Foo=number' sets an argument field to a constant value
Richard Hendersonacfdd232020-09-03 12:23:34 -0700867 if re.fullmatch(re_C_ident + '=[+-]?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800868 (fname, value) = t.split('=')
869 value = int(value)
870 flds = add_field(lineno, flds, fname, ConstField(value))
871 continue
872
873 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
874 # required ones, or dont-cares.
John Snow2d110c12020-05-13 23:52:30 -0400875 if re.fullmatch('[01.-]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800876 shift = len(t)
877 fms = t.replace('0', '1')
878 fms = fms.replace('.', '0')
879 fms = fms.replace('-', '0')
880 fbs = t.replace('.', '0')
881 fbs = fbs.replace('-', '0')
882 ubm = t.replace('1', '0')
883 ubm = ubm.replace('.', '0')
884 ubm = ubm.replace('-', '1')
885 fms = int(fms, 2)
886 fbs = int(fbs, 2)
887 ubm = int(ubm, 2)
888 fixedbits = (fixedbits << shift) | fbs
889 fixedmask = (fixedmask << shift) | fms
890 undefmask = (undefmask << shift) | ubm
891 # Otherwise, fieldname:fieldwidth
Richard Hendersonacfdd232020-09-03 12:23:34 -0700892 elif re.fullmatch(re_C_ident + ':s?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800893 (fname, flen) = t.split(':')
894 sign = False
895 if flen[0] == 's':
896 sign = True
897 flen = flen[1:]
898 shift = int(flen, 10)
Richard Henderson2decfc92019-03-05 15:34:41 -0800899 if shift + width > insnwidth:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700900 error(lineno, f'field {fname} exceeds insnwidth')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800901 f = Field(sign, insnwidth - width - shift, shift)
902 flds = add_field(lineno, flds, fname, f)
903 fixedbits <<= shift
904 fixedmask <<= shift
905 undefmask <<= shift
906 else:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700907 error(lineno, f'invalid token "{t}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800908 width += shift
909
Richard Henderson17560e92019-01-30 18:01:29 -0800910 if variablewidth and width < insnwidth and width % 8 == 0:
911 shift = insnwidth - width
912 fixedbits <<= shift
913 fixedmask <<= shift
914 undefmask <<= shift
915 undefmask |= (1 << shift) - 1
916
Richard Henderson568ae7e2017-12-07 12:44:09 -0800917 # We should have filled in all of the bits of the instruction.
Richard Henderson17560e92019-01-30 18:01:29 -0800918 elif not (is_format and width == 0) and width != insnwidth:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700919 error(lineno, f'definition has {width} bits')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800920
zhaolichang65fdb3c2020-09-17 15:50:23 +0800921 # Do not check for fields overlapping fields; one valid usage
Richard Henderson568ae7e2017-12-07 12:44:09 -0800922 # is to be able to duplicate fields via import.
923 fieldmask = 0
924 for f in flds.values():
925 fieldmask |= f.mask
926
927 # Fix up what we've parsed to match either a format or a pattern.
928 if is_format:
929 # Formats cannot reference formats.
930 if fmt:
931 error(lineno, 'format referencing format')
932 # If an argument set is given, then there should be no fields
933 # without a place to store it.
934 if arg:
935 for f in flds.keys():
936 if f not in arg.fields:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700937 error(lineno, f'field {f} not in argument set {arg.name}')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800938 else:
939 arg = infer_argument_set(flds)
940 if name in formats:
941 error(lineno, 'duplicate format name', name)
942 fmt = Format(name, lineno, arg, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800943 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800944 formats[name] = fmt
945 else:
946 # Patterns can reference a format ...
947 if fmt:
948 # ... but not an argument simultaneously
949 if arg:
950 error(lineno, 'pattern specifies both format and argument set')
951 if fixedmask & fmt.fixedmask:
952 error(lineno, 'pattern fixed bits overlap format fixed bits')
Richard Henderson17560e92019-01-30 18:01:29 -0800953 if width != fmt.width:
954 error(lineno, 'pattern uses format of different width')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800955 fieldmask |= fmt.fieldmask
956 fixedbits |= fmt.fixedbits
957 fixedmask |= fmt.fixedmask
958 undefmask |= fmt.undefmask
959 else:
Richard Henderson17560e92019-01-30 18:01:29 -0800960 (fmt, flds) = infer_format(arg, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800961 arg = fmt.base
962 for f in flds.keys():
963 if f not in arg.fields:
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700964 error(lineno, f'field {f} not in argument set {arg.name}')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800965 if f in fmt.fields.keys():
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700966 error(lineno, f'field {f} set by format and pattern')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800967 for f in arg.fields:
968 if f not in flds.keys() and f not in fmt.fields.keys():
Richard Henderson9f6e2b42021-04-28 16:37:02 -0700969 error(lineno, f'field {f} not initialized')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800970 pat = Pattern(name, lineno, fmt, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800971 undefmask, fieldmask, flds, width)
Richard Henderson08561fc2020-05-17 10:14:11 -0700972 parent_pat.pats.append(pat)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800973 allpatterns.append(pat)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800974
975 # Validate the masks that we have assembled.
976 if fieldmask & fixedmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700977 error(lineno, 'fieldmask overlaps fixedmask ',
978 f'({whex(fieldmask)} & {whex(fixedmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800979 if fieldmask & undefmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700980 error(lineno, 'fieldmask overlaps undefmask ',
981 f'({whex(fieldmask)} & {whex(undefmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800982 if fixedmask & undefmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700983 error(lineno, 'fixedmask overlaps undefmask ',
984 f'({whex(fixedmask)} & {whex(undefmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800985 if not is_format:
986 allbits = fieldmask | fixedmask | undefmask
987 if allbits != insnmask:
Richard Hendersonc7cefe62021-04-28 16:27:56 -0700988 error(lineno, 'bits left unspecified ',
989 f'({whex(allbits ^ insnmask)})')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800990# end parse_general
991
Richard Henderson0eff2df2019-02-23 11:35:36 -0800992
Richard Henderson08561fc2020-05-17 10:14:11 -0700993def parse_file(f, parent_pat):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800994 """Parse all of the patterns within a file"""
Richard Hendersonacfdd232020-09-03 12:23:34 -0700995 global re_arg_ident
996 global re_fld_ident
997 global re_fmt_ident
998 global re_pat_ident
Richard Henderson568ae7e2017-12-07 12:44:09 -0800999
1000 # Read all of the lines of the file. Concatenate lines
1001 # ending in backslash; discard empty lines and comments.
1002 toks = []
1003 lineno = 0
Richard Henderson0eff2df2019-02-23 11:35:36 -08001004 nesting = 0
Richard Henderson08561fc2020-05-17 10:14:11 -07001005 nesting_pats = []
Richard Henderson0eff2df2019-02-23 11:35:36 -08001006
Richard Henderson568ae7e2017-12-07 12:44:09 -08001007 for line in f:
1008 lineno += 1
1009
Richard Henderson0eff2df2019-02-23 11:35:36 -08001010 # Expand and strip spaces, to find indent.
1011 line = line.rstrip()
1012 line = line.expandtabs()
1013 len1 = len(line)
1014 line = line.lstrip()
1015 len2 = len(line)
1016
Richard Henderson568ae7e2017-12-07 12:44:09 -08001017 # Discard comments
1018 end = line.find('#')
1019 if end >= 0:
1020 line = line[:end]
1021
1022 t = line.split()
1023 if len(toks) != 0:
1024 # Next line after continuation
1025 toks.extend(t)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001026 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -08001027 # Allow completely blank lines.
1028 if len1 == 0:
1029 continue
1030 indent = len1 - len2
1031 # Empty line due to comment.
1032 if len(t) == 0:
1033 # Indentation must be correct, even for comment lines.
1034 if indent != nesting:
1035 error(lineno, 'indentation ', indent, ' != ', nesting)
1036 continue
1037 start_lineno = lineno
Richard Henderson568ae7e2017-12-07 12:44:09 -08001038 toks = t
1039
1040 # Continuation?
1041 if toks[-1] == '\\':
1042 toks.pop()
1043 continue
1044
Richard Henderson568ae7e2017-12-07 12:44:09 -08001045 name = toks[0]
1046 del toks[0]
1047
Richard Henderson0eff2df2019-02-23 11:35:36 -08001048 # End nesting?
Richard Henderson067e8b02020-05-18 08:45:32 -07001049 if name == '}' or name == ']':
Richard Henderson0eff2df2019-02-23 11:35:36 -08001050 if len(toks) != 0:
1051 error(start_lineno, 'extra tokens after close brace')
Richard Henderson08561fc2020-05-17 10:14:11 -07001052
Richard Henderson067e8b02020-05-18 08:45:32 -07001053 # Make sure { } and [ ] nest properly.
1054 if (name == '}') != isinstance(parent_pat, IncMultiPattern):
1055 error(lineno, 'mismatched close brace')
1056
Richard Henderson08561fc2020-05-17 10:14:11 -07001057 try:
1058 parent_pat = nesting_pats.pop()
1059 except:
Richard Henderson067e8b02020-05-18 08:45:32 -07001060 error(lineno, 'extra close brace')
Richard Henderson08561fc2020-05-17 10:14:11 -07001061
Richard Henderson0eff2df2019-02-23 11:35:36 -08001062 nesting -= 2
1063 if indent != nesting:
Richard Henderson08561fc2020-05-17 10:14:11 -07001064 error(lineno, 'indentation ', indent, ' != ', nesting)
1065
Richard Henderson0eff2df2019-02-23 11:35:36 -08001066 toks = []
1067 continue
1068
1069 # Everything else should have current indentation.
1070 if indent != nesting:
1071 error(start_lineno, 'indentation ', indent, ' != ', nesting)
1072
1073 # Start nesting?
Richard Henderson067e8b02020-05-18 08:45:32 -07001074 if name == '{' or name == '[':
Richard Henderson0eff2df2019-02-23 11:35:36 -08001075 if len(toks) != 0:
1076 error(start_lineno, 'extra tokens after open brace')
Richard Henderson08561fc2020-05-17 10:14:11 -07001077
Richard Henderson067e8b02020-05-18 08:45:32 -07001078 if name == '{':
1079 nested_pat = IncMultiPattern(start_lineno)
1080 else:
1081 nested_pat = ExcMultiPattern(start_lineno)
Richard Henderson08561fc2020-05-17 10:14:11 -07001082 parent_pat.pats.append(nested_pat)
1083 nesting_pats.append(parent_pat)
1084 parent_pat = nested_pat
1085
Richard Henderson0eff2df2019-02-23 11:35:36 -08001086 nesting += 2
1087 toks = []
1088 continue
1089
Richard Henderson568ae7e2017-12-07 12:44:09 -08001090 # Determine the type of object needing to be parsed.
Richard Hendersonacfdd232020-09-03 12:23:34 -07001091 if re.fullmatch(re_fld_ident, name):
Richard Henderson0eff2df2019-02-23 11:35:36 -08001092 parse_field(start_lineno, name[1:], toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001093 elif re.fullmatch(re_arg_ident, name):
Richard Henderson0eff2df2019-02-23 11:35:36 -08001094 parse_arguments(start_lineno, name[1:], toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001095 elif re.fullmatch(re_fmt_ident, name):
Richard Henderson08561fc2020-05-17 10:14:11 -07001096 parse_generic(start_lineno, None, name[1:], toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001097 elif re.fullmatch(re_pat_ident, name):
Richard Henderson08561fc2020-05-17 10:14:11 -07001098 parse_generic(start_lineno, parent_pat, name, toks)
Richard Hendersonacfdd232020-09-03 12:23:34 -07001099 else:
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001100 error(lineno, f'invalid token "{name}"')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001101 toks = []
Richard Henderson067e8b02020-05-18 08:45:32 -07001102
1103 if nesting != 0:
1104 error(lineno, 'missing close brace')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001105# end parse_file
1106
1107
Richard Henderson70e07112019-01-31 11:34:11 -08001108class SizeTree:
1109 """Class representing a node in a size decode tree"""
1110
1111 def __init__(self, m, w):
1112 self.mask = m
1113 self.subs = []
1114 self.base = None
1115 self.width = w
1116
1117 def str1(self, i):
1118 ind = str_indent(i)
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001119 r = ind + whex(self.mask) + ' [\n'
Richard Henderson70e07112019-01-31 11:34:11 -08001120 for (b, s) in self.subs:
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001121 r += ind + f' {whex(b)}:\n'
Richard Henderson70e07112019-01-31 11:34:11 -08001122 r += s.str1(i + 4) + '\n'
1123 r += ind + ']'
1124 return r
1125
1126 def __str__(self):
1127 return self.str1(0)
1128
1129 def output_code(self, i, extracted, outerbits, outermask):
1130 ind = str_indent(i)
1131
1132 # If we need to load more bytes to test, do so now.
1133 if extracted < self.width:
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001134 output(ind, f'insn = {decode_function}_load_bytes',
1135 f'(ctx, insn, {extracted // 8}, {self.width // 8});\n')
Richard Henderson70e07112019-01-31 11:34:11 -08001136 extracted = self.width
1137
1138 # Attempt to aid the compiler in producing compact switch statements.
1139 # If the bits in the mask are contiguous, extract them.
1140 sh = is_contiguous(self.mask)
1141 if sh > 0:
1142 # Propagate SH down into the local functions.
1143 def str_switch(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001144 return f'(insn >> {sh}) & {b >> sh:#x}'
Richard Henderson70e07112019-01-31 11:34:11 -08001145
1146 def str_case(b, sh=sh):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001147 return hex(b >> sh)
Richard Henderson70e07112019-01-31 11:34:11 -08001148 else:
1149 def str_switch(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001150 return f'insn & {whexC(b)}'
Richard Henderson70e07112019-01-31 11:34:11 -08001151
1152 def str_case(b):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001153 return whexC(b)
Richard Henderson70e07112019-01-31 11:34:11 -08001154
1155 output(ind, 'switch (', str_switch(self.mask), ') {\n')
1156 for b, s in sorted(self.subs):
1157 innermask = outermask | self.mask
1158 innerbits = outerbits | b
1159 output(ind, 'case ', str_case(b), ':\n')
1160 output(ind, ' /* ',
1161 str_match_bits(innerbits, innermask), ' */\n')
1162 s.output_code(i + 4, extracted, innerbits, innermask)
1163 output(ind, '}\n')
1164 output(ind, 'return insn;\n')
1165# end SizeTree
1166
1167class SizeLeaf:
1168 """Class representing a leaf node in a size decode tree"""
1169
1170 def __init__(self, m, w):
1171 self.mask = m
1172 self.width = w
1173
1174 def str1(self, i):
Richard Hendersonc7cefe62021-04-28 16:27:56 -07001175 return str_indent(i) + whex(self.mask)
Richard Henderson70e07112019-01-31 11:34:11 -08001176
1177 def __str__(self):
1178 return self.str1(0)
1179
1180 def output_code(self, i, extracted, outerbits, outermask):
1181 global decode_function
1182 ind = str_indent(i)
1183
1184 # If we need to load more bytes, do so now.
1185 if extracted < self.width:
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001186 output(ind, f'insn = {decode_function}_load_bytes',
1187 f'(ctx, insn, {extracted // 8}, {self.width // 8});\n')
Richard Henderson70e07112019-01-31 11:34:11 -08001188 extracted = self.width
1189 output(ind, 'return insn;\n')
1190# end SizeLeaf
1191
1192
1193def build_size_tree(pats, width, outerbits, outermask):
1194 global insnwidth
1195
1196 # Collect the mask of bits that are fixed in this width
1197 innermask = 0xff << (insnwidth - width)
1198 innermask &= ~outermask
1199 minwidth = None
1200 onewidth = True
1201 for i in pats:
1202 innermask &= i.fixedmask
1203 if minwidth is None:
1204 minwidth = i.width
1205 elif minwidth != i.width:
1206 onewidth = False;
1207 if minwidth < i.width:
1208 minwidth = i.width
1209
1210 if onewidth:
1211 return SizeLeaf(innermask, minwidth)
1212
1213 if innermask == 0:
1214 if width < minwidth:
1215 return build_size_tree(pats, width + 8, outerbits, outermask)
1216
1217 pnames = []
1218 for p in pats:
1219 pnames.append(p.name + ':' + p.file + ':' + str(p.lineno))
1220 error_with_file(pats[0].file, pats[0].lineno,
Richard Henderson9f6e2b42021-04-28 16:37:02 -07001221 f'overlapping patterns size {width}:', pnames)
Richard Henderson70e07112019-01-31 11:34:11 -08001222
1223 bins = {}
1224 for i in pats:
1225 fb = i.fixedbits & innermask
1226 if fb in bins:
1227 bins[fb].append(i)
1228 else:
1229 bins[fb] = [i]
1230
1231 fullmask = outermask | innermask
1232 lens = sorted(bins.keys())
1233 if len(lens) == 1:
1234 b = lens[0]
1235 return build_size_tree(bins[b], width + 8, b | outerbits, fullmask)
1236
1237 r = SizeTree(innermask, width)
1238 for b, l in bins.items():
1239 s = build_size_tree(l, width, b | outerbits, fullmask)
1240 r.subs.append((b, s))
1241 return r
1242# end build_size_tree
1243
1244
Richard Henderson70e07112019-01-31 11:34:11 -08001245def prop_size(tree):
1246 """Propagate minimum widths up the decode size tree"""
1247
1248 if isinstance(tree, SizeTree):
1249 min = None
1250 for (b, s) in tree.subs:
1251 width = prop_size(s)
1252 if min is None or min > width:
1253 min = width
1254 assert min >= tree.width
1255 tree.width = min
1256 else:
1257 min = tree.width
1258 return min
1259# end prop_size
1260
1261
Richard Henderson568ae7e2017-12-07 12:44:09 -08001262def main():
1263 global arguments
1264 global formats
Richard Henderson0eff2df2019-02-23 11:35:36 -08001265 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -08001266 global translate_scope
1267 global translate_prefix
1268 global output_fd
1269 global output_file
1270 global input_file
1271 global insnwidth
1272 global insntype
Bastian Koppelmann83d7c402018-03-19 12:58:46 +01001273 global insnmask
Richard Hendersonabd04f92018-10-23 10:26:25 +01001274 global decode_function
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +00001275 global bitop_width
Richard Henderson17560e92019-01-30 18:01:29 -08001276 global variablewidth
Richard Hendersonc6920792019-08-09 08:12:50 -07001277 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -08001278
Richard Henderson568ae7e2017-12-07 12:44:09 -08001279 decode_scope = 'static '
1280
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001281 long_opts = ['decode=', 'translate=', 'output=', 'insnwidth=',
Richard Henderson17560e92019-01-30 18:01:29 -08001282 'static-decode=', 'varinsnwidth=']
Richard Henderson568ae7e2017-12-07 12:44:09 -08001283 try:
Paolo Bonziniabff1ab2020-08-07 12:10:23 +02001284 (opts, args) = getopt.gnu_getopt(sys.argv[1:], 'o:vw:', long_opts)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001285 except getopt.GetoptError as err:
1286 error(0, err)
1287 for o, a in opts:
1288 if o in ('-o', '--output'):
1289 output_file = a
1290 elif o == '--decode':
1291 decode_function = a
1292 decode_scope = ''
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001293 elif o == '--static-decode':
1294 decode_function = a
Richard Henderson568ae7e2017-12-07 12:44:09 -08001295 elif o == '--translate':
1296 translate_prefix = a
1297 translate_scope = ''
Richard Henderson17560e92019-01-30 18:01:29 -08001298 elif o in ('-w', '--insnwidth', '--varinsnwidth'):
1299 if o == '--varinsnwidth':
1300 variablewidth = True
Richard Henderson568ae7e2017-12-07 12:44:09 -08001301 insnwidth = int(a)
1302 if insnwidth == 16:
1303 insntype = 'uint16_t'
1304 insnmask = 0xffff
Luis Fernando Fujita Pires60c425f2021-04-07 22:18:49 +00001305 elif insnwidth == 64:
1306 insntype = 'uint64_t'
1307 insnmask = 0xffffffffffffffff
1308 bitop_width = 64
Richard Henderson568ae7e2017-12-07 12:44:09 -08001309 elif insnwidth != 32:
1310 error(0, 'cannot handle insns of width', insnwidth)
1311 else:
1312 assert False, 'unhandled option'
1313
1314 if len(args) < 1:
1315 error(0, 'missing input file')
Richard Henderson08561fc2020-05-17 10:14:11 -07001316
1317 toppat = ExcMultiPattern(0)
1318
Richard Henderson6699ae62018-10-26 14:59:43 +01001319 for filename in args:
1320 input_file = filename
Philippe Mathieu-Daudé4caceca2021-01-10 01:02:40 +01001321 f = open(filename, 'rt', encoding='utf-8')
Richard Henderson08561fc2020-05-17 10:14:11 -07001322 parse_file(f, toppat)
Richard Henderson6699ae62018-10-26 14:59:43 +01001323 f.close()
Richard Henderson568ae7e2017-12-07 12:44:09 -08001324
Richard Henderson08561fc2020-05-17 10:14:11 -07001325 # We do not want to compute masks for toppat, because those masks
1326 # are used as a starting point for build_tree. For toppat, we must
1327 # insist that decode begins from naught.
1328 for i in toppat.pats:
1329 i.prop_masks()
Richard Henderson70e07112019-01-31 11:34:11 -08001330
Richard Henderson08561fc2020-05-17 10:14:11 -07001331 toppat.build_tree()
1332 toppat.prop_format()
1333
1334 if variablewidth:
1335 for i in toppat.pats:
1336 i.prop_width()
1337 stree = build_size_tree(toppat.pats, 8, 0, 0)
1338 prop_size(stree)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001339
1340 if output_file:
Philippe Mathieu-Daudé4caceca2021-01-10 01:02:40 +01001341 output_fd = open(output_file, 'wt', encoding='utf-8')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001342 else:
Philippe Mathieu-Daudé4caceca2021-01-10 01:02:40 +01001343 output_fd = io.TextIOWrapper(sys.stdout.buffer,
1344 encoding=sys.stdout.encoding,
1345 errors="ignore")
Richard Henderson568ae7e2017-12-07 12:44:09 -08001346
1347 output_autogen()
1348 for n in sorted(arguments.keys()):
1349 f = arguments[n]
1350 f.output_def()
1351
1352 # A single translate function can be invoked for different patterns.
1353 # Make sure that the argument sets are the same, and declare the
1354 # function only once.
Richard Hendersonc6920792019-08-09 08:12:50 -07001355 #
1356 # If we're sharing formats, we're likely also sharing trans_* functions,
1357 # but we can't tell which ones. Prevent issues from the compiler by
1358 # suppressing redundant declaration warnings.
1359 if anyextern:
Thomas Huth7aa12aa2020-07-08 20:19:44 +02001360 output("#pragma GCC diagnostic push\n",
1361 "#pragma GCC diagnostic ignored \"-Wredundant-decls\"\n",
1362 "#ifdef __clang__\n"
Richard Hendersonc6920792019-08-09 08:12:50 -07001363 "# pragma GCC diagnostic ignored \"-Wtypedef-redefinition\"\n",
Richard Hendersonc6920792019-08-09 08:12:50 -07001364 "#endif\n\n")
1365
Richard Henderson568ae7e2017-12-07 12:44:09 -08001366 out_pats = {}
Richard Henderson0eff2df2019-02-23 11:35:36 -08001367 for i in allpatterns:
Richard Henderson568ae7e2017-12-07 12:44:09 -08001368 if i.name in out_pats:
1369 p = out_pats[i.name]
1370 if i.base.base != p.base.base:
1371 error(0, i.name, ' has conflicting argument sets')
1372 else:
1373 i.output_decl()
1374 out_pats[i.name] = i
1375 output('\n')
1376
Richard Hendersonc6920792019-08-09 08:12:50 -07001377 if anyextern:
Thomas Huth7aa12aa2020-07-08 20:19:44 +02001378 output("#pragma GCC diagnostic pop\n\n")
Richard Hendersonc6920792019-08-09 08:12:50 -07001379
Richard Henderson568ae7e2017-12-07 12:44:09 -08001380 for n in sorted(formats.keys()):
1381 f = formats[n]
1382 f.output_extract()
1383
1384 output(decode_scope, 'bool ', decode_function,
1385 '(DisasContext *ctx, ', insntype, ' insn)\n{\n')
1386
1387 i4 = str_indent(4)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001388
Richard Henderson82bfac12019-02-27 21:37:32 -08001389 if len(allpatterns) != 0:
1390 output(i4, 'union {\n')
1391 for n in sorted(arguments.keys()):
1392 f = arguments[n]
1393 output(i4, i4, f.struct_name(), ' f_', f.name, ';\n')
1394 output(i4, '} u;\n\n')
Richard Henderson08561fc2020-05-17 10:14:11 -07001395 toppat.output_code(4, False, 0, 0)
Richard Henderson82bfac12019-02-27 21:37:32 -08001396
Richard Hendersoneb6b87f2019-02-23 08:57:46 -08001397 output(i4, 'return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001398 output('}\n')
1399
Richard Henderson70e07112019-01-31 11:34:11 -08001400 if variablewidth:
1401 output('\n', decode_scope, insntype, ' ', decode_function,
1402 '_load(DisasContext *ctx)\n{\n',
1403 ' ', insntype, ' insn = 0;\n\n')
1404 stree.output_code(4, 0, 0, 0)
1405 output('}\n')
1406
Richard Henderson568ae7e2017-12-07 12:44:09 -08001407 if output_file:
1408 output_fd.close()
1409# end main
1410
1411
1412if __name__ == '__main__':
1413 main()