decodetree.py 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. #!/usr/bin/env python
  2. # 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. # Generate a decoding tree from a specification file.
  19. #
  20. # The tree is built from instruction "patterns". A pattern may represent
  21. # a single architectural instruction or a group of same, depending on what
  22. # is convenient for further processing.
  23. #
  24. # Each pattern has "fixedbits" & "fixedmask", the combination of which
  25. # describes the condition under which the pattern is matched:
  26. #
  27. # (insn & fixedmask) == fixedbits
  28. #
  29. # Each pattern may have "fields", which are extracted from the insn and
  30. # passed along to the translator. Examples of such are registers,
  31. # immediates, and sub-opcodes.
  32. #
  33. # In support of patterns, one may declare fields, argument sets, and
  34. # formats, each of which may be re-used to simplify further definitions.
  35. #
  36. # *** Field syntax:
  37. #
  38. # field_def := '%' identifier ( unnamed_field )+ ( !function=identifier )?
  39. # unnamed_field := number ':' ( 's' ) number
  40. #
  41. # For unnamed_field, the first number is the least-significant bit position of
  42. # the field and the second number is the length of the field. If the 's' is
  43. # present, the field is considered signed. If multiple unnamed_fields are
  44. # present, they are concatenated. In this way one can define disjoint fields.
  45. #
  46. # If !function is specified, the concatenated result is passed through the
  47. # named function, taking and returning an integral value.
  48. #
  49. # FIXME: the fields of the structure into which this result will be stored
  50. # is restricted to "int". Which means that we cannot expand 64-bit items.
  51. #
  52. # Field examples:
  53. #
  54. # %disp 0:s16 -- sextract(i, 0, 16)
  55. # %imm9 16:6 10:3 -- extract(i, 16, 6) << 3 | extract(i, 10, 3)
  56. # %disp12 0:s1 1:1 2:10 -- sextract(i, 0, 1) << 11
  57. # | extract(i, 1, 1) << 10
  58. # | extract(i, 2, 10)
  59. # %shimm8 5:s8 13:1 !function=expand_shimm8
  60. # -- expand_shimm8(sextract(i, 5, 8) << 1
  61. # | extract(i, 13, 1))
  62. #
  63. # *** Argument set syntax:
  64. #
  65. # args_def := '&' identifier ( args_elt )+
  66. # args_elt := identifier
  67. #
  68. # Each args_elt defines an argument within the argument set.
  69. # Each argument set will be rendered as a C structure "arg_$name"
  70. # with each of the fields being one of the member arguments.
  71. #
  72. # Argument set examples:
  73. #
  74. # &reg3 ra rb rc
  75. # &loadstore reg base offset
  76. #
  77. # *** Format syntax:
  78. #
  79. # fmt_def := '@' identifier ( fmt_elt )+
  80. # fmt_elt := fixedbit_elt | field_elt | field_ref | args_ref
  81. # fixedbit_elt := [01.-]+
  82. # field_elt := identifier ':' 's'? number
  83. # field_ref := '%' identifier | identifier '=' '%' identifier
  84. # args_ref := '&' identifier
  85. #
  86. # Defining a format is a handy way to avoid replicating groups of fields
  87. # across many instruction patterns.
  88. #
  89. # A fixedbit_elt describes a contiguous sequence of bits that must
  90. # be 1, 0, [.-] for don't care. The difference between '.' and '-'
  91. # is that '.' means that the bit will be covered with a field or a
  92. # final [01] from the pattern, and '-' means that the bit is really
  93. # ignored by the cpu and will not be specified.
  94. #
  95. # A field_elt describes a simple field only given a width; the position of
  96. # the field is implied by its position with respect to other fixedbit_elt
  97. # and field_elt.
  98. #
  99. # If any fixedbit_elt or field_elt appear then all bits must be defined.
  100. # Padding with a fixedbit_elt of all '.' is an easy way to accomplish that.
  101. #
  102. # A field_ref incorporates a field by reference. This is the only way to
  103. # add a complex field to a format. A field may be renamed in the process
  104. # via assignment to another identifier. This is intended to allow the
  105. # same argument set be used with disjoint named fields.
  106. #
  107. # A single args_ref may specify an argument set to use for the format.
  108. # The set of fields in the format must be a subset of the arguments in
  109. # the argument set. If an argument set is not specified, one will be
  110. # inferred from the set of fields.
  111. #
  112. # It is recommended, but not required, that all field_ref and args_ref
  113. # appear at the end of the line, not interleaving with fixedbit_elf or
  114. # field_elt.
  115. #
  116. # Format examples:
  117. #
  118. # @opr ...... ra:5 rb:5 ... 0 ....... rc:5
  119. # @opi ...... ra:5 lit:8 1 ....... rc:5
  120. #
  121. # *** Pattern syntax:
  122. #
  123. # pat_def := identifier ( pat_elt )+
  124. # pat_elt := fixedbit_elt | field_elt | field_ref
  125. # | args_ref | fmt_ref | const_elt
  126. # fmt_ref := '@' identifier
  127. # const_elt := identifier '=' number
  128. #
  129. # The fixedbit_elt and field_elt specifiers are unchanged from formats.
  130. # A pattern that does not specify a named format will have one inferred
  131. # from a referenced argument set (if present) and the set of fields.
  132. #
  133. # A const_elt allows a argument to be set to a constant value. This may
  134. # come in handy when fields overlap between patterns and one has to
  135. # include the values in the fixedbit_elt instead.
  136. #
  137. # The decoder will call a translator function for each pattern matched.
  138. #
  139. # Pattern examples:
  140. #
  141. # addl_r 010000 ..... ..... .... 0000000 ..... @opr
  142. # addl_i 010000 ..... ..... .... 0000000 ..... @opi
  143. #
  144. # which will, in part, invoke
  145. #
  146. # trans_addl_r(ctx, &arg_opr, insn)
  147. # and
  148. # trans_addl_i(ctx, &arg_opi, insn)
  149. #
  150. import os
  151. import re
  152. import sys
  153. import getopt
  154. insnwidth = 32
  155. insnmask = 0xffffffff
  156. fields = {}
  157. arguments = {}
  158. formats = {}
  159. patterns = []
  160. translate_prefix = 'trans'
  161. translate_scope = 'static '
  162. input_file = ''
  163. output_file = None
  164. output_fd = None
  165. insntype = 'uint32_t'
  166. re_ident = '[a-zA-Z][a-zA-Z0-9_]*'
  167. def error(lineno, *args):
  168. """Print an error message from file:line and args and exit."""
  169. global output_file
  170. global output_fd
  171. if lineno:
  172. r = '{0}:{1}: error:'.format(input_file, lineno)
  173. elif input_file:
  174. r = '{0}: error:'.format(input_file)
  175. else:
  176. r = 'error:'
  177. for a in args:
  178. r += ' ' + str(a)
  179. r += '\n'
  180. sys.stderr.write(r)
  181. if output_file and output_fd:
  182. output_fd.close()
  183. os.remove(output_file)
  184. exit(1)
  185. def output(*args):
  186. global output_fd
  187. for a in args:
  188. output_fd.write(a)
  189. if sys.version_info >= (3, 0):
  190. re_fullmatch = re.fullmatch
  191. else:
  192. def re_fullmatch(pat, str):
  193. return re.match('^' + pat + '$', str)
  194. def output_autogen():
  195. output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
  196. def str_indent(c):
  197. """Return a string with C spaces"""
  198. return ' ' * c
  199. def str_fields(fields):
  200. """Return a string uniquely identifing FIELDS"""
  201. r = ''
  202. for n in sorted(fields.keys()):
  203. r += '_' + n
  204. return r[1:]
  205. def str_match_bits(bits, mask):
  206. """Return a string pretty-printing BITS/MASK"""
  207. global insnwidth
  208. i = 1 << (insnwidth - 1)
  209. space = 0x01010100
  210. r = ''
  211. while i != 0:
  212. if i & mask:
  213. if i & bits:
  214. r += '1'
  215. else:
  216. r += '0'
  217. else:
  218. r += '.'
  219. if i & space:
  220. r += ' '
  221. i >>= 1
  222. return r
  223. def is_pow2(x):
  224. """Return true iff X is equal to a power of 2."""
  225. return (x & (x - 1)) == 0
  226. def ctz(x):
  227. """Return the number of times 2 factors into X."""
  228. r = 0
  229. while ((x >> r) & 1) == 0:
  230. r += 1
  231. return r
  232. def is_contiguous(bits):
  233. shift = ctz(bits)
  234. if is_pow2((bits >> shift) + 1):
  235. return shift
  236. else:
  237. return -1
  238. def eq_fields_for_args(flds_a, flds_b):
  239. if len(flds_a) != len(flds_b):
  240. return False
  241. for k, a in flds_a.items():
  242. if k not in flds_b:
  243. return False
  244. return True
  245. def eq_fields_for_fmts(flds_a, flds_b):
  246. if len(flds_a) != len(flds_b):
  247. return False
  248. for k, a in flds_a.items():
  249. if k not in flds_b:
  250. return False
  251. b = flds_b[k]
  252. if a.__class__ != b.__class__ or a != b:
  253. return False
  254. return True
  255. class Field:
  256. """Class representing a simple instruction field"""
  257. def __init__(self, sign, pos, len):
  258. self.sign = sign
  259. self.pos = pos
  260. self.len = len
  261. self.mask = ((1 << len) - 1) << pos
  262. def __str__(self):
  263. if self.sign:
  264. s = 's'
  265. else:
  266. s = ''
  267. return str(pos) + ':' + s + str(len)
  268. def str_extract(self):
  269. if self.sign:
  270. extr = 'sextract32'
  271. else:
  272. extr = 'extract32'
  273. return '{0}(insn, {1}, {2})'.format(extr, self.pos, self.len)
  274. def __eq__(self, other):
  275. return self.sign == other.sign and self.sign == other.sign
  276. def __ne__(self, other):
  277. return not self.__eq__(other)
  278. # end Field
  279. class MultiField:
  280. """Class representing a compound instruction field"""
  281. def __init__(self, subs, mask):
  282. self.subs = subs
  283. self.sign = subs[0].sign
  284. self.mask = mask
  285. def __str__(self):
  286. return str(self.subs)
  287. def str_extract(self):
  288. ret = '0'
  289. pos = 0
  290. for f in reversed(self.subs):
  291. if pos == 0:
  292. ret = f.str_extract()
  293. else:
  294. ret = 'deposit32({0}, {1}, {2}, {3})' \
  295. .format(ret, pos, 32 - pos, f.str_extract())
  296. pos += f.len
  297. return ret
  298. def __ne__(self, other):
  299. if len(self.subs) != len(other.subs):
  300. return True
  301. for a, b in zip(self.subs, other.subs):
  302. if a.__class__ != b.__class__ or a != b:
  303. return True
  304. return False
  305. def __eq__(self, other):
  306. return not self.__ne__(other)
  307. # end MultiField
  308. class ConstField:
  309. """Class representing an argument field with constant value"""
  310. def __init__(self, value):
  311. self.value = value
  312. self.mask = 0
  313. self.sign = value < 0
  314. def __str__(self):
  315. return str(self.value)
  316. def str_extract(self):
  317. return str(self.value)
  318. def __cmp__(self, other):
  319. return self.value - other.value
  320. # end ConstField
  321. class FunctionField:
  322. """Class representing a field passed through an expander"""
  323. def __init__(self, func, base):
  324. self.mask = base.mask
  325. self.sign = base.sign
  326. self.base = base
  327. self.func = func
  328. def __str__(self):
  329. return self.func + '(' + str(self.base) + ')'
  330. def str_extract(self):
  331. return self.func + '(' + self.base.str_extract() + ')'
  332. def __eq__(self, other):
  333. return self.func == other.func and self.base == other.base
  334. def __ne__(self, other):
  335. return not self.__eq__(other)
  336. # end FunctionField
  337. class Arguments:
  338. """Class representing the extracted fields of a format"""
  339. def __init__(self, nm, flds):
  340. self.name = nm
  341. self.fields = sorted(flds)
  342. def __str__(self):
  343. return self.name + ' ' + str(self.fields)
  344. def struct_name(self):
  345. return 'arg_' + self.name
  346. def output_def(self):
  347. output('typedef struct {\n')
  348. for n in self.fields:
  349. output(' int ', n, ';\n')
  350. output('} ', self.struct_name(), ';\n\n')
  351. # end Arguments
  352. class General:
  353. """Common code between instruction formats and instruction patterns"""
  354. def __init__(self, name, lineno, base, fixb, fixm, udfm, fldm, flds):
  355. self.name = name
  356. self.lineno = lineno
  357. self.base = base
  358. self.fixedbits = fixb
  359. self.fixedmask = fixm
  360. self.undefmask = udfm
  361. self.fieldmask = fldm
  362. self.fields = flds
  363. def __str__(self):
  364. r = self.name
  365. if self.base:
  366. r = r + ' ' + self.base.name
  367. else:
  368. r = r + ' ' + str(self.fields)
  369. r = r + ' ' + str_match_bits(self.fixedbits, self.fixedmask)
  370. return r
  371. def str1(self, i):
  372. return str_indent(i) + self.__str__()
  373. # end General
  374. class Format(General):
  375. """Class representing an instruction format"""
  376. def extract_name(self):
  377. return 'extract_' + self.name
  378. def output_extract(self):
  379. output('static void ', self.extract_name(), '(',
  380. self.base.struct_name(), ' *a, ', insntype, ' insn)\n{\n')
  381. for n, f in self.fields.items():
  382. output(' a->', n, ' = ', f.str_extract(), ';\n')
  383. output('}\n\n')
  384. # end Format
  385. class Pattern(General):
  386. """Class representing an instruction pattern"""
  387. def output_decl(self):
  388. global translate_scope
  389. global translate_prefix
  390. output('typedef ', self.base.base.struct_name(),
  391. ' arg_', self.name, ';\n')
  392. output(translate_scope, 'bool ', translate_prefix, '_', self.name,
  393. '(DisasContext *ctx, arg_', self.name,
  394. ' *a, ', insntype, ' insn);\n')
  395. def output_code(self, i, extracted, outerbits, outermask):
  396. global translate_prefix
  397. ind = str_indent(i)
  398. arg = self.base.base.name
  399. output(ind, '/* line ', str(self.lineno), ' */\n')
  400. if not extracted:
  401. output(ind, self.base.extract_name(), '(&u.f_', arg, ', insn);\n')
  402. for n, f in self.fields.items():
  403. output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n')
  404. output(ind, 'return ', translate_prefix, '_', self.name,
  405. '(ctx, &u.f_', arg, ', insn);\n')
  406. # end Pattern
  407. def parse_field(lineno, name, toks):
  408. """Parse one instruction field from TOKS at LINENO"""
  409. global fields
  410. global re_ident
  411. global insnwidth
  412. # A "simple" field will have only one entry;
  413. # a "multifield" will have several.
  414. subs = []
  415. width = 0
  416. func = None
  417. for t in toks:
  418. if re_fullmatch('!function=' + re_ident, t):
  419. if func:
  420. error(lineno, 'duplicate function')
  421. func = t.split('=')
  422. func = func[1]
  423. continue
  424. if re_fullmatch('[0-9]+:s[0-9]+', t):
  425. # Signed field extract
  426. subtoks = t.split(':s')
  427. sign = True
  428. elif re_fullmatch('[0-9]+:[0-9]+', t):
  429. # Unsigned field extract
  430. subtoks = t.split(':')
  431. sign = False
  432. else:
  433. error(lineno, 'invalid field token "{0}"'.format(t))
  434. po = int(subtoks[0])
  435. le = int(subtoks[1])
  436. if po + le > insnwidth:
  437. error(lineno, 'field {0} too large'.format(t))
  438. f = Field(sign, po, le)
  439. subs.append(f)
  440. width += le
  441. if width > insnwidth:
  442. error(lineno, 'field too large')
  443. if len(subs) == 1:
  444. f = subs[0]
  445. else:
  446. mask = 0
  447. for s in subs:
  448. if mask & s.mask:
  449. error(lineno, 'field components overlap')
  450. mask |= s.mask
  451. f = MultiField(subs, mask)
  452. if func:
  453. f = FunctionField(func, f)
  454. if name in fields:
  455. error(lineno, 'duplicate field', name)
  456. fields[name] = f
  457. # end parse_field
  458. def parse_arguments(lineno, name, toks):
  459. """Parse one argument set from TOKS at LINENO"""
  460. global arguments
  461. global re_ident
  462. flds = []
  463. for t in toks:
  464. if not re_fullmatch(re_ident, t):
  465. error(lineno, 'invalid argument set token "{0}"'.format(t))
  466. if t in flds:
  467. error(lineno, 'duplicate argument "{0}"'.format(t))
  468. flds.append(t)
  469. if name in arguments:
  470. error(lineno, 'duplicate argument set', name)
  471. arguments[name] = Arguments(name, flds)
  472. # end parse_arguments
  473. def lookup_field(lineno, name):
  474. global fields
  475. if name in fields:
  476. return fields[name]
  477. error(lineno, 'undefined field', name)
  478. def add_field(lineno, flds, new_name, f):
  479. if new_name in flds:
  480. error(lineno, 'duplicate field', new_name)
  481. flds[new_name] = f
  482. return flds
  483. def add_field_byname(lineno, flds, new_name, old_name):
  484. return add_field(lineno, flds, new_name, lookup_field(lineno, old_name))
  485. def infer_argument_set(flds):
  486. global arguments
  487. for arg in arguments.values():
  488. if eq_fields_for_args(flds, arg.fields):
  489. return arg
  490. name = str(len(arguments))
  491. arg = Arguments(name, flds.keys())
  492. arguments[name] = arg
  493. return arg
  494. def infer_format(arg, fieldmask, flds):
  495. global arguments
  496. global formats
  497. const_flds = {}
  498. var_flds = {}
  499. for n, c in flds.items():
  500. if c is ConstField:
  501. const_flds[n] = c
  502. else:
  503. var_flds[n] = c
  504. # Look for an existing format with the same argument set and fields
  505. for fmt in formats.values():
  506. if arg and fmt.base != arg:
  507. continue
  508. if fieldmask != fmt.fieldmask:
  509. continue
  510. if not eq_fields_for_fmts(flds, fmt.fields):
  511. continue
  512. return (fmt, const_flds)
  513. name = 'Fmt_' + str(len(formats))
  514. if not arg:
  515. arg = infer_argument_set(flds)
  516. fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds)
  517. formats[name] = fmt
  518. return (fmt, const_flds)
  519. # end infer_format
  520. def parse_generic(lineno, is_format, name, toks):
  521. """Parse one instruction format from TOKS at LINENO"""
  522. global fields
  523. global arguments
  524. global formats
  525. global patterns
  526. global re_ident
  527. global insnwidth
  528. global insnmask
  529. fixedmask = 0
  530. fixedbits = 0
  531. undefmask = 0
  532. width = 0
  533. flds = {}
  534. arg = None
  535. fmt = None
  536. for t in toks:
  537. # '&Foo' gives a format an explcit argument set.
  538. if t[0] == '&':
  539. tt = t[1:]
  540. if arg:
  541. error(lineno, 'multiple argument sets')
  542. if tt in arguments:
  543. arg = arguments[tt]
  544. else:
  545. error(lineno, 'undefined argument set', t)
  546. continue
  547. # '@Foo' gives a pattern an explicit format.
  548. if t[0] == '@':
  549. tt = t[1:]
  550. if fmt:
  551. error(lineno, 'multiple formats')
  552. if tt in formats:
  553. fmt = formats[tt]
  554. else:
  555. error(lineno, 'undefined format', t)
  556. continue
  557. # '%Foo' imports a field.
  558. if t[0] == '%':
  559. tt = t[1:]
  560. flds = add_field_byname(lineno, flds, tt, tt)
  561. continue
  562. # 'Foo=%Bar' imports a field with a different name.
  563. if re_fullmatch(re_ident + '=%' + re_ident, t):
  564. (fname, iname) = t.split('=%')
  565. flds = add_field_byname(lineno, flds, fname, iname)
  566. continue
  567. # 'Foo=number' sets an argument field to a constant value
  568. if re_fullmatch(re_ident + '=[0-9]+', t):
  569. (fname, value) = t.split('=')
  570. value = int(value)
  571. flds = add_field(lineno, flds, fname, ConstField(value))
  572. continue
  573. # Pattern of 0s, 1s, dots and dashes indicate required zeros,
  574. # required ones, or dont-cares.
  575. if re_fullmatch('[01.-]+', t):
  576. shift = len(t)
  577. fms = t.replace('0', '1')
  578. fms = fms.replace('.', '0')
  579. fms = fms.replace('-', '0')
  580. fbs = t.replace('.', '0')
  581. fbs = fbs.replace('-', '0')
  582. ubm = t.replace('1', '0')
  583. ubm = ubm.replace('.', '0')
  584. ubm = ubm.replace('-', '1')
  585. fms = int(fms, 2)
  586. fbs = int(fbs, 2)
  587. ubm = int(ubm, 2)
  588. fixedbits = (fixedbits << shift) | fbs
  589. fixedmask = (fixedmask << shift) | fms
  590. undefmask = (undefmask << shift) | ubm
  591. # Otherwise, fieldname:fieldwidth
  592. elif re_fullmatch(re_ident + ':s?[0-9]+', t):
  593. (fname, flen) = t.split(':')
  594. sign = False
  595. if flen[0] == 's':
  596. sign = True
  597. flen = flen[1:]
  598. shift = int(flen, 10)
  599. f = Field(sign, insnwidth - width - shift, shift)
  600. flds = add_field(lineno, flds, fname, f)
  601. fixedbits <<= shift
  602. fixedmask <<= shift
  603. undefmask <<= shift
  604. else:
  605. error(lineno, 'invalid token "{0}"'.format(t))
  606. width += shift
  607. # We should have filled in all of the bits of the instruction.
  608. if not (is_format and width == 0) and width != insnwidth:
  609. error(lineno, 'definition has {0} bits'.format(width))
  610. # Do not check for fields overlaping fields; one valid usage
  611. # is to be able to duplicate fields via import.
  612. fieldmask = 0
  613. for f in flds.values():
  614. fieldmask |= f.mask
  615. # Fix up what we've parsed to match either a format or a pattern.
  616. if is_format:
  617. # Formats cannot reference formats.
  618. if fmt:
  619. error(lineno, 'format referencing format')
  620. # If an argument set is given, then there should be no fields
  621. # without a place to store it.
  622. if arg:
  623. for f in flds.keys():
  624. if f not in arg.fields:
  625. error(lineno, 'field {0} not in argument set {1}'
  626. .format(f, arg.name))
  627. else:
  628. arg = infer_argument_set(flds)
  629. if name in formats:
  630. error(lineno, 'duplicate format name', name)
  631. fmt = Format(name, lineno, arg, fixedbits, fixedmask,
  632. undefmask, fieldmask, flds)
  633. formats[name] = fmt
  634. else:
  635. # Patterns can reference a format ...
  636. if fmt:
  637. # ... but not an argument simultaneously
  638. if arg:
  639. error(lineno, 'pattern specifies both format and argument set')
  640. if fixedmask & fmt.fixedmask:
  641. error(lineno, 'pattern fixed bits overlap format fixed bits')
  642. fieldmask |= fmt.fieldmask
  643. fixedbits |= fmt.fixedbits
  644. fixedmask |= fmt.fixedmask
  645. undefmask |= fmt.undefmask
  646. else:
  647. (fmt, flds) = infer_format(arg, fieldmask, flds)
  648. arg = fmt.base
  649. for f in flds.keys():
  650. if f not in arg.fields:
  651. error(lineno, 'field {0} not in argument set {1}'
  652. .format(f, arg.name))
  653. if f in fmt.fields.keys():
  654. error(lineno, 'field {0} set by format and pattern'.format(f))
  655. for f in arg.fields:
  656. if f not in flds.keys() and f not in fmt.fields.keys():
  657. error(lineno, 'field {0} not initialized'.format(f))
  658. pat = Pattern(name, lineno, fmt, fixedbits, fixedmask,
  659. undefmask, fieldmask, flds)
  660. patterns.append(pat)
  661. # Validate the masks that we have assembled.
  662. if fieldmask & fixedmask:
  663. error(lineno, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
  664. .format(fieldmask, fixedmask))
  665. if fieldmask & undefmask:
  666. error(lineno, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
  667. .format(fieldmask, undefmask))
  668. if fixedmask & undefmask:
  669. error(lineno, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
  670. .format(fixedmask, undefmask))
  671. if not is_format:
  672. allbits = fieldmask | fixedmask | undefmask
  673. if allbits != insnmask:
  674. error(lineno, 'bits left unspecified (0x{0:08x})'
  675. .format(allbits ^ insnmask))
  676. # end parse_general
  677. def parse_file(f):
  678. """Parse all of the patterns within a file"""
  679. # Read all of the lines of the file. Concatenate lines
  680. # ending in backslash; discard empty lines and comments.
  681. toks = []
  682. lineno = 0
  683. for line in f:
  684. lineno += 1
  685. # Discard comments
  686. end = line.find('#')
  687. if end >= 0:
  688. line = line[:end]
  689. t = line.split()
  690. if len(toks) != 0:
  691. # Next line after continuation
  692. toks.extend(t)
  693. elif len(t) == 0:
  694. # Empty line
  695. continue
  696. else:
  697. toks = t
  698. # Continuation?
  699. if toks[-1] == '\\':
  700. toks.pop()
  701. continue
  702. if len(toks) < 2:
  703. error(lineno, 'short line')
  704. name = toks[0]
  705. del toks[0]
  706. # Determine the type of object needing to be parsed.
  707. if name[0] == '%':
  708. parse_field(lineno, name[1:], toks)
  709. elif name[0] == '&':
  710. parse_arguments(lineno, name[1:], toks)
  711. elif name[0] == '@':
  712. parse_generic(lineno, True, name[1:], toks)
  713. else:
  714. parse_generic(lineno, False, name, toks)
  715. toks = []
  716. # end parse_file
  717. class Tree:
  718. """Class representing a node in a decode tree"""
  719. def __init__(self, fm, tm):
  720. self.fixedmask = fm
  721. self.thismask = tm
  722. self.subs = []
  723. self.base = None
  724. def str1(self, i):
  725. ind = str_indent(i)
  726. r = '{0}{1:08x}'.format(ind, self.fixedmask)
  727. if self.format:
  728. r += ' ' + self.format.name
  729. r += ' [\n'
  730. for (b, s) in self.subs:
  731. r += '{0} {1:08x}:\n'.format(ind, b)
  732. r += s.str1(i + 4) + '\n'
  733. r += ind + ']'
  734. return r
  735. def __str__(self):
  736. return self.str1(0)
  737. def output_code(self, i, extracted, outerbits, outermask):
  738. ind = str_indent(i)
  739. # If we identified all nodes below have the same format,
  740. # extract the fields now.
  741. if not extracted and self.base:
  742. output(ind, self.base.extract_name(),
  743. '(&u.f_', self.base.base.name, ', insn);\n')
  744. extracted = True
  745. # Attempt to aid the compiler in producing compact switch statements.
  746. # If the bits in the mask are contiguous, extract them.
  747. sh = is_contiguous(self.thismask)
  748. if sh > 0:
  749. # Propagate SH down into the local functions.
  750. def str_switch(b, sh=sh):
  751. return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh)
  752. def str_case(b, sh=sh):
  753. return '0x{0:x}'.format(b >> sh)
  754. else:
  755. def str_switch(b):
  756. return 'insn & 0x{0:08x}'.format(b)
  757. def str_case(b):
  758. return '0x{0:08x}'.format(b)
  759. output(ind, 'switch (', str_switch(self.thismask), ') {\n')
  760. for b, s in sorted(self.subs):
  761. assert (self.thismask & ~s.fixedmask) == 0
  762. innermask = outermask | self.thismask
  763. innerbits = outerbits | b
  764. output(ind, 'case ', str_case(b), ':\n')
  765. output(ind, ' /* ',
  766. str_match_bits(innerbits, innermask), ' */\n')
  767. s.output_code(i + 4, extracted, innerbits, innermask)
  768. output(ind, '}\n')
  769. output(ind, 'return false;\n')
  770. # end Tree
  771. def build_tree(pats, outerbits, outermask):
  772. # Find the intersection of all remaining fixedmask.
  773. innermask = ~outermask
  774. for i in pats:
  775. innermask &= i.fixedmask
  776. if innermask == 0:
  777. pnames = []
  778. for p in pats:
  779. pnames.append(p.name + ':' + str(p.lineno))
  780. error(pats[0].lineno, 'overlapping patterns:', pnames)
  781. fullmask = outermask | innermask
  782. # Sort each element of pats into the bin selected by the mask.
  783. bins = {}
  784. for i in pats:
  785. fb = i.fixedbits & innermask
  786. if fb in bins:
  787. bins[fb].append(i)
  788. else:
  789. bins[fb] = [i]
  790. # We must recurse if any bin has more than one element or if
  791. # the single element in the bin has not been fully matched.
  792. t = Tree(fullmask, innermask)
  793. for b, l in bins.items():
  794. s = l[0]
  795. if len(l) > 1 or s.fixedmask & ~fullmask != 0:
  796. s = build_tree(l, b | outerbits, fullmask)
  797. t.subs.append((b, s))
  798. return t
  799. # end build_tree
  800. def prop_format(tree):
  801. """Propagate Format objects into the decode tree"""
  802. # Depth first search.
  803. for (b, s) in tree.subs:
  804. if isinstance(s, Tree):
  805. prop_format(s)
  806. # If all entries in SUBS have the same format, then
  807. # propagate that into the tree.
  808. f = None
  809. for (b, s) in tree.subs:
  810. if f is None:
  811. f = s.base
  812. if f is None:
  813. return
  814. if f is not s.base:
  815. return
  816. tree.base = f
  817. # end prop_format
  818. def main():
  819. global arguments
  820. global formats
  821. global patterns
  822. global translate_scope
  823. global translate_prefix
  824. global output_fd
  825. global output_file
  826. global input_file
  827. global insnwidth
  828. global insntype
  829. global insnmask
  830. decode_function = 'decode'
  831. decode_scope = 'static '
  832. long_opts = ['decode=', 'translate=', 'output=', 'insnwidth=']
  833. try:
  834. (opts, args) = getopt.getopt(sys.argv[1:], 'o:w:', long_opts)
  835. except getopt.GetoptError as err:
  836. error(0, err)
  837. for o, a in opts:
  838. if o in ('-o', '--output'):
  839. output_file = a
  840. elif o == '--decode':
  841. decode_function = a
  842. decode_scope = ''
  843. elif o == '--translate':
  844. translate_prefix = a
  845. translate_scope = ''
  846. elif o in ('-w', '--insnwidth'):
  847. insnwidth = int(a)
  848. if insnwidth == 16:
  849. insntype = 'uint16_t'
  850. insnmask = 0xffff
  851. elif insnwidth != 32:
  852. error(0, 'cannot handle insns of width', insnwidth)
  853. else:
  854. assert False, 'unhandled option'
  855. if len(args) < 1:
  856. error(0, 'missing input file')
  857. input_file = args[0]
  858. f = open(input_file, 'r')
  859. parse_file(f)
  860. f.close()
  861. t = build_tree(patterns, 0, 0)
  862. prop_format(t)
  863. if output_file:
  864. output_fd = open(output_file, 'w')
  865. else:
  866. output_fd = sys.stdout
  867. output_autogen()
  868. for n in sorted(arguments.keys()):
  869. f = arguments[n]
  870. f.output_def()
  871. # A single translate function can be invoked for different patterns.
  872. # Make sure that the argument sets are the same, and declare the
  873. # function only once.
  874. out_pats = {}
  875. for i in patterns:
  876. if i.name in out_pats:
  877. p = out_pats[i.name]
  878. if i.base.base != p.base.base:
  879. error(0, i.name, ' has conflicting argument sets')
  880. else:
  881. i.output_decl()
  882. out_pats[i.name] = i
  883. output('\n')
  884. for n in sorted(formats.keys()):
  885. f = formats[n]
  886. f.output_extract()
  887. output(decode_scope, 'bool ', decode_function,
  888. '(DisasContext *ctx, ', insntype, ' insn)\n{\n')
  889. i4 = str_indent(4)
  890. output(i4, 'union {\n')
  891. for n in sorted(arguments.keys()):
  892. f = arguments[n]
  893. output(i4, i4, f.struct_name(), ' f_', f.name, ';\n')
  894. output(i4, '} u;\n\n')
  895. t.output_code(4, False, 0, 0)
  896. output('}\n')
  897. if output_file:
  898. output_fd.close()
  899. # end main
  900. if __name__ == '__main__':
  901. main()