and now for something completely different...
[soc.git] / src / soc / sv / trans / svp64.py
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3 # Funded by NLnet http://nlnet.nl
4
5 """SVP64 OpenPOWER v3.0B assembly translator
6
7 This class takes raw svp64 assembly mnemonics (aliases excluded) and
8 creates an EXT001-encoded "svp64 prefix" followed by a v3.0B opcode.
9
10 It is very simple and straightforward, the only weirdness being the
11 extraction of the register information and conversion to v3.0B numbering.
12
13 Encoding format of svp64: https://libre-soc.org/openpower/sv/svp64/
14 Bugtracker: https://bugs.libre-soc.org/show_bug.cgi?id=578
15 """
16
17 import os, sys
18 from collections import OrderedDict
19
20 from soc.decoder.pseudo.pagereader import ISA
21 from soc.decoder.power_enums import get_csv, find_wiki_dir
22
23
24 # identifies register by type
25 def is_CR_3bit(regname):
26 return regname in ['BF', 'BFA']
27
28 def is_CR_5bit(regname):
29 return regname in ['BA', 'BB', 'BC', 'BI', 'BT']
30
31 def is_GPR(regname):
32 return regname in ['RA', 'RB', 'RC', 'RS', 'RT']
33
34 def get_regtype(regname):
35 if is_CR_3bit(regname):
36 return "CR_3bit"
37 if is_CR_5bit(regname):
38 return "CR_5bit"
39 if is_GPR(regname):
40 return "GPR"
41
42 # decode GPR into sv extra
43 def get_extra_gpr(etype, regmode, field):
44 if regmode == 'scalar':
45 # cut into 2-bits 5-bits SS FFFFF
46 sv_extra = field >> 5
47 field = field & 0b11111
48 else:
49 # cut into 5-bits 2-bits FFFFF SS
50 sv_extra = field & 0b11
51 field = field >> 2
52 return sv_extra, field
53
54
55 # decode 3-bit CR into sv extra
56 def get_extra_cr_3bit(etype, regmode, field):
57 if regmode == 'scalar':
58 # cut into 2-bits 3-bits SS FFF
59 sv_extra = field >> 3
60 field = field & 0b111
61 else:
62 # cut into 3-bits 4-bits FFF SSSS but will cut 2 zeros off later
63 sv_extra = field & 0b1111
64 field = field >> 4
65 return sv_extra, field
66
67
68 # decodes SUBVL
69 def decode_subvl(encoding):
70 pmap = {'2': 0b01, '3': 0b10, '4': 0b11}
71 assert encoding in pmap, \
72 "encoding %s for SUBVL not recognised" % encoding
73 return pmap[encoding]
74
75
76 # decodes elwidth
77 def decode_elwidth(encoding):
78 pmap = {'8': 0b11, '16': 0b10, '32': 0b01}
79 assert encoding in pmap, \
80 "encoding %s for elwidth not recognised" % encoding
81 return pmap[encoding]
82
83
84 # decodes predicate register encoding
85 def decode_predicate(encoding):
86 pmap = { # integer
87 '1<<r3': (0, 0b001),
88 'r3' : (0, 0b010),
89 '~r3' : (0, 0b011),
90 'r10' : (0, 0b100),
91 '~r10' : (0, 0b101),
92 'r30' : (0, 0b110),
93 '~r30' : (0, 0b111),
94 # CR
95 'lt' : (1, 0b000),
96 'nl' : (1, 0b001), 'ge' : (1, 0b001), # same value
97 'gt' : (1, 0b010),
98 'ng' : (1, 0b011), 'le' : (1, 0b011), # same value
99 'eq' : (1, 0b100),
100 'ne' : (1, 0b101),
101 'so' : (1, 0b110), 'un' : (1, 0b110), # same value
102 'ns' : (1, 0b111), 'nu' : (1, 0b111), # same value
103 }
104 assert encoding in pmap, \
105 "encoding %s for predicate not recognised" % encoding
106 return pmap[encoding]
107
108
109 # gets SVP64 ReMap information
110 class SVP64RM:
111 def __init__(self):
112 self.instrs = {}
113 pth = find_wiki_dir()
114 for fname in os.listdir(pth):
115 if fname.startswith("RM"):
116 for entry in get_csv(fname):
117 self.instrs[entry['insn']] = entry
118
119
120 # decodes svp64 assembly listings and creates EXT001 svp64 prefixes
121 class SVP64:
122 def __init__(self, lst):
123 self.lst = lst
124 self.trans = self.translate(lst)
125
126 def __iter__(self):
127 for insn in self.trans:
128 yield insn
129
130 def translate(self, lst):
131 isa = ISA() # reads the v3.0B pseudo-code markdown files
132 svp64 = SVP64RM() # reads the svp64 Remap entries for registers
133 res = []
134 for insn in lst:
135 # find first space, to get opcode
136 ls = insn.split(' ')
137 opcode = ls[0]
138 # now find opcode fields
139 fields = ''.join(ls[1:]).split(',')
140 fields = list(map(str.strip, fields))
141 print ("opcode, fields", ls, opcode, fields)
142
143 # identify if is a svp64 mnemonic
144 if not opcode.startswith('sv.'):
145 res.append(insn) # unaltered
146 continue
147
148 # start working on decoding the svp64 op: sv.baseop.vec2.mode
149 opmodes = opcode.split(".")[1:] # strip leading "sv."
150 v30b_op = opmodes.pop(0) # first is the v3.0B
151 if v30b_op not in isa.instr:
152 raise Exception("opcode %s of '%s' not supported" % \
153 (v30b_op, insn))
154 if v30b_op not in svp64.instrs:
155 raise Exception("opcode %s of '%s' not an svp64 instruction" % \
156 (v30b_op, insn))
157 isa.instr[v30b_op].regs[0]
158 v30b_regs = isa.instr[v30b_op].regs[0]
159 rm = svp64.instrs[v30b_op]
160 print ("v3.0B regs", opcode, v30b_regs)
161 print (rm)
162
163 # right. the first thing to do is identify the ordering of
164 # the registers, by name. the EXTRA2/3 ordering is in
165 # rm['0']..rm['3'] but those fields contain the names RA, BB
166 # etc. we have to read the pseudocode to understand which
167 # reg is which in our instruction. sigh.
168
169 # first turn the svp64 rm into a "by name" dict, recording
170 # which position in the RM EXTRA it goes into
171 # also: record if the src or dest was a CR, for sanity-checking
172 # (elwidth overrides on CRs are banned)
173 dest_reg_cr, src_reg_cr = False, False
174 svp64_reg_byname = {}
175 for i in range(4):
176 rfield = rm[str(i)]
177 if not rfield or rfield == '0':
178 continue
179 print ("EXTRA field", i, rfield)
180 rfield = rfield.split(";") # s:RA;d:CR1 etc.
181 for r in rfield:
182 rtype = r[0]
183 r = r[2:] # ignore s: and d:
184 svp64_reg_byname[r] = i # this reg in EXTRA position 0-3
185 # check the regtype (if CR, record that)
186 regtype = get_regtype(r)
187 if regtype in ['CR_3bit', 'CR_5bit']:
188 if rtype == 'd':
189 dest_reg_cr = True
190 if rtype == 'd':
191 src_reg_cr = True
192
193 print ("EXTRA field index, by regname", svp64_reg_byname)
194
195 # okaaay now we identify the field value (opcode N,N,N) with
196 # the pseudo-code info (opcode RT, RA, RB)
197 opregfields = zip(fields, v30b_regs) # err that was easy
198
199 # now for each of those find its place in the EXTRA encoding
200 extras = OrderedDict()
201 for idx, (field, regname) in enumerate(opregfields):
202 extra = svp64_reg_byname.get(regname, None)
203 regtype = get_regtype(regname)
204 extras[extra] = (idx, field, regname, regtype)
205 print (" ", extra, extras[extra])
206
207 # great! got the extra fields in their associated positions:
208 # also we know the register type. now to create the EXTRA encodings
209 etype = rm['Etype'] # Extra type: EXTRA3/EXTRA2
210 ptype = rm['Ptype'] # Predication type: Twin / Single
211 extra_bits = 0
212 v30b_newfields = []
213 for extra_idx, (idx, field, regname, regtype) in extras.items():
214 # is it a field we don't alter/examine? if so just put it
215 # into newfields
216 if regtype is None:
217 v30b_newfields.append(field)
218
219 # first, decode the field number. "5.v" or "3.s" or "9"
220 field = field.split(".")
221 regmode = 'scalar' # default
222 if len(field) == 2:
223 if field[1] == 's':
224 regmode = 'scalar'
225 elif field[1] == 'v':
226 regmode = 'vector'
227 field = int(field[0]) # actual register number
228 print (" ", regmode, field, end=" ")
229
230 # XXX TODO: the following is a bit of a laborious repeated
231 # mess, which could (and should) easily be parameterised.
232
233 # encode SV-GPR field into extra, v3.0field
234 if regtype == 'GPR':
235 sv_extra, field = get_extra_gpr(etype, regmode, field)
236 # now sanity-check. EXTRA3 is ok, EXTRA2 has limits
237 # (and shrink to a single bit if ok)
238 if etype == 'EXTRA2':
239 if regmode == 'scalar':
240 # range is r0-r63 in increments of 1
241 assert (sv_extra >> 1) == 0, \
242 "scalar GPR %s cannot fit into EXTRA2 %s" % \
243 (regname, str(extras[extra_idx]))
244 # all good: encode as scalar
245 sv_extra = sv_extra & 0b01
246 else:
247 # range is r0-r127 in increments of 4
248 assert sv_extra & 0b01 == 0, \
249 "vector field %s cannot fit into EXTRA2 %s" % \
250 (regname, str(extras[extra_idx]))
251 # all good: encode as vector (bit 2 set)
252 sv_extra = 0b10 | (sv_extra >> 1)
253 elif regmode == 'vector':
254 # EXTRA3 vector bit needs marking
255 sv_extra |= 0b100
256
257 # encode SV-CR 3-bit field into extra, v3.0field
258 elif regtype == 'CR_3bit':
259 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
260 # now sanity-check (and shrink afterwards)
261 if etype == 'EXTRA2':
262 if regmode == 'scalar':
263 # range is CR0-CR15 in increments of 1
264 assert (sv_extra >> 1) == 0, \
265 "scalar CR %s cannot fit into EXTRA2 %s" % \
266 (regname, str(extras[extra_idx]))
267 # all good: encode as scalar
268 sv_extra = sv_extra & 0b01
269 else:
270 # range is CR0-CR127 in increments of 16
271 assert sv_extra & 0b111 == 0, \
272 "vector CR %s cannot fit into EXTRA2 %s" % \
273 (regname, str(extras[extra_idx]))
274 # all good: encode as vector (bit 2 set)
275 sv_extra = 0b10 | (sv_extra >> 3)
276 else:
277 if regmode == 'scalar':
278 # range is CR0-CR31 in increments of 1
279 assert (sv_extra >> 2) == 0, \
280 "scalar CR %s cannot fit into EXTRA2 %s" % \
281 (regname, str(extras[extra_idx]))
282 # all good: encode as scalar
283 sv_extra = sv_extra & 0b11
284 else:
285 # range is CR0-CR127 in increments of 8
286 assert sv_extra & 0b11 == 0, \
287 "vector CR %s cannot fit into EXTRA2 %s" % \
288 (regname, str(extras[extra_idx]))
289 # all good: encode as vector (bit 3 set)
290 sv_extra = 0b100 | (sv_extra >> 2)
291
292 # encode SV-CR 5-bit field into extra, v3.0field
293 # *sigh* this is the same as 3-bit except the 2 LSBs are
294 # passed through
295 elif regtype == 'CR_5bit':
296 cr_subfield = field & 0b11
297 field = field >> 2 # strip bottom 2 bits
298 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
299 # now sanity-check (and shrink afterwards)
300 if etype == 'EXTRA2':
301 if regmode == 'scalar':
302 # range is CR0-CR15 in increments of 1
303 assert (sv_extra >> 1) == 0, \
304 "scalar CR %s cannot fit into EXTRA2 %s" % \
305 (regname, str(extras[extra_idx]))
306 # all good: encode as scalar
307 sv_extra = sv_extra & 0b01
308 else:
309 # range is CR0-CR127 in increments of 16
310 assert sv_extra & 0b111 == 0, \
311 "vector CR %s cannot fit into EXTRA2 %s" % \
312 (regname, str(extras[extra_idx]))
313 # all good: encode as vector (bit 2 set)
314 sv_extra = 0b10 | (sv_extra >> 3)
315 else:
316 if regmode == 'scalar':
317 # range is CR0-CR31 in increments of 1
318 assert (sv_extra >> 2) == 0, \
319 "scalar CR %s cannot fit into EXTRA2 %s" % \
320 (regname, str(extras[extra_idx]))
321 # all good: encode as scalar
322 sv_extra = sv_extra & 0b11
323 else:
324 # range is CR0-CR127 in increments of 8
325 assert sv_extra & 0b11 == 0, \
326 "vector CR %s cannot fit into EXTRA2 %s" % \
327 (regname, str(extras[extra_idx]))
328 # all good: encode as vector (bit 3 set)
329 sv_extra = 0b100 | (sv_extra >> 2)
330
331 # reconstruct the actual 5-bit CR field
332 field = (field << 2) | cr_subfield
333
334 # capture the extra field info
335 print ("=>", "%5s" % bin(sv_extra), field)
336 extras[extra_idx] = sv_extra
337
338 # append altered field value to v3.0b
339 v30b_newfields.append(str(field))
340
341 print ("new v3.0B fields", v30b_op, v30b_newfields)
342 print ("extras", extras)
343
344 # rright. now we have all the info. start creating SVP64 RM
345 svp64_rm = 0b0
346
347 # begin with EXTRA fields
348 for idx, sv_extra in extras.items():
349 if idx is None: continue
350 # start at bit 10, work up 2/3 times EXTRA idx
351 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
352 svp64_rm |= sv_extra << (10+idx*offs)
353
354 # parts of svp64_rm
355 mmode = 0 # bit 0
356 pmask = 0 # bits 1-3
357 destwid = 0 # bits 4-5
358 srcwid = 0 # bits 6-7
359 subvl = 0 # bits 8-9
360 smask = 0 # bits 16-18 but only for twin-predication
361 mode = 0 # bits 19-23
362
363 has_pmask = False
364 has_smask = False
365
366 # ok let's start identifying opcode augmentation fields
367 for encmode in opmodes:
368 # predicate mask (dest)
369 if encmode.startswith("m="):
370 pme = encmode
371 pmmode, pmask = decode_predicate(encmode[2:])
372 mmode = pmmode
373 has_pmask = True
374 # predicate mask (src, twin-pred)
375 elif encmode.startswith("sm="):
376 sme = encmode
377 smmode, smask = decode_predicate(encmode[3:])
378 mmode = smmode
379 has_smask = True
380 # vec2/3/4
381 elif encmode.startswith("vec"):
382 subvl = decode_subvl(encmode[3:])
383 # elwidth
384 elif encmode.startswith("ew="):
385 destwid = decode_elwidth(encmode[3:])
386 elif encmode.startswith("sw="):
387 srcwid = decode_elwidth(encmode[3:])
388
389 # sanity-check that 2Pred mask is same mode
390 if has_pmask and has_smask:
391 assert smmode == pmmode, \
392 "predicate masks %s and %s must be same reg type" % \
393 (pme, sme)
394
395 # sanity-check that twin-predication mask only specified in 2P mode
396 if ptype == '1P':
397 assert has_smask == False, \
398 "source-mask can only be specified on Twin-predicate ops"
399
400 # put in predicate masks into svp64_rm
401 if ptype == '2P':
402 svp64_rm |= (smask << 16) # source pred: bits 16-18
403 svp64_rm |= (mmode) # mask mode: bit 0
404 svp64_rm |= (pmask << 1) # 1-pred: bits 1-3
405
406 # and subvl
407 svp64_rm += (subvl << 8) # subvl: bits 8-9
408
409 # put in elwidths
410 svp64_rm += (srcwid << 6) # srcwid: bits 6-7
411 svp64_rm += (destwid << 4) # destwid: bits 4-5
412
413 # nice debug printout. (and now for something completely different)
414 # https://youtu.be/u0WOIwlXE9g?t=146
415 print ("svp64_rm", hex(svp64_rm), bin(svp64_rm))
416 print (" mmode 0 :", bin(mmode))
417 print (" pmask 1-3 :", bin(pmask))
418 print (" dstwid 4-5 :", bin(destwid))
419 print (" srcwid 6-7 :", bin(srcwid))
420 print (" subvl 8-9 :", bin(subvl))
421 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
422 for idx, sv_extra in extras.items():
423 if idx is None: continue
424 start = (10+idx*offs)
425 end = start + offs-1
426 print (" extra%d %2d-%2d:" % (idx, start, end),
427 bin(sv_extra))
428 if ptype == '2P':
429 print (" smask 16-17:", bin(smask))
430 print ()
431
432 return res
433
434 if __name__ == '__main__':
435 isa = SVP64(['slw 3, 1, 4',
436 'extsw 5, 3',
437 'sv.extsw 5, 3',
438 'sv.cmpi 5, 1, 3, 2',
439 'sv.setb 5, 31',
440 'sv.isel 64.v, 3, 2, 65.v',
441 'sv.setb.m=r3.sm=1<<r3 5, 31',
442 'sv.setb.vec2 5, 31',
443 'sv.setb.sw=8.ew=16 5, 31',
444 ])
445 csvs = SVP64RM()