blob: 3307c74c303a0d7ed7b496c0a9ffaa23fa143da4 [file] [log] [blame]
Philippe Mathieu-Daudé3d004a32020-01-30 17:32:25 +01001#!/usr/bin/env python3
Richard Henderson568ae7e2017-12-07 12:44:09 -08002# Copyright (c) 2018 Linaro Limited
3#
4# This library is free software; you can redistribute it and/or
5# modify it under the terms of the GNU Lesser General Public
6# License as published by the Free Software Foundation; either
7# version 2 of the License, or (at your option) any later version.
8#
9# This library is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12# Lesser General Public License for more details.
13#
14# You should have received a copy of the GNU Lesser General Public
15# License along with this library; if not, see <http://www.gnu.org/licenses/>.
16#
17
18#
19# Generate a decoding tree from a specification file.
Richard Henderson3fdbf5d2019-02-23 13:00:10 -080020# See the syntax and semantics in docs/devel/decodetree.rst.
Richard Henderson568ae7e2017-12-07 12:44:09 -080021#
22
Richard Henderson568ae7e2017-12-07 12:44:09 -080023import os
24import re
25import sys
26import getopt
Richard Henderson568ae7e2017-12-07 12:44:09 -080027
28insnwidth = 32
29insnmask = 0xffffffff
Richard Henderson17560e92019-01-30 18:01:29 -080030variablewidth = False
Richard Henderson568ae7e2017-12-07 12:44:09 -080031fields = {}
32arguments = {}
33formats = {}
34patterns = []
Richard Henderson0eff2df2019-02-23 11:35:36 -080035allpatterns = []
Richard Hendersonc6920792019-08-09 08:12:50 -070036anyextern = False
Richard Henderson568ae7e2017-12-07 12:44:09 -080037
38translate_prefix = 'trans'
39translate_scope = 'static '
40input_file = ''
41output_file = None
42output_fd = None
43insntype = 'uint32_t'
Richard Hendersonabd04f92018-10-23 10:26:25 +010044decode_function = 'decode'
Richard Henderson568ae7e2017-12-07 12:44:09 -080045
46re_ident = '[a-zA-Z][a-zA-Z0-9_]*'
47
48
Richard Henderson6699ae62018-10-26 14:59:43 +010049def error_with_file(file, lineno, *args):
Richard Henderson568ae7e2017-12-07 12:44:09 -080050 """Print an error message from file:line and args and exit."""
51 global output_file
52 global output_fd
53
Richard Henderson2fd51b12020-05-15 14:48:54 -070054 prefix = ''
55 if file:
56 prefix += '{0}:'.format(file)
Richard Henderson568ae7e2017-12-07 12:44:09 -080057 if lineno:
Richard Henderson2fd51b12020-05-15 14:48:54 -070058 prefix += '{0}:'.format(lineno)
59 if prefix:
60 prefix += ' '
61 print(prefix, end='error: ', file=sys.stderr)
62 print(*args, file=sys.stderr)
63
Richard Henderson568ae7e2017-12-07 12:44:09 -080064 if output_file and output_fd:
65 output_fd.close()
66 os.remove(output_file)
67 exit(1)
Richard Henderson2fd51b12020-05-15 14:48:54 -070068# end error_with_file
69
Richard Henderson568ae7e2017-12-07 12:44:09 -080070
Richard Henderson6699ae62018-10-26 14:59:43 +010071def error(lineno, *args):
Richard Henderson2fd51b12020-05-15 14:48:54 -070072 error_with_file(input_file, lineno, *args)
73# end error
74
Richard Henderson568ae7e2017-12-07 12:44:09 -080075
76def output(*args):
77 global output_fd
78 for a in args:
79 output_fd.write(a)
80
81
Richard Henderson568ae7e2017-12-07 12:44:09 -080082def output_autogen():
83 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
84
85
86def str_indent(c):
87 """Return a string with C spaces"""
88 return ' ' * c
89
90
91def str_fields(fields):
92 """Return a string uniquely identifing FIELDS"""
93 r = ''
94 for n in sorted(fields.keys()):
95 r += '_' + n
96 return r[1:]
97
98
99def str_match_bits(bits, mask):
100 """Return a string pretty-printing BITS/MASK"""
101 global insnwidth
102
103 i = 1 << (insnwidth - 1)
104 space = 0x01010100
105 r = ''
106 while i != 0:
107 if i & mask:
108 if i & bits:
109 r += '1'
110 else:
111 r += '0'
112 else:
113 r += '.'
114 if i & space:
115 r += ' '
116 i >>= 1
117 return r
118
119
120def is_pow2(x):
121 """Return true iff X is equal to a power of 2."""
122 return (x & (x - 1)) == 0
123
124
125def ctz(x):
126 """Return the number of times 2 factors into X."""
Richard Hendersonb44b3442020-05-16 13:15:02 -0700127 assert x != 0
Richard Henderson568ae7e2017-12-07 12:44:09 -0800128 r = 0
129 while ((x >> r) & 1) == 0:
130 r += 1
131 return r
132
133
134def is_contiguous(bits):
Richard Hendersonb44b3442020-05-16 13:15:02 -0700135 if bits == 0:
136 return -1
Richard Henderson568ae7e2017-12-07 12:44:09 -0800137 shift = ctz(bits)
138 if is_pow2((bits >> shift) + 1):
139 return shift
140 else:
141 return -1
142
143
144def eq_fields_for_args(flds_a, flds_b):
145 if len(flds_a) != len(flds_b):
146 return False
147 for k, a in flds_a.items():
148 if k not in flds_b:
149 return False
150 return True
151
152
153def eq_fields_for_fmts(flds_a, flds_b):
154 if len(flds_a) != len(flds_b):
155 return False
156 for k, a in flds_a.items():
157 if k not in flds_b:
158 return False
159 b = flds_b[k]
160 if a.__class__ != b.__class__ or a != b:
161 return False
162 return True
163
164
165class Field:
166 """Class representing a simple instruction field"""
167 def __init__(self, sign, pos, len):
168 self.sign = sign
169 self.pos = pos
170 self.len = len
171 self.mask = ((1 << len) - 1) << pos
172
173 def __str__(self):
174 if self.sign:
175 s = 's'
176 else:
177 s = ''
Cleber Rosacbcdf1a2018-10-04 12:18:50 -0400178 return str(self.pos) + ':' + s + str(self.len)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800179
180 def str_extract(self):
181 if self.sign:
182 extr = 'sextract32'
183 else:
184 extr = 'extract32'
185 return '{0}(insn, {1}, {2})'.format(extr, self.pos, self.len)
186
187 def __eq__(self, other):
Richard Henderson2c7d4422019-06-11 16:39:41 +0100188 return self.sign == other.sign and self.mask == other.mask
Richard Henderson568ae7e2017-12-07 12:44:09 -0800189
190 def __ne__(self, other):
191 return not self.__eq__(other)
192# end Field
193
194
195class MultiField:
196 """Class representing a compound instruction field"""
197 def __init__(self, subs, mask):
198 self.subs = subs
199 self.sign = subs[0].sign
200 self.mask = mask
201
202 def __str__(self):
203 return str(self.subs)
204
205 def str_extract(self):
206 ret = '0'
207 pos = 0
208 for f in reversed(self.subs):
209 if pos == 0:
210 ret = f.str_extract()
211 else:
212 ret = 'deposit32({0}, {1}, {2}, {3})' \
213 .format(ret, pos, 32 - pos, f.str_extract())
214 pos += f.len
215 return ret
216
217 def __ne__(self, other):
218 if len(self.subs) != len(other.subs):
219 return True
220 for a, b in zip(self.subs, other.subs):
221 if a.__class__ != b.__class__ or a != b:
222 return True
223 return False
224
225 def __eq__(self, other):
226 return not self.__ne__(other)
227# end MultiField
228
229
230class ConstField:
231 """Class representing an argument field with constant value"""
232 def __init__(self, value):
233 self.value = value
234 self.mask = 0
235 self.sign = value < 0
236
237 def __str__(self):
238 return str(self.value)
239
240 def str_extract(self):
241 return str(self.value)
242
243 def __cmp__(self, other):
244 return self.value - other.value
245# end ConstField
246
247
248class FunctionField:
Richard Henderson94597b62019-07-22 17:02:56 -0700249 """Class representing a field passed through a function"""
Richard Henderson568ae7e2017-12-07 12:44:09 -0800250 def __init__(self, func, base):
251 self.mask = base.mask
252 self.sign = base.sign
253 self.base = base
254 self.func = func
255
256 def __str__(self):
257 return self.func + '(' + str(self.base) + ')'
258
259 def str_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700260 return self.func + '(ctx, ' + self.base.str_extract() + ')'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800261
262 def __eq__(self, other):
263 return self.func == other.func and self.base == other.base
264
265 def __ne__(self, other):
266 return not self.__eq__(other)
267# end FunctionField
268
269
Richard Henderson94597b62019-07-22 17:02:56 -0700270class ParameterField:
271 """Class representing a pseudo-field read from a function"""
272 def __init__(self, func):
273 self.mask = 0
274 self.sign = 0
275 self.func = func
276
277 def __str__(self):
278 return self.func
279
280 def str_extract(self):
281 return self.func + '(ctx)'
282
283 def __eq__(self, other):
284 return self.func == other.func
285
286 def __ne__(self, other):
287 return not self.__eq__(other)
288# end ParameterField
289
290
Richard Henderson568ae7e2017-12-07 12:44:09 -0800291class Arguments:
292 """Class representing the extracted fields of a format"""
Richard Hendersonabd04f92018-10-23 10:26:25 +0100293 def __init__(self, nm, flds, extern):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800294 self.name = nm
Richard Hendersonabd04f92018-10-23 10:26:25 +0100295 self.extern = extern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800296 self.fields = sorted(flds)
297
298 def __str__(self):
299 return self.name + ' ' + str(self.fields)
300
301 def struct_name(self):
302 return 'arg_' + self.name
303
304 def output_def(self):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100305 if not self.extern:
306 output('typedef struct {\n')
307 for n in self.fields:
308 output(' int ', n, ';\n')
309 output('} ', self.struct_name(), ';\n\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800310# end Arguments
311
312
313class General:
314 """Common code between instruction formats and instruction patterns"""
Richard Henderson17560e92019-01-30 18:01:29 -0800315 def __init__(self, name, lineno, base, fixb, fixm, udfm, fldm, flds, w):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800316 self.name = name
Richard Henderson6699ae62018-10-26 14:59:43 +0100317 self.file = input_file
Richard Henderson568ae7e2017-12-07 12:44:09 -0800318 self.lineno = lineno
319 self.base = base
320 self.fixedbits = fixb
321 self.fixedmask = fixm
322 self.undefmask = udfm
323 self.fieldmask = fldm
324 self.fields = flds
Richard Henderson17560e92019-01-30 18:01:29 -0800325 self.width = w
Richard Henderson568ae7e2017-12-07 12:44:09 -0800326
327 def __str__(self):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800328 return self.name + ' ' + str_match_bits(self.fixedbits, self.fixedmask)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800329
330 def str1(self, i):
331 return str_indent(i) + self.__str__()
332# end General
333
334
335class Format(General):
336 """Class representing an instruction format"""
337
338 def extract_name(self):
Richard Henderson71ecf792019-02-28 14:45:50 -0800339 global decode_function
340 return decode_function + '_extract_' + self.name
Richard Henderson568ae7e2017-12-07 12:44:09 -0800341
342 def output_extract(self):
Richard Henderson451e4ff2019-03-20 19:21:31 -0700343 output('static void ', self.extract_name(), '(DisasContext *ctx, ',
Richard Henderson568ae7e2017-12-07 12:44:09 -0800344 self.base.struct_name(), ' *a, ', insntype, ' insn)\n{\n')
345 for n, f in self.fields.items():
346 output(' a->', n, ' = ', f.str_extract(), ';\n')
347 output('}\n\n')
348# end Format
349
350
351class Pattern(General):
352 """Class representing an instruction pattern"""
353
354 def output_decl(self):
355 global translate_scope
356 global translate_prefix
357 output('typedef ', self.base.base.struct_name(),
358 ' arg_', self.name, ';\n')
Richard Henderson76805592018-03-02 10:45:35 +0000359 output(translate_scope, 'bool ', translate_prefix, '_', self.name,
Richard Henderson3a7be552018-10-23 11:05:27 +0100360 '(DisasContext *ctx, arg_', self.name, ' *a);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800361
362 def output_code(self, i, extracted, outerbits, outermask):
363 global translate_prefix
364 ind = str_indent(i)
365 arg = self.base.base.name
Richard Henderson6699ae62018-10-26 14:59:43 +0100366 output(ind, '/* ', self.file, ':', str(self.lineno), ' */\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800367 if not extracted:
Richard Henderson451e4ff2019-03-20 19:21:31 -0700368 output(ind, self.base.extract_name(),
369 '(ctx, &u.f_', arg, ', insn);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800370 for n, f in self.fields.items():
371 output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n')
Richard Hendersoneb6b87f2019-02-23 08:57:46 -0800372 output(ind, 'if (', translate_prefix, '_', self.name,
373 '(ctx, &u.f_', arg, ')) return true;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800374# end Pattern
375
376
Richard Hendersondf630442020-05-16 11:19:45 -0700377class MultiPattern(General):
378 """Class representing a set of instruction patterns"""
379
380 def __init__(self, lineno, pats):
381 self.file = input_file
382 self.lineno = lineno
383 self.pats = pats
384 self.base = None
385 self.fixedbits = 0
386 self.fixedmask = 0
387 self.undefmask = 0
388 self.width = None
389
390 def __str__(self):
391 r = 'group'
392 if self.fixedbits is not None:
393 r += ' ' + str_match_bits(self.fixedbits, self.fixedmask)
394 return r
395
396 def output_decl(self):
397 for p in self.pats:
398 p.output_decl()
399# end MultiPattern
400
401
402class IncMultiPattern(MultiPattern):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800403 """Class representing an overlapping set of instruction patterns"""
404
Richard Henderson17560e92019-01-30 18:01:29 -0800405 def __init__(self, lineno, pats, fixb, fixm, udfm, w):
Richard Henderson0eff2df2019-02-23 11:35:36 -0800406 self.file = input_file
407 self.lineno = lineno
408 self.pats = pats
409 self.base = None
410 self.fixedbits = fixb
411 self.fixedmask = fixm
412 self.undefmask = udfm
Richard Henderson17560e92019-01-30 18:01:29 -0800413 self.width = w
Richard Henderson0eff2df2019-02-23 11:35:36 -0800414
Richard Henderson0eff2df2019-02-23 11:35:36 -0800415 def output_code(self, i, extracted, outerbits, outermask):
416 global translate_prefix
417 ind = str_indent(i)
418 for p in self.pats:
419 if outermask != p.fixedmask:
420 innermask = p.fixedmask & ~outermask
421 innerbits = p.fixedbits & ~outermask
422 output(ind, 'if ((insn & ',
423 '0x{0:08x}) == 0x{1:08x}'.format(innermask, innerbits),
424 ') {\n')
425 output(ind, ' /* ',
426 str_match_bits(p.fixedbits, p.fixedmask), ' */\n')
427 p.output_code(i + 4, extracted, p.fixedbits, p.fixedmask)
428 output(ind, '}\n')
429 else:
430 p.output_code(i, extracted, p.fixedbits, p.fixedmask)
Richard Henderson040145c2020-05-16 10:50:43 -0700431#end IncMultiPattern
Richard Henderson0eff2df2019-02-23 11:35:36 -0800432
433
Richard Henderson568ae7e2017-12-07 12:44:09 -0800434def parse_field(lineno, name, toks):
435 """Parse one instruction field from TOKS at LINENO"""
436 global fields
437 global re_ident
438 global insnwidth
439
440 # A "simple" field will have only one entry;
441 # a "multifield" will have several.
442 subs = []
443 width = 0
444 func = None
445 for t in toks:
John Snow2d110c12020-05-13 23:52:30 -0400446 if re.fullmatch('!function=' + re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800447 if func:
448 error(lineno, 'duplicate function')
449 func = t.split('=')
450 func = func[1]
451 continue
452
John Snow2d110c12020-05-13 23:52:30 -0400453 if re.fullmatch('[0-9]+:s[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800454 # Signed field extract
455 subtoks = t.split(':s')
456 sign = True
John Snow2d110c12020-05-13 23:52:30 -0400457 elif re.fullmatch('[0-9]+:[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800458 # Unsigned field extract
459 subtoks = t.split(':')
460 sign = False
461 else:
462 error(lineno, 'invalid field token "{0}"'.format(t))
463 po = int(subtoks[0])
464 le = int(subtoks[1])
465 if po + le > insnwidth:
466 error(lineno, 'field {0} too large'.format(t))
467 f = Field(sign, po, le)
468 subs.append(f)
469 width += le
470
471 if width > insnwidth:
472 error(lineno, 'field too large')
Richard Henderson94597b62019-07-22 17:02:56 -0700473 if len(subs) == 0:
474 if func:
475 f = ParameterField(func)
476 else:
477 error(lineno, 'field with no value')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800478 else:
Richard Henderson94597b62019-07-22 17:02:56 -0700479 if len(subs) == 1:
480 f = subs[0]
481 else:
482 mask = 0
483 for s in subs:
484 if mask & s.mask:
485 error(lineno, 'field components overlap')
486 mask |= s.mask
487 f = MultiField(subs, mask)
488 if func:
489 f = FunctionField(func, f)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800490
491 if name in fields:
492 error(lineno, 'duplicate field', name)
493 fields[name] = f
494# end parse_field
495
496
497def parse_arguments(lineno, name, toks):
498 """Parse one argument set from TOKS at LINENO"""
499 global arguments
500 global re_ident
Richard Hendersonc6920792019-08-09 08:12:50 -0700501 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800502
503 flds = []
Richard Hendersonabd04f92018-10-23 10:26:25 +0100504 extern = False
Richard Henderson568ae7e2017-12-07 12:44:09 -0800505 for t in toks:
John Snow2d110c12020-05-13 23:52:30 -0400506 if re.fullmatch('!extern', t):
Richard Hendersonabd04f92018-10-23 10:26:25 +0100507 extern = True
Richard Hendersonc6920792019-08-09 08:12:50 -0700508 anyextern = True
Richard Hendersonabd04f92018-10-23 10:26:25 +0100509 continue
John Snow2d110c12020-05-13 23:52:30 -0400510 if not re.fullmatch(re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800511 error(lineno, 'invalid argument set token "{0}"'.format(t))
512 if t in flds:
513 error(lineno, 'duplicate argument "{0}"'.format(t))
514 flds.append(t)
515
516 if name in arguments:
517 error(lineno, 'duplicate argument set', name)
Richard Hendersonabd04f92018-10-23 10:26:25 +0100518 arguments[name] = Arguments(name, flds, extern)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800519# end parse_arguments
520
521
522def lookup_field(lineno, name):
523 global fields
524 if name in fields:
525 return fields[name]
526 error(lineno, 'undefined field', name)
527
528
529def add_field(lineno, flds, new_name, f):
530 if new_name in flds:
531 error(lineno, 'duplicate field', new_name)
532 flds[new_name] = f
533 return flds
534
535
536def add_field_byname(lineno, flds, new_name, old_name):
537 return add_field(lineno, flds, new_name, lookup_field(lineno, old_name))
538
539
540def infer_argument_set(flds):
541 global arguments
Richard Hendersonabd04f92018-10-23 10:26:25 +0100542 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800543
544 for arg in arguments.values():
545 if eq_fields_for_args(flds, arg.fields):
546 return arg
547
Richard Hendersonabd04f92018-10-23 10:26:25 +0100548 name = decode_function + str(len(arguments))
549 arg = Arguments(name, flds.keys(), False)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800550 arguments[name] = arg
551 return arg
552
553
Richard Henderson17560e92019-01-30 18:01:29 -0800554def infer_format(arg, fieldmask, flds, width):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800555 global arguments
556 global formats
Richard Hendersonabd04f92018-10-23 10:26:25 +0100557 global decode_function
Richard Henderson568ae7e2017-12-07 12:44:09 -0800558
559 const_flds = {}
560 var_flds = {}
561 for n, c in flds.items():
562 if c is ConstField:
563 const_flds[n] = c
564 else:
565 var_flds[n] = c
566
567 # Look for an existing format with the same argument set and fields
568 for fmt in formats.values():
569 if arg and fmt.base != arg:
570 continue
571 if fieldmask != fmt.fieldmask:
572 continue
Richard Henderson17560e92019-01-30 18:01:29 -0800573 if width != fmt.width:
574 continue
Richard Henderson568ae7e2017-12-07 12:44:09 -0800575 if not eq_fields_for_fmts(flds, fmt.fields):
576 continue
577 return (fmt, const_flds)
578
Richard Hendersonabd04f92018-10-23 10:26:25 +0100579 name = decode_function + '_Fmt_' + str(len(formats))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800580 if not arg:
581 arg = infer_argument_set(flds)
582
Richard Henderson17560e92019-01-30 18:01:29 -0800583 fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800584 formats[name] = fmt
585
586 return (fmt, const_flds)
587# end infer_format
588
589
590def parse_generic(lineno, is_format, name, toks):
591 """Parse one instruction format from TOKS at LINENO"""
592 global fields
593 global arguments
594 global formats
595 global patterns
Richard Henderson0eff2df2019-02-23 11:35:36 -0800596 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -0800597 global re_ident
598 global insnwidth
599 global insnmask
Richard Henderson17560e92019-01-30 18:01:29 -0800600 global variablewidth
Richard Henderson568ae7e2017-12-07 12:44:09 -0800601
602 fixedmask = 0
603 fixedbits = 0
604 undefmask = 0
605 width = 0
606 flds = {}
607 arg = None
608 fmt = None
609 for t in toks:
610 # '&Foo' gives a format an explcit argument set.
611 if t[0] == '&':
612 tt = t[1:]
613 if arg:
614 error(lineno, 'multiple argument sets')
615 if tt in arguments:
616 arg = arguments[tt]
617 else:
618 error(lineno, 'undefined argument set', t)
619 continue
620
621 # '@Foo' gives a pattern an explicit format.
622 if t[0] == '@':
623 tt = t[1:]
624 if fmt:
625 error(lineno, 'multiple formats')
626 if tt in formats:
627 fmt = formats[tt]
628 else:
629 error(lineno, 'undefined format', t)
630 continue
631
632 # '%Foo' imports a field.
633 if t[0] == '%':
634 tt = t[1:]
635 flds = add_field_byname(lineno, flds, tt, tt)
636 continue
637
638 # 'Foo=%Bar' imports a field with a different name.
John Snow2d110c12020-05-13 23:52:30 -0400639 if re.fullmatch(re_ident + '=%' + re_ident, t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800640 (fname, iname) = t.split('=%')
641 flds = add_field_byname(lineno, flds, fname, iname)
642 continue
643
644 # 'Foo=number' sets an argument field to a constant value
John Snow2d110c12020-05-13 23:52:30 -0400645 if re.fullmatch(re_ident + '=[+-]?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800646 (fname, value) = t.split('=')
647 value = int(value)
648 flds = add_field(lineno, flds, fname, ConstField(value))
649 continue
650
651 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
652 # required ones, or dont-cares.
John Snow2d110c12020-05-13 23:52:30 -0400653 if re.fullmatch('[01.-]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800654 shift = len(t)
655 fms = t.replace('0', '1')
656 fms = fms.replace('.', '0')
657 fms = fms.replace('-', '0')
658 fbs = t.replace('.', '0')
659 fbs = fbs.replace('-', '0')
660 ubm = t.replace('1', '0')
661 ubm = ubm.replace('.', '0')
662 ubm = ubm.replace('-', '1')
663 fms = int(fms, 2)
664 fbs = int(fbs, 2)
665 ubm = int(ubm, 2)
666 fixedbits = (fixedbits << shift) | fbs
667 fixedmask = (fixedmask << shift) | fms
668 undefmask = (undefmask << shift) | ubm
669 # Otherwise, fieldname:fieldwidth
John Snow2d110c12020-05-13 23:52:30 -0400670 elif re.fullmatch(re_ident + ':s?[0-9]+', t):
Richard Henderson568ae7e2017-12-07 12:44:09 -0800671 (fname, flen) = t.split(':')
672 sign = False
673 if flen[0] == 's':
674 sign = True
675 flen = flen[1:]
676 shift = int(flen, 10)
Richard Henderson2decfc92019-03-05 15:34:41 -0800677 if shift + width > insnwidth:
678 error(lineno, 'field {0} exceeds insnwidth'.format(fname))
Richard Henderson568ae7e2017-12-07 12:44:09 -0800679 f = Field(sign, insnwidth - width - shift, shift)
680 flds = add_field(lineno, flds, fname, f)
681 fixedbits <<= shift
682 fixedmask <<= shift
683 undefmask <<= shift
684 else:
685 error(lineno, 'invalid token "{0}"'.format(t))
686 width += shift
687
Richard Henderson17560e92019-01-30 18:01:29 -0800688 if variablewidth and width < insnwidth and width % 8 == 0:
689 shift = insnwidth - width
690 fixedbits <<= shift
691 fixedmask <<= shift
692 undefmask <<= shift
693 undefmask |= (1 << shift) - 1
694
Richard Henderson568ae7e2017-12-07 12:44:09 -0800695 # We should have filled in all of the bits of the instruction.
Richard Henderson17560e92019-01-30 18:01:29 -0800696 elif not (is_format and width == 0) and width != insnwidth:
Richard Henderson568ae7e2017-12-07 12:44:09 -0800697 error(lineno, 'definition has {0} bits'.format(width))
698
699 # Do not check for fields overlaping fields; one valid usage
700 # is to be able to duplicate fields via import.
701 fieldmask = 0
702 for f in flds.values():
703 fieldmask |= f.mask
704
705 # Fix up what we've parsed to match either a format or a pattern.
706 if is_format:
707 # Formats cannot reference formats.
708 if fmt:
709 error(lineno, 'format referencing format')
710 # If an argument set is given, then there should be no fields
711 # without a place to store it.
712 if arg:
713 for f in flds.keys():
714 if f not in arg.fields:
715 error(lineno, 'field {0} not in argument set {1}'
716 .format(f, arg.name))
717 else:
718 arg = infer_argument_set(flds)
719 if name in formats:
720 error(lineno, 'duplicate format name', name)
721 fmt = Format(name, lineno, arg, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800722 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800723 formats[name] = fmt
724 else:
725 # Patterns can reference a format ...
726 if fmt:
727 # ... but not an argument simultaneously
728 if arg:
729 error(lineno, 'pattern specifies both format and argument set')
730 if fixedmask & fmt.fixedmask:
731 error(lineno, 'pattern fixed bits overlap format fixed bits')
Richard Henderson17560e92019-01-30 18:01:29 -0800732 if width != fmt.width:
733 error(lineno, 'pattern uses format of different width')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800734 fieldmask |= fmt.fieldmask
735 fixedbits |= fmt.fixedbits
736 fixedmask |= fmt.fixedmask
737 undefmask |= fmt.undefmask
738 else:
Richard Henderson17560e92019-01-30 18:01:29 -0800739 (fmt, flds) = infer_format(arg, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800740 arg = fmt.base
741 for f in flds.keys():
742 if f not in arg.fields:
743 error(lineno, 'field {0} not in argument set {1}'
744 .format(f, arg.name))
745 if f in fmt.fields.keys():
746 error(lineno, 'field {0} set by format and pattern'.format(f))
747 for f in arg.fields:
748 if f not in flds.keys() and f not in fmt.fields.keys():
749 error(lineno, 'field {0} not initialized'.format(f))
750 pat = Pattern(name, lineno, fmt, fixedbits, fixedmask,
Richard Henderson17560e92019-01-30 18:01:29 -0800751 undefmask, fieldmask, flds, width)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800752 patterns.append(pat)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800753 allpatterns.append(pat)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800754
755 # Validate the masks that we have assembled.
756 if fieldmask & fixedmask:
757 error(lineno, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
758 .format(fieldmask, fixedmask))
759 if fieldmask & undefmask:
760 error(lineno, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
761 .format(fieldmask, undefmask))
762 if fixedmask & undefmask:
763 error(lineno, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
764 .format(fixedmask, undefmask))
765 if not is_format:
766 allbits = fieldmask | fixedmask | undefmask
767 if allbits != insnmask:
768 error(lineno, 'bits left unspecified (0x{0:08x})'
769 .format(allbits ^ insnmask))
770# end parse_general
771
Richard Henderson040145c2020-05-16 10:50:43 -0700772def build_incmulti_pattern(lineno, pats):
773 """Validate the Patterns going into a IncMultiPattern."""
Richard Henderson0eff2df2019-02-23 11:35:36 -0800774 global patterns
775 global insnmask
776
777 if len(pats) < 2:
778 error(lineno, 'less than two patterns within braces')
779
780 fixedmask = insnmask
781 undefmask = insnmask
782
783 # Collect fixed/undefmask for all of the children.
784 # Move the defining lineno back to that of the first child.
785 for p in pats:
786 fixedmask &= p.fixedmask
787 undefmask &= p.undefmask
788 if p.lineno < lineno:
789 lineno = p.lineno
790
Richard Henderson17560e92019-01-30 18:01:29 -0800791 width = None
792 for p in pats:
793 if width is None:
794 width = p.width
795 elif width != p.width:
796 error(lineno, 'width mismatch in patterns within braces')
797
Richard Henderson0eff2df2019-02-23 11:35:36 -0800798 repeat = True
Richard Hendersonb44b3442020-05-16 13:15:02 -0700799 fixedbits = 0
800 while repeat and fixedmask != 0:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800801 fixedbits = None
802 for p in pats:
803 thisbits = p.fixedbits & fixedmask
804 if fixedbits is None:
805 fixedbits = thisbits
806 elif fixedbits != thisbits:
807 fixedmask &= ~(fixedbits ^ thisbits)
808 break
809 else:
810 repeat = False
811
Richard Henderson040145c2020-05-16 10:50:43 -0700812 mp = IncMultiPattern(lineno, pats, fixedbits, fixedmask, undefmask, width)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800813 patterns.append(mp)
Richard Henderson040145c2020-05-16 10:50:43 -0700814# end build_incmulti_pattern
Richard Henderson568ae7e2017-12-07 12:44:09 -0800815
816def parse_file(f):
817 """Parse all of the patterns within a file"""
818
Richard Henderson0eff2df2019-02-23 11:35:36 -0800819 global patterns
820
Richard Henderson568ae7e2017-12-07 12:44:09 -0800821 # Read all of the lines of the file. Concatenate lines
822 # ending in backslash; discard empty lines and comments.
823 toks = []
824 lineno = 0
Richard Henderson0eff2df2019-02-23 11:35:36 -0800825 nesting = 0
826 saved_pats = []
827
Richard Henderson568ae7e2017-12-07 12:44:09 -0800828 for line in f:
829 lineno += 1
830
Richard Henderson0eff2df2019-02-23 11:35:36 -0800831 # Expand and strip spaces, to find indent.
832 line = line.rstrip()
833 line = line.expandtabs()
834 len1 = len(line)
835 line = line.lstrip()
836 len2 = len(line)
837
Richard Henderson568ae7e2017-12-07 12:44:09 -0800838 # Discard comments
839 end = line.find('#')
840 if end >= 0:
841 line = line[:end]
842
843 t = line.split()
844 if len(toks) != 0:
845 # Next line after continuation
846 toks.extend(t)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800847 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800848 # Allow completely blank lines.
849 if len1 == 0:
850 continue
851 indent = len1 - len2
852 # Empty line due to comment.
853 if len(t) == 0:
854 # Indentation must be correct, even for comment lines.
855 if indent != nesting:
856 error(lineno, 'indentation ', indent, ' != ', nesting)
857 continue
858 start_lineno = lineno
Richard Henderson568ae7e2017-12-07 12:44:09 -0800859 toks = t
860
861 # Continuation?
862 if toks[-1] == '\\':
863 toks.pop()
864 continue
865
Richard Henderson568ae7e2017-12-07 12:44:09 -0800866 name = toks[0]
867 del toks[0]
868
Richard Henderson0eff2df2019-02-23 11:35:36 -0800869 # End nesting?
870 if name == '}':
871 if nesting == 0:
872 error(start_lineno, 'mismatched close brace')
873 if len(toks) != 0:
874 error(start_lineno, 'extra tokens after close brace')
875 nesting -= 2
876 if indent != nesting:
877 error(start_lineno, 'indentation ', indent, ' != ', nesting)
878 pats = patterns
879 patterns = saved_pats.pop()
Richard Henderson040145c2020-05-16 10:50:43 -0700880 build_incmulti_pattern(lineno, pats)
Richard Henderson0eff2df2019-02-23 11:35:36 -0800881 toks = []
882 continue
883
884 # Everything else should have current indentation.
885 if indent != nesting:
886 error(start_lineno, 'indentation ', indent, ' != ', nesting)
887
888 # Start nesting?
889 if name == '{':
890 if len(toks) != 0:
891 error(start_lineno, 'extra tokens after open brace')
892 saved_pats.append(patterns)
893 patterns = []
894 nesting += 2
895 toks = []
896 continue
897
Richard Henderson568ae7e2017-12-07 12:44:09 -0800898 # Determine the type of object needing to be parsed.
899 if name[0] == '%':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800900 parse_field(start_lineno, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800901 elif name[0] == '&':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800902 parse_arguments(start_lineno, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800903 elif name[0] == '@':
Richard Henderson0eff2df2019-02-23 11:35:36 -0800904 parse_generic(start_lineno, True, name[1:], toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800905 else:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800906 parse_generic(start_lineno, False, name, toks)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800907 toks = []
908# end parse_file
909
910
911class Tree:
912 """Class representing a node in a decode tree"""
913
914 def __init__(self, fm, tm):
915 self.fixedmask = fm
916 self.thismask = tm
917 self.subs = []
918 self.base = None
919
920 def str1(self, i):
921 ind = str_indent(i)
922 r = '{0}{1:08x}'.format(ind, self.fixedmask)
923 if self.format:
924 r += ' ' + self.format.name
925 r += ' [\n'
926 for (b, s) in self.subs:
927 r += '{0} {1:08x}:\n'.format(ind, b)
928 r += s.str1(i + 4) + '\n'
929 r += ind + ']'
930 return r
931
932 def __str__(self):
933 return self.str1(0)
934
935 def output_code(self, i, extracted, outerbits, outermask):
936 ind = str_indent(i)
937
938 # If we identified all nodes below have the same format,
939 # extract the fields now.
940 if not extracted and self.base:
941 output(ind, self.base.extract_name(),
Richard Henderson451e4ff2019-03-20 19:21:31 -0700942 '(ctx, &u.f_', self.base.base.name, ', insn);\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800943 extracted = True
944
945 # Attempt to aid the compiler in producing compact switch statements.
946 # If the bits in the mask are contiguous, extract them.
947 sh = is_contiguous(self.thismask)
948 if sh > 0:
949 # Propagate SH down into the local functions.
950 def str_switch(b, sh=sh):
951 return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh)
952
953 def str_case(b, sh=sh):
954 return '0x{0:x}'.format(b >> sh)
955 else:
956 def str_switch(b):
957 return 'insn & 0x{0:08x}'.format(b)
958
959 def str_case(b):
960 return '0x{0:08x}'.format(b)
961
962 output(ind, 'switch (', str_switch(self.thismask), ') {\n')
963 for b, s in sorted(self.subs):
964 assert (self.thismask & ~s.fixedmask) == 0
965 innermask = outermask | self.thismask
966 innerbits = outerbits | b
967 output(ind, 'case ', str_case(b), ':\n')
968 output(ind, ' /* ',
969 str_match_bits(innerbits, innermask), ' */\n')
970 s.output_code(i + 4, extracted, innerbits, innermask)
Richard Hendersoneb6b87f2019-02-23 08:57:46 -0800971 output(ind, ' return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800972 output(ind, '}\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -0800973# end Tree
974
975
976def build_tree(pats, outerbits, outermask):
977 # Find the intersection of all remaining fixedmask.
Philippe Mathieu-Daudé9b3186e2018-12-16 20:07:38 -0800978 innermask = ~outermask & insnmask
Richard Henderson568ae7e2017-12-07 12:44:09 -0800979 for i in pats:
980 innermask &= i.fixedmask
981
982 if innermask == 0:
Richard Hendersonb44b3442020-05-16 13:15:02 -0700983 # Edge condition: One pattern covers the entire insnmask
984 if len(pats) == 1:
985 t = Tree(outermask, innermask)
986 t.subs.append((0, pats[0]))
987 return t
988
Richard Henderson0eff2df2019-02-23 11:35:36 -0800989 text = 'overlapping patterns:'
Richard Henderson568ae7e2017-12-07 12:44:09 -0800990 for p in pats:
Richard Henderson0eff2df2019-02-23 11:35:36 -0800991 text += '\n' + p.file + ':' + str(p.lineno) + ': ' + str(p)
992 error_with_file(pats[0].file, pats[0].lineno, text)
Richard Henderson568ae7e2017-12-07 12:44:09 -0800993
994 fullmask = outermask | innermask
995
996 # Sort each element of pats into the bin selected by the mask.
997 bins = {}
998 for i in pats:
999 fb = i.fixedbits & innermask
1000 if fb in bins:
1001 bins[fb].append(i)
1002 else:
1003 bins[fb] = [i]
1004
1005 # We must recurse if any bin has more than one element or if
1006 # the single element in the bin has not been fully matched.
1007 t = Tree(fullmask, innermask)
1008
1009 for b, l in bins.items():
1010 s = l[0]
1011 if len(l) > 1 or s.fixedmask & ~fullmask != 0:
1012 s = build_tree(l, b | outerbits, fullmask)
1013 t.subs.append((b, s))
1014
1015 return t
1016# end build_tree
1017
1018
Richard Henderson70e07112019-01-31 11:34:11 -08001019class SizeTree:
1020 """Class representing a node in a size decode tree"""
1021
1022 def __init__(self, m, w):
1023 self.mask = m
1024 self.subs = []
1025 self.base = None
1026 self.width = w
1027
1028 def str1(self, i):
1029 ind = str_indent(i)
1030 r = '{0}{1:08x}'.format(ind, self.mask)
1031 r += ' [\n'
1032 for (b, s) in self.subs:
1033 r += '{0} {1:08x}:\n'.format(ind, b)
1034 r += s.str1(i + 4) + '\n'
1035 r += ind + ']'
1036 return r
1037
1038 def __str__(self):
1039 return self.str1(0)
1040
1041 def output_code(self, i, extracted, outerbits, outermask):
1042 ind = str_indent(i)
1043
1044 # If we need to load more bytes to test, do so now.
1045 if extracted < self.width:
1046 output(ind, 'insn = ', decode_function,
1047 '_load_bytes(ctx, insn, {0}, {1});\n'
Philippe Mathieu-Daudéb4123782020-03-30 14:13:45 +02001048 .format(extracted // 8, self.width // 8));
Richard Henderson70e07112019-01-31 11:34:11 -08001049 extracted = self.width
1050
1051 # Attempt to aid the compiler in producing compact switch statements.
1052 # If the bits in the mask are contiguous, extract them.
1053 sh = is_contiguous(self.mask)
1054 if sh > 0:
1055 # Propagate SH down into the local functions.
1056 def str_switch(b, sh=sh):
1057 return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh)
1058
1059 def str_case(b, sh=sh):
1060 return '0x{0:x}'.format(b >> sh)
1061 else:
1062 def str_switch(b):
1063 return 'insn & 0x{0:08x}'.format(b)
1064
1065 def str_case(b):
1066 return '0x{0:08x}'.format(b)
1067
1068 output(ind, 'switch (', str_switch(self.mask), ') {\n')
1069 for b, s in sorted(self.subs):
1070 innermask = outermask | self.mask
1071 innerbits = outerbits | b
1072 output(ind, 'case ', str_case(b), ':\n')
1073 output(ind, ' /* ',
1074 str_match_bits(innerbits, innermask), ' */\n')
1075 s.output_code(i + 4, extracted, innerbits, innermask)
1076 output(ind, '}\n')
1077 output(ind, 'return insn;\n')
1078# end SizeTree
1079
1080class SizeLeaf:
1081 """Class representing a leaf node in a size decode tree"""
1082
1083 def __init__(self, m, w):
1084 self.mask = m
1085 self.width = w
1086
1087 def str1(self, i):
1088 ind = str_indent(i)
1089 return '{0}{1:08x}'.format(ind, self.mask)
1090
1091 def __str__(self):
1092 return self.str1(0)
1093
1094 def output_code(self, i, extracted, outerbits, outermask):
1095 global decode_function
1096 ind = str_indent(i)
1097
1098 # If we need to load more bytes, do so now.
1099 if extracted < self.width:
1100 output(ind, 'insn = ', decode_function,
1101 '_load_bytes(ctx, insn, {0}, {1});\n'
Philippe Mathieu-Daudéb4123782020-03-30 14:13:45 +02001102 .format(extracted // 8, self.width // 8));
Richard Henderson70e07112019-01-31 11:34:11 -08001103 extracted = self.width
1104 output(ind, 'return insn;\n')
1105# end SizeLeaf
1106
1107
1108def build_size_tree(pats, width, outerbits, outermask):
1109 global insnwidth
1110
1111 # Collect the mask of bits that are fixed in this width
1112 innermask = 0xff << (insnwidth - width)
1113 innermask &= ~outermask
1114 minwidth = None
1115 onewidth = True
1116 for i in pats:
1117 innermask &= i.fixedmask
1118 if minwidth is None:
1119 minwidth = i.width
1120 elif minwidth != i.width:
1121 onewidth = False;
1122 if minwidth < i.width:
1123 minwidth = i.width
1124
1125 if onewidth:
1126 return SizeLeaf(innermask, minwidth)
1127
1128 if innermask == 0:
1129 if width < minwidth:
1130 return build_size_tree(pats, width + 8, outerbits, outermask)
1131
1132 pnames = []
1133 for p in pats:
1134 pnames.append(p.name + ':' + p.file + ':' + str(p.lineno))
1135 error_with_file(pats[0].file, pats[0].lineno,
1136 'overlapping patterns size {0}:'.format(width), pnames)
1137
1138 bins = {}
1139 for i in pats:
1140 fb = i.fixedbits & innermask
1141 if fb in bins:
1142 bins[fb].append(i)
1143 else:
1144 bins[fb] = [i]
1145
1146 fullmask = outermask | innermask
1147 lens = sorted(bins.keys())
1148 if len(lens) == 1:
1149 b = lens[0]
1150 return build_size_tree(bins[b], width + 8, b | outerbits, fullmask)
1151
1152 r = SizeTree(innermask, width)
1153 for b, l in bins.items():
1154 s = build_size_tree(l, width, b | outerbits, fullmask)
1155 r.subs.append((b, s))
1156 return r
1157# end build_size_tree
1158
1159
Richard Henderson568ae7e2017-12-07 12:44:09 -08001160def prop_format(tree):
1161 """Propagate Format objects into the decode tree"""
1162
1163 # Depth first search.
1164 for (b, s) in tree.subs:
1165 if isinstance(s, Tree):
1166 prop_format(s)
1167
1168 # If all entries in SUBS have the same format, then
1169 # propagate that into the tree.
1170 f = None
1171 for (b, s) in tree.subs:
1172 if f is None:
1173 f = s.base
1174 if f is None:
1175 return
1176 if f is not s.base:
1177 return
1178 tree.base = f
1179# end prop_format
1180
1181
Richard Henderson70e07112019-01-31 11:34:11 -08001182def prop_size(tree):
1183 """Propagate minimum widths up the decode size tree"""
1184
1185 if isinstance(tree, SizeTree):
1186 min = None
1187 for (b, s) in tree.subs:
1188 width = prop_size(s)
1189 if min is None or min > width:
1190 min = width
1191 assert min >= tree.width
1192 tree.width = min
1193 else:
1194 min = tree.width
1195 return min
1196# end prop_size
1197
1198
Richard Henderson568ae7e2017-12-07 12:44:09 -08001199def main():
1200 global arguments
1201 global formats
1202 global patterns
Richard Henderson0eff2df2019-02-23 11:35:36 -08001203 global allpatterns
Richard Henderson568ae7e2017-12-07 12:44:09 -08001204 global translate_scope
1205 global translate_prefix
1206 global output_fd
1207 global output_file
1208 global input_file
1209 global insnwidth
1210 global insntype
Bastian Koppelmann83d7c402018-03-19 12:58:46 +01001211 global insnmask
Richard Hendersonabd04f92018-10-23 10:26:25 +01001212 global decode_function
Richard Henderson17560e92019-01-30 18:01:29 -08001213 global variablewidth
Richard Hendersonc6920792019-08-09 08:12:50 -07001214 global anyextern
Richard Henderson568ae7e2017-12-07 12:44:09 -08001215
Richard Henderson568ae7e2017-12-07 12:44:09 -08001216 decode_scope = 'static '
1217
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001218 long_opts = ['decode=', 'translate=', 'output=', 'insnwidth=',
Richard Henderson17560e92019-01-30 18:01:29 -08001219 'static-decode=', 'varinsnwidth=']
Richard Henderson568ae7e2017-12-07 12:44:09 -08001220 try:
Richard Henderson17560e92019-01-30 18:01:29 -08001221 (opts, args) = getopt.getopt(sys.argv[1:], 'o:vw:', long_opts)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001222 except getopt.GetoptError as err:
1223 error(0, err)
1224 for o, a in opts:
1225 if o in ('-o', '--output'):
1226 output_file = a
1227 elif o == '--decode':
1228 decode_function = a
1229 decode_scope = ''
Richard Hendersoncd3e7fc2019-02-23 17:44:31 -08001230 elif o == '--static-decode':
1231 decode_function = a
Richard Henderson568ae7e2017-12-07 12:44:09 -08001232 elif o == '--translate':
1233 translate_prefix = a
1234 translate_scope = ''
Richard Henderson17560e92019-01-30 18:01:29 -08001235 elif o in ('-w', '--insnwidth', '--varinsnwidth'):
1236 if o == '--varinsnwidth':
1237 variablewidth = True
Richard Henderson568ae7e2017-12-07 12:44:09 -08001238 insnwidth = int(a)
1239 if insnwidth == 16:
1240 insntype = 'uint16_t'
1241 insnmask = 0xffff
1242 elif insnwidth != 32:
1243 error(0, 'cannot handle insns of width', insnwidth)
1244 else:
1245 assert False, 'unhandled option'
1246
1247 if len(args) < 1:
1248 error(0, 'missing input file')
Richard Henderson6699ae62018-10-26 14:59:43 +01001249 for filename in args:
1250 input_file = filename
1251 f = open(filename, 'r')
1252 parse_file(f)
1253 f.close()
Richard Henderson568ae7e2017-12-07 12:44:09 -08001254
Richard Henderson70e07112019-01-31 11:34:11 -08001255 if variablewidth:
1256 stree = build_size_tree(patterns, 8, 0, 0)
1257 prop_size(stree)
1258
1259 dtree = build_tree(patterns, 0, 0)
1260 prop_format(dtree)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001261
1262 if output_file:
1263 output_fd = open(output_file, 'w')
1264 else:
1265 output_fd = sys.stdout
1266
1267 output_autogen()
1268 for n in sorted(arguments.keys()):
1269 f = arguments[n]
1270 f.output_def()
1271
1272 # A single translate function can be invoked for different patterns.
1273 # Make sure that the argument sets are the same, and declare the
1274 # function only once.
Richard Hendersonc6920792019-08-09 08:12:50 -07001275 #
1276 # If we're sharing formats, we're likely also sharing trans_* functions,
1277 # but we can't tell which ones. Prevent issues from the compiler by
1278 # suppressing redundant declaration warnings.
1279 if anyextern:
1280 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1281 "# pragma GCC diagnostic push\n",
1282 "# pragma GCC diagnostic ignored \"-Wredundant-decls\"\n",
1283 "# ifdef __clang__\n"
1284 "# pragma GCC diagnostic ignored \"-Wtypedef-redefinition\"\n",
1285 "# endif\n",
1286 "#endif\n\n")
1287
Richard Henderson568ae7e2017-12-07 12:44:09 -08001288 out_pats = {}
Richard Henderson0eff2df2019-02-23 11:35:36 -08001289 for i in allpatterns:
Richard Henderson568ae7e2017-12-07 12:44:09 -08001290 if i.name in out_pats:
1291 p = out_pats[i.name]
1292 if i.base.base != p.base.base:
1293 error(0, i.name, ' has conflicting argument sets')
1294 else:
1295 i.output_decl()
1296 out_pats[i.name] = i
1297 output('\n')
1298
Richard Hendersonc6920792019-08-09 08:12:50 -07001299 if anyextern:
1300 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1301 "# pragma GCC diagnostic pop\n",
1302 "#endif\n\n")
1303
Richard Henderson568ae7e2017-12-07 12:44:09 -08001304 for n in sorted(formats.keys()):
1305 f = formats[n]
1306 f.output_extract()
1307
1308 output(decode_scope, 'bool ', decode_function,
1309 '(DisasContext *ctx, ', insntype, ' insn)\n{\n')
1310
1311 i4 = str_indent(4)
Richard Henderson568ae7e2017-12-07 12:44:09 -08001312
Richard Henderson82bfac12019-02-27 21:37:32 -08001313 if len(allpatterns) != 0:
1314 output(i4, 'union {\n')
1315 for n in sorted(arguments.keys()):
1316 f = arguments[n]
1317 output(i4, i4, f.struct_name(), ' f_', f.name, ';\n')
1318 output(i4, '} u;\n\n')
Richard Henderson70e07112019-01-31 11:34:11 -08001319 dtree.output_code(4, False, 0, 0)
Richard Henderson82bfac12019-02-27 21:37:32 -08001320
Richard Hendersoneb6b87f2019-02-23 08:57:46 -08001321 output(i4, 'return false;\n')
Richard Henderson568ae7e2017-12-07 12:44:09 -08001322 output('}\n')
1323
Richard Henderson70e07112019-01-31 11:34:11 -08001324 if variablewidth:
1325 output('\n', decode_scope, insntype, ' ', decode_function,
1326 '_load(DisasContext *ctx)\n{\n',
1327 ' ', insntype, ' insn = 0;\n\n')
1328 stree.output_code(4, 0, 0, 0)
1329 output('}\n')
1330
Richard Henderson568ae7e2017-12-07 12:44:09 -08001331 if output_file:
1332 output_fd.close()
1333# end main
1334
1335
1336if __name__ == '__main__':
1337 main()