provide "merger" of SVP64 RM info into v3.0B CSV files
[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_svp64 import SVP64RM
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 # decodes "Mode" in similar way to BO field (supposed to, anyway)
110 def decode_bo(encoding):
111 pmap = { # TODO: double-check that these are the same as Branch BO
112 'lt' : 0b000,
113 'nl' : 0b001, 'ge' : 0b001, # same value
114 'gt' : 0b010,
115 'ng' : 0b011, 'le' : 0b011, # same value
116 'eq' : 0b100,
117 'ne' : 0b101,
118 'so' : 0b110, 'un' : 0b110, # same value
119 'ns' : 0b111, 'nu' : 0b111, # same value
120 }
121 assert encoding in pmap, \
122 "encoding %s for BO Mode not recognised" % encoding
123 return pmap[encoding]
124
125 # partial-decode fail-first mode
126 def decode_ffirst(encoding):
127 if encoding in ['RC1', '~RC1']:
128 return encoding
129 return decode_bo(encoding)
130
131
132
133 # decodes svp64 assembly listings and creates EXT001 svp64 prefixes
134 class SVP64:
135 def __init__(self, lst):
136 self.lst = lst
137 self.trans = self.translate(lst)
138
139 def __iter__(self):
140 for insn in self.trans:
141 yield insn
142
143 def translate(self, lst):
144 isa = ISA() # reads the v3.0B pseudo-code markdown files
145 svp64 = SVP64RM() # reads the svp64 Remap entries for registers
146 res = []
147 for insn in lst:
148 # find first space, to get opcode
149 ls = insn.split(' ')
150 opcode = ls[0]
151 # now find opcode fields
152 fields = ''.join(ls[1:]).split(',')
153 fields = list(map(str.strip, fields))
154 print ("opcode, fields", ls, opcode, fields)
155
156 # identify if is a svp64 mnemonic
157 if not opcode.startswith('sv.'):
158 res.append(insn) # unaltered
159 continue
160 opcode = opcode[3:] # strip leading "sv."
161
162 # start working on decoding the svp64 op: sv.basev30Bop/vec2/mode
163 opmodes = opcode.split("/") # split at "/"
164 v30b_op = opmodes.pop(0) # first is the v3.0B
165 # check instruction ends with dot
166 rc_mode = v30b_op.endswith('.')
167 if rc_mode:
168 v30b_op = v30b_op[:-1]
169
170 if v30b_op not in isa.instr:
171 raise Exception("opcode %s of '%s' not supported" % \
172 (v30b_op, insn))
173 if v30b_op not in svp64.instrs:
174 raise Exception("opcode %s of '%s' not an svp64 instruction" % \
175 (v30b_op, insn))
176 v30b_regs = isa.instr[v30b_op].regs[0] # get regs info "RT, RA, RB"
177 rm = svp64.instrs[v30b_op] # one row of the svp64 RM CSV
178 print ("v3.0B op", v30b_op, "Rc=1" if rc_mode else '')
179 print ("v3.0B regs", opcode, v30b_regs)
180 print (rm)
181
182 # right. the first thing to do is identify the ordering of
183 # the registers, by name. the EXTRA2/3 ordering is in
184 # rm['0']..rm['3'] but those fields contain the names RA, BB
185 # etc. we have to read the pseudocode to understand which
186 # reg is which in our instruction. sigh.
187
188 # first turn the svp64 rm into a "by name" dict, recording
189 # which position in the RM EXTRA it goes into
190 # also: record if the src or dest was a CR, for sanity-checking
191 # (elwidth overrides on CRs are banned)
192 dest_reg_cr, src_reg_cr = False, False
193 svp64_reg_byname = {}
194 for i in range(4):
195 rfield = rm[str(i)]
196 if not rfield or rfield == '0':
197 continue
198 print ("EXTRA field", i, rfield)
199 rfield = rfield.split(";") # s:RA;d:CR1 etc.
200 for r in rfield:
201 rtype = r[0]
202 # TODO: ignoring s/d makes it impossible to do
203 # LD/ST-with-update.
204 r = r[2:] # ignore s: and d:
205 svp64_reg_byname[r] = i # this reg in EXTRA position 0-3
206 # check the regtype (if CR, record that)
207 regtype = get_regtype(r)
208 if regtype in ['CR_3bit', 'CR_5bit']:
209 if rtype == 'd':
210 dest_reg_cr = True
211 if rtype == 'd':
212 src_reg_cr = True
213
214 print ("EXTRA field index, by regname", svp64_reg_byname)
215
216 # okaaay now we identify the field value (opcode N,N,N) with
217 # the pseudo-code info (opcode RT, RA, RB)
218 assert len(fields) == len(v30b_regs), \
219 "length of fields %s must match insn `%s`" % \
220 (str(v30b_regs), insn)
221 opregfields = zip(fields, v30b_regs) # err that was easy
222
223 # now for each of those find its place in the EXTRA encoding
224 extras = OrderedDict()
225 for idx, (field, regname) in enumerate(opregfields):
226 extra = svp64_reg_byname.get(regname, None)
227 regtype = get_regtype(regname)
228 extras[extra] = (idx, field, regname, regtype)
229 print (" ", extra, extras[extra])
230
231 # great! got the extra fields in their associated positions:
232 # also we know the register type. now to create the EXTRA encodings
233 etype = rm['Etype'] # Extra type: EXTRA3/EXTRA2
234 ptype = rm['Ptype'] # Predication type: Twin / Single
235 extra_bits = 0
236 v30b_newfields = []
237 for extra_idx, (idx, field, regname, regtype) in extras.items():
238 # is it a field we don't alter/examine? if so just put it
239 # into newfields
240 if regtype is None:
241 v30b_newfields.append(field)
242
243 # first, decode the field number. "5.v" or "3.s" or "9"
244 field = field.split(".")
245 regmode = 'scalar' # default
246 if len(field) == 2:
247 if field[1] == 's':
248 regmode = 'scalar'
249 elif field[1] == 'v':
250 regmode = 'vector'
251 field = int(field[0]) # actual register number
252 print (" ", regmode, field, end=" ")
253
254 # XXX TODO: the following is a bit of a laborious repeated
255 # mess, which could (and should) easily be parameterised.
256
257 # encode SV-GPR field into extra, v3.0field
258 if regtype == 'GPR':
259 sv_extra, field = get_extra_gpr(etype, regmode, field)
260 # now sanity-check. EXTRA3 is ok, EXTRA2 has limits
261 # (and shrink to a single bit if ok)
262 if etype == 'EXTRA2':
263 if regmode == 'scalar':
264 # range is r0-r63 in increments of 1
265 assert (sv_extra >> 1) == 0, \
266 "scalar GPR %s cannot fit into EXTRA2 %s" % \
267 (regname, str(extras[extra_idx]))
268 # all good: encode as scalar
269 sv_extra = sv_extra & 0b01
270 else:
271 # range is r0-r127 in increments of 4
272 assert sv_extra & 0b01 == 0, \
273 "vector field %s cannot fit into EXTRA2 %s" % \
274 (regname, str(extras[extra_idx]))
275 # all good: encode as vector (bit 2 set)
276 sv_extra = 0b10 | (sv_extra >> 1)
277 elif regmode == 'vector':
278 # EXTRA3 vector bit needs marking
279 sv_extra |= 0b100
280
281 # encode SV-CR 3-bit field into extra, v3.0field
282 elif regtype == 'CR_3bit':
283 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
284 # now sanity-check (and shrink afterwards)
285 if etype == 'EXTRA2':
286 if regmode == 'scalar':
287 # range is CR0-CR15 in increments of 1
288 assert (sv_extra >> 1) == 0, \
289 "scalar CR %s cannot fit into EXTRA2 %s" % \
290 (regname, str(extras[extra_idx]))
291 # all good: encode as scalar
292 sv_extra = sv_extra & 0b01
293 else:
294 # range is CR0-CR127 in increments of 16
295 assert sv_extra & 0b111 == 0, \
296 "vector CR %s cannot fit into EXTRA2 %s" % \
297 (regname, str(extras[extra_idx]))
298 # all good: encode as vector (bit 2 set)
299 sv_extra = 0b10 | (sv_extra >> 3)
300 else:
301 if regmode == 'scalar':
302 # range is CR0-CR31 in increments of 1
303 assert (sv_extra >> 2) == 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 & 0b11
308 else:
309 # range is CR0-CR127 in increments of 8
310 assert sv_extra & 0b11 == 0, \
311 "vector CR %s cannot fit into EXTRA2 %s" % \
312 (regname, str(extras[extra_idx]))
313 # all good: encode as vector (bit 3 set)
314 sv_extra = 0b100 | (sv_extra >> 2)
315
316 # encode SV-CR 5-bit field into extra, v3.0field
317 # *sigh* this is the same as 3-bit except the 2 LSBs are
318 # passed through
319 elif regtype == 'CR_5bit':
320 cr_subfield = field & 0b11
321 field = field >> 2 # strip bottom 2 bits
322 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
323 # now sanity-check (and shrink afterwards)
324 if etype == 'EXTRA2':
325 if regmode == 'scalar':
326 # range is CR0-CR15 in increments of 1
327 assert (sv_extra >> 1) == 0, \
328 "scalar CR %s cannot fit into EXTRA2 %s" % \
329 (regname, str(extras[extra_idx]))
330 # all good: encode as scalar
331 sv_extra = sv_extra & 0b01
332 else:
333 # range is CR0-CR127 in increments of 16
334 assert sv_extra & 0b111 == 0, \
335 "vector CR %s cannot fit into EXTRA2 %s" % \
336 (regname, str(extras[extra_idx]))
337 # all good: encode as vector (bit 2 set)
338 sv_extra = 0b10 | (sv_extra >> 3)
339 else:
340 if regmode == 'scalar':
341 # range is CR0-CR31 in increments of 1
342 assert (sv_extra >> 2) == 0, \
343 "scalar CR %s cannot fit into EXTRA2 %s" % \
344 (regname, str(extras[extra_idx]))
345 # all good: encode as scalar
346 sv_extra = sv_extra & 0b11
347 else:
348 # range is CR0-CR127 in increments of 8
349 assert sv_extra & 0b11 == 0, \
350 "vector CR %s cannot fit into EXTRA2 %s" % \
351 (regname, str(extras[extra_idx]))
352 # all good: encode as vector (bit 3 set)
353 sv_extra = 0b100 | (sv_extra >> 2)
354
355 # reconstruct the actual 5-bit CR field
356 field = (field << 2) | cr_subfield
357
358 # capture the extra field info
359 print ("=>", "%5s" % bin(sv_extra), field)
360 extras[extra_idx] = sv_extra
361
362 # append altered field value to v3.0b
363 v30b_newfields.append(str(field))
364
365 print ("new v3.0B fields", v30b_op, v30b_newfields)
366 print ("extras", extras)
367
368 # rright. now we have all the info. start creating SVP64 RM
369 svp64_rm = 0b0
370
371 # begin with EXTRA fields
372 for idx, sv_extra in extras.items():
373 if idx is None: continue
374 # start at bit 10, work up 2/3 times EXTRA idx
375 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
376 svp64_rm |= sv_extra << (10+idx*offs)
377
378 # parts of svp64_rm
379 mmode = 0 # bit 0
380 pmask = 0 # bits 1-3
381 destwid = 0 # bits 4-5
382 srcwid = 0 # bits 6-7
383 subvl = 0 # bits 8-9
384 smask = 0 # bits 16-18 but only for twin-predication
385 mode = 0 # bits 19-23
386
387 has_pmask = False
388 has_smask = False
389
390 saturation = None
391 src_zero = 0
392 dst_zero = 0
393 sv_mode = None
394
395 mapreduce = False
396 mapreduce_crm = False
397 mapreduce_svm = False
398
399 predresult = False
400 failfirst = False
401
402 # ok let's start identifying opcode augmentation fields
403 for encmode in opmodes:
404 # predicate mask (dest)
405 if encmode.startswith("m="):
406 pme = encmode
407 pmmode, pmask = decode_predicate(encmode[2:])
408 mmode = pmmode
409 has_pmask = True
410 # predicate mask (src, twin-pred)
411 elif encmode.startswith("sm="):
412 sme = encmode
413 smmode, smask = decode_predicate(encmode[3:])
414 mmode = smmode
415 has_smask = True
416 # vec2/3/4
417 elif encmode.startswith("vec"):
418 subvl = decode_subvl(encmode[3:])
419 # elwidth
420 elif encmode.startswith("ew="):
421 destwid = decode_elwidth(encmode[3:])
422 elif encmode.startswith("sw="):
423 srcwid = decode_elwidth(encmode[3:])
424 # saturation
425 elif encmode == 'sats':
426 assert sv_mode is None
427 saturation = 1
428 sv_mode = 0b10
429 elif encmode == 'satu':
430 assert sv_mode is None
431 sv_mode = 0b10
432 saturation = 0
433 # predicate zeroing
434 elif encmode == 'sz':
435 src_zero = 1
436 elif encmode == 'dz':
437 dst_zero = 1
438 # failfirst
439 elif encmode.startswith("ff="):
440 assert sv_mode is None
441 sv_mode = 0b01
442 failfirst = decode_ffirst(encmode[3:])
443 # predicate-result, interestingly same as fail-first
444 elif encmode.startswith("pr="):
445 assert sv_mode is None
446 sv_mode = 0b11
447 predresult = decode_ffirst(encmode[3:])
448 # map-reduce mode
449 elif encmode == 'mr':
450 assert sv_mode is None
451 sv_mode = 0b00
452 mapreduce = True
453 elif encmode == 'crm': # CR on map-reduce
454 assert sv_mode is None
455 sv_mode = 0b00
456 mapreduce_crm = True
457 elif encmode == 'svm': # sub-vector mode
458 mapreduce_svm = True
459
460 # sanity-check that 2Pred mask is same mode
461 if has_pmask and has_smask:
462 assert smmode == pmmode, \
463 "predicate masks %s and %s must be same reg type" % \
464 (pme, sme)
465
466 # sanity-check that twin-predication mask only specified in 2P mode
467 if ptype == '1P':
468 assert has_smask == False, \
469 "source-mask can only be specified on Twin-predicate ops"
470
471 # construct the mode field, doing sanity-checking along the way
472
473 if mapreduce_svm:
474 assert sv_mode == 0b00, "sub-vector mode in mapreduce only"
475 assert subvl != 0, "sub-vector mode not possible on SUBVL=1"
476
477 if src_zero:
478 assert has_smask, "src zeroing requires a source predicate"
479 if dst_zero:
480 assert has_pmask, "dest zeroing requires a dest predicate"
481
482 # "normal" mode
483 if sv_mode is None:
484 mode |= (src_zero << 3) | (dst_zero << 4) # predicate zeroing
485 sv_mode = 0b00
486
487 # "mapreduce" modes
488 elif sv_mode == 0b00:
489 mode |= (0b1<<2) # sets mapreduce
490 assert dst_zero == 0, "dest-zero not allowed in mapreduce mode"
491 if mapreduce_crm:
492 mode |= (0b1<<4) # sets CRM mode
493 assert rc_mode, "CRM only allowed when Rc=1"
494 # bit of weird encoding to jam zero-pred or SVM mode in.
495 # SVM mode can be enabled only when SUBVL=2/3/4 (vec2/3/4)
496 if subvl == 0:
497 mode |= (src_zero << 3) # predicate src-zeroing
498 elif mapreduce_svm:
499 mode |= (1 << 3) # SVM mode
500
501 # "failfirst" modes
502 elif sv_mode == 0b01:
503 assert dst_zero == 0, "dest-zero not allowed in failfirst mode"
504 if failfirst == 'RC1':
505 mode |= (0b1<<4) # sets RC1 mode
506 mode |= (src_zero << 3) # predicate src-zeroing
507 assert rc_mode==False, "ffirst RC1 only possible when Rc=0"
508 elif failfirst == '~RC1':
509 mode |= (0b1<<4) # sets RC1 mode...
510 mode |= (src_zero << 3) # predicate src-zeroing
511 mode |= (0b1<<2) # ... with inversion
512 assert rc_mode==False, "ffirst RC1 only possible when Rc=0"
513 else:
514 assert src_zero == 0, "src-zero not allowed in ffirst BO"
515 assert rc_mode, "ffirst BO only possible when Rc=1"
516 mode |= (failfirst << 2) # set BO
517
518 # "saturation" modes
519 elif sv_mode == 0b10:
520 mode |= (src_zero << 3) | (dst_zero << 4) # predicate zeroing
521 mode |= (saturation<<2) # sets signed/unsigned saturation
522
523 # "predicate-result" modes. err... code-duplication from ffirst
524 elif sv_mode == 0b11:
525 assert dst_zero == 0, "dest-zero not allowed in predresult mode"
526 if predresult == 'RC1':
527 mode |= (0b1<<4) # sets RC1 mode
528 mode |= (src_zero << 3) # predicate src-zeroing
529 assert rc_mode==False, "pr-mode RC1 only possible when Rc=0"
530 elif predresult == '~RC1':
531 mode |= (0b1<<4) # sets RC1 mode...
532 mode |= (src_zero << 3) # predicate src-zeroing
533 mode |= (0b1<<2) # ... with inversion
534 assert rc_mode==False, "pr-mode RC1 only possible when Rc=0"
535 else:
536 assert src_zero == 0, "src-zero not allowed in pr-mode BO"
537 assert rc_mode, "pr-mode BO only possible when Rc=1"
538 mode |= (predresult << 2) # set BO
539
540 # whewww.... modes all done :)
541 # now put into svp64_rm
542 mode |= sv_mode
543 svp64_rm |= (mode << 19) # mode: bits 19-23
544
545 # put in predicate masks into svp64_rm
546 if ptype == '2P':
547 svp64_rm |= (smask << 16) # source pred: bits 16-18
548 svp64_rm |= (mmode) # mask mode: bit 0
549 svp64_rm |= (pmask << 1) # 1-pred: bits 1-3
550
551 # and subvl
552 svp64_rm += (subvl << 8) # subvl: bits 8-9
553
554 # put in elwidths
555 svp64_rm += (srcwid << 6) # srcwid: bits 6-7
556 svp64_rm += (destwid << 4) # destwid: bits 4-5
557
558 # nice debug printout. (and now for something completely different)
559 # https://youtu.be/u0WOIwlXE9g?t=146
560 print ("svp64_rm", hex(svp64_rm), bin(svp64_rm))
561 print (" mmode 0 :", bin(mmode))
562 print (" pmask 1-3 :", bin(pmask))
563 print (" dstwid 4-5 :", bin(destwid))
564 print (" srcwid 6-7 :", bin(srcwid))
565 print (" subvl 8-9 :", bin(subvl))
566 print (" mode 19-23:", bin(mode))
567 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
568 for idx, sv_extra in extras.items():
569 if idx is None: continue
570 start = (10+idx*offs)
571 end = start + offs-1
572 print (" extra%d %2d-%2d:" % (idx, start, end),
573 bin(sv_extra))
574 if ptype == '2P':
575 print (" smask 16-17:", bin(smask))
576 print ()
577
578 return res
579
580 if __name__ == '__main__':
581 isa = SVP64(['slw 3, 1, 4',
582 'extsw 5, 3',
583 'sv.extsw 5, 3',
584 'sv.cmpi 5, 1, 3, 2',
585 'sv.setb 5, 31',
586 'sv.isel 64.v, 3, 2, 65.v',
587 'sv.setb/m=r3/sm=1<<r3 5, 31',
588 'sv.setb/vec2 5, 31',
589 'sv.setb/sw=8/ew=16 5, 31',
590 'sv.extsw./ff=eq 5, 31',
591 'sv.extsw./satu/sz/dz/sm=r3/m=r3 5, 31',
592 'sv.extsw./pr=eq 5.v, 31',
593 ])
594 csvs = SVP64RM()