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