Clone of mesa.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

sid_tables.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. CopyRight = '''
  2. /*
  3. * Copyright 2015 Advanced Micro Devices, Inc.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a
  6. * copy of this software and associated documentation files (the "Software"),
  7. * to deal in the Software without restriction, including without limitation
  8. * on the rights to use, copy, modify, merge, publish, distribute, sub
  9. * license, and/or sell copies of the Software, and to permit persons to whom
  10. * the Software is furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice (including the next
  13. * paragraph) shall be included in all copies or substantial portions of the
  14. * Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
  20. * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  21. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22. * USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. *
  24. */
  25. '''
  26. import collections
  27. import functools
  28. import itertools
  29. import os.path
  30. import re
  31. import sys
  32. class StringTable:
  33. """
  34. A class for collecting multiple strings in a single larger string that is
  35. used by indexing (to avoid relocations in the resulting binary)
  36. """
  37. def __init__(self):
  38. self.table = []
  39. self.length = 0
  40. def add(self, string):
  41. # We might get lucky with string being a suffix of a previously added string
  42. for te in self.table:
  43. if te[0].endswith(string):
  44. idx = te[1] + len(te[0]) - len(string)
  45. te[2].add(idx)
  46. return idx
  47. idx = self.length
  48. self.table.append((string, idx, set((idx,))))
  49. self.length += len(string) + 1
  50. return idx
  51. def emit(self, filp, name, static=True):
  52. """
  53. Write
  54. [static] const char name[] = "...";
  55. to filp.
  56. """
  57. fragments = [
  58. '"%s\\0" /* %s */' % (
  59. te[0].encode('string_escape'),
  60. ', '.join(str(idx) for idx in te[2])
  61. )
  62. for te in self.table
  63. ]
  64. filp.write('%sconst char %s[] =\n%s;\n' % (
  65. 'static ' if static else '',
  66. name,
  67. '\n'.join('\t' + fragment for fragment in fragments)
  68. ))
  69. class IntTable:
  70. """
  71. A class for collecting multiple arrays of integers in a single big array
  72. that is used by indexing (to avoid relocations in the resulting binary)
  73. """
  74. def __init__(self, typename):
  75. self.typename = typename
  76. self.table = []
  77. self.idxs = set()
  78. def add(self, array):
  79. # We might get lucky and find the array somewhere in the existing data
  80. try:
  81. idx = 0
  82. while True:
  83. idx = self.table.index(array[0], idx, len(self.table) - len(array) + 1)
  84. for i in range(1, len(array)):
  85. if array[i] != self.table[idx + i]:
  86. break
  87. else:
  88. self.idxs.add(idx)
  89. return idx
  90. idx += 1
  91. except ValueError:
  92. pass
  93. idx = len(self.table)
  94. self.table += array
  95. self.idxs.add(idx)
  96. return idx
  97. def emit(self, filp, name, static=True):
  98. """
  99. Write
  100. [static] const typename name[] = { ... };
  101. to filp.
  102. """
  103. idxs = sorted(self.idxs) + [len(self.table)]
  104. fragments = [
  105. ('\t/* %s */ %s' % (
  106. idxs[i],
  107. ' '.join((str(elt) + ',') for elt in self.table[idxs[i]:idxs[i+1]])
  108. ))
  109. for i in range(len(idxs) - 1)
  110. ]
  111. filp.write('%sconst %s %s[] = {\n%s\n};\n' % (
  112. 'static ' if static else '',
  113. self.typename, name,
  114. '\n'.join(fragments)
  115. ))
  116. class Field:
  117. def __init__(self, reg, s_name):
  118. self.s_name = s_name
  119. self.name = strip_prefix(s_name)
  120. self.values = []
  121. def format(self, string_table, idx_table):
  122. if len(self.values):
  123. values_offsets = []
  124. for value in self.values:
  125. while value[1] >= len(values_offsets):
  126. values_offsets.append(-1)
  127. values_offsets[value[1]] = string_table.add(strip_prefix(value[0]))
  128. return '{%s, %s(~0u), %s, %s}' % (
  129. string_table.add(self.name), self.s_name,
  130. len(values_offsets), idx_table.add(values_offsets))
  131. else:
  132. return '{%s, %s(~0u)}' % (string_table.add(self.name), self.s_name)
  133. def __eq__(self, other):
  134. return (self.s_name == other.s_name and
  135. self.name == other.name and
  136. len(self.values) == len(other.values) and
  137. all(a[0] == b[0] and a[1] == b[1] for a, b, in zip(self.values, other.values)))
  138. def __ne__(self, other):
  139. return not (self == other)
  140. class FieldTable:
  141. """
  142. A class for collecting multiple arrays of register fields in a single big
  143. array that is used by indexing (to avoid relocations in the resulting binary)
  144. """
  145. def __init__(self):
  146. self.table = []
  147. self.idxs = set()
  148. self.name_to_idx = collections.defaultdict(lambda: [])
  149. def add(self, array):
  150. """
  151. Add an array of Field objects, and return the index of where to find
  152. the array in the table.
  153. """
  154. # Check if we can find the array in the table already
  155. for base_idx in self.name_to_idx.get(array[0].name, []):
  156. if base_idx + len(array) > len(self.table):
  157. continue
  158. for i, a in enumerate(array):
  159. b = self.table[base_idx + i]
  160. if a != b:
  161. break
  162. else:
  163. return base_idx
  164. base_idx = len(self.table)
  165. self.idxs.add(base_idx)
  166. for field in array:
  167. self.name_to_idx[field.name].append(len(self.table))
  168. self.table.append(field)
  169. return base_idx
  170. def emit(self, filp, string_table, idx_table):
  171. """
  172. Write
  173. static const struct si_field sid_fields_table[] = { ... };
  174. to filp.
  175. """
  176. idxs = sorted(self.idxs) + [len(self.table)]
  177. filp.write('static const struct si_field sid_fields_table[] = {\n')
  178. for start, end in zip(idxs, idxs[1:]):
  179. filp.write('\t/* %s */\n' % (start))
  180. for field in self.table[start:end]:
  181. filp.write('\t%s,\n' % (field.format(string_table, idx_table)))
  182. filp.write('};\n')
  183. class Reg:
  184. def __init__(self, r_name):
  185. self.r_name = r_name
  186. self.name = strip_prefix(r_name)
  187. self.fields = []
  188. def __eq__(self, other):
  189. if not isinstance(other, Reg):
  190. return False
  191. return (self.r_name == other.r_name and
  192. self.name == other.name and
  193. len(self.fields) == len(other.fields) and
  194. all(a == b for a, b in zip(self.fields, other.fields)))
  195. def __ne__(self, other):
  196. return not (self == other)
  197. def strip_prefix(s):
  198. '''Strip prefix in the form ._.*_, e.g. R_001234_'''
  199. return s[s[2:].find('_')+3:]
  200. class Asic:
  201. """
  202. Store the registers of one ASIC class / group of classes.
  203. """
  204. def __init__(self, name):
  205. self.name = name
  206. self.registers = []
  207. def parse(self, filp, packets, older_asics):
  208. """
  209. Parse registers from the given header file. Packets are separately
  210. stored in the packets array.
  211. """
  212. for line in filp:
  213. if not line.startswith('#define '):
  214. continue
  215. line = line[8:].strip()
  216. if line.startswith('R_'):
  217. name = line.split()[0]
  218. for it in self.registers:
  219. if it.r_name == name:
  220. sys.exit('Duplicate register define: %s' % (name))
  221. else:
  222. reg = Reg(name)
  223. self.registers.append(reg)
  224. elif line.startswith('S_'):
  225. name = line[:line.find('(')]
  226. for it in reg.fields:
  227. if it.s_name == name:
  228. sys.exit('Duplicate field define: %s' % (name))
  229. else:
  230. field = Field(reg, name)
  231. reg.fields.append(field)
  232. elif line.startswith('V_'):
  233. split = line.split()
  234. name = split[0]
  235. value = int(split[1], 0)
  236. for (n,v) in field.values:
  237. if n == name:
  238. sys.exit('Duplicate value define: name = ' + name)
  239. field.values.append((name, value))
  240. elif line.startswith('PKT3_') and line.find('0x') != -1 and line.find('(') == -1:
  241. packets.append(line.split()[0])
  242. # Copy values for corresponding fields from older ASICs if they were
  243. # not redefined
  244. for reg in self.registers:
  245. old_reg = False
  246. for field in reg.fields:
  247. if len(field.values) > 0:
  248. continue
  249. if old_reg is False:
  250. for old_reg in itertools.chain(
  251. *(asic.registers for asic in reversed(older_asics))):
  252. if old_reg.name == reg.name:
  253. break
  254. else:
  255. old_reg = None
  256. if old_reg is not None:
  257. for old_field in old_reg.fields:
  258. if old_field.name == field.name:
  259. field.values = old_field.values
  260. break
  261. # Copy fields to indexed registers which have their fields only defined
  262. # at register index 0.
  263. # For example, copy fields from CB_COLOR0_INFO to CB_COLORn_INFO, n > 0.
  264. match_number = re.compile('[0-9]+')
  265. reg_dict = dict()
  266. # Create a dict of registers with fields and '0' in their name
  267. for reg in self.registers:
  268. if len(reg.fields) and reg.name.find('0') != -1:
  269. reg_dict[reg.name] = reg
  270. # Assign fields
  271. for reg in self.registers:
  272. if not len(reg.fields):
  273. reg0 = reg_dict.get(match_number.sub('0', reg.name))
  274. if reg0 != None:
  275. reg.fields = reg0.fields
  276. def write_tables(asics, packets):
  277. strings = StringTable()
  278. strings_offsets = IntTable("int")
  279. fields = FieldTable()
  280. print '/* This file is autogenerated by sid_tables.py from sid.h. Do not edit directly. */'
  281. print
  282. print CopyRight.strip()
  283. print '''
  284. #ifndef SID_TABLES_H
  285. #define SID_TABLES_H
  286. struct si_field {
  287. unsigned name_offset;
  288. unsigned mask;
  289. unsigned num_values;
  290. unsigned values_offset; /* offset into sid_strings_offsets */
  291. };
  292. struct si_reg {
  293. unsigned name_offset;
  294. unsigned offset;
  295. unsigned num_fields;
  296. unsigned fields_offset;
  297. };
  298. struct si_packet3 {
  299. unsigned name_offset;
  300. unsigned op;
  301. };
  302. '''
  303. print 'static const struct si_packet3 packet3_table[] = {'
  304. for pkt in packets:
  305. print '\t{%s, %s},' % (strings.add(pkt[5:]), pkt)
  306. print '};'
  307. print
  308. regs = {}
  309. for asic in asics:
  310. print 'static const struct si_reg %s_reg_table[] = {' % (asic.name)
  311. for reg in asic.registers:
  312. # Only output a register that was changed or added relative to
  313. # the previous generation
  314. previous = regs.get(reg.r_name, None)
  315. if previous == reg:
  316. continue
  317. if len(reg.fields):
  318. print '\t{%s, %s, %s, %s},' % (strings.add(reg.name), reg.r_name,
  319. len(reg.fields), fields.add(reg.fields))
  320. else:
  321. print '\t{%s, %s},' % (strings.add(reg.name), reg.r_name)
  322. regs[reg.r_name] = reg
  323. print '};'
  324. print
  325. fields.emit(sys.stdout, strings, strings_offsets)
  326. print
  327. strings.emit(sys.stdout, "sid_strings")
  328. print
  329. strings_offsets.emit(sys.stdout, "sid_strings_offsets")
  330. print
  331. print '#endif'
  332. def main():
  333. asics = []
  334. packets = []
  335. for arg in sys.argv[1:]:
  336. basename = os.path.basename(arg)
  337. m = re.match(r'(.*)\.h', basename)
  338. asic = Asic(m.group(1))
  339. with open(arg) as filp:
  340. asic.parse(filp, packets, asics)
  341. asics.append(asic)
  342. write_tables(asics, packets)
  343. if __name__ == '__main__':
  344. main()
  345. # kate: space-indent on; indent-width 4; replace-tabs on;