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