675d26b5e21e0d6f279cfd19bdd93057c0d3ae5d
[openpower-isa.git] / src / openpower / 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 creates
8 an EXT001-encoded "svp64 prefix" (as a .long) 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 Encoding format of arithmetic: https://libre-soc.org/openpower/sv/normal/
15 Encoding format of LDST: https://libre-soc.org/openpower/sv/ldst/
16 **TODO format of branches: https://libre-soc.org/openpower/sv/branches/**
17 **TODO format of CRs: https://libre-soc.org/openpower/sv/cr_ops/**
18 Bugtracker: https://bugs.libre-soc.org/show_bug.cgi?id=578
19 """
20
21 import os
22 import sys
23 from collections import OrderedDict
24
25 from openpower.decoder.isa.caller import (SVP64PrefixFields, SV64P_MAJOR_SIZE,
26 SV64P_PID_SIZE, SVP64RMFields,
27 SVP64RM_EXTRA2_SPEC_SIZE,
28 SVP64RM_EXTRA3_SPEC_SIZE,
29 SVP64RM_MODE_SIZE, SVP64RM_SMASK_SIZE,
30 SVP64RM_MMODE_SIZE, SVP64RM_MASK_SIZE,
31 SVP64RM_SUBVL_SIZE, SVP64RM_EWSRC_SIZE,
32 SVP64RM_ELWIDTH_SIZE)
33 from openpower.decoder.pseudo.pagereader import ISA
34 from openpower.decoder.power_svp64 import SVP64RM, get_regtype, decode_extra
35 from openpower.decoder.selectable_int import SelectableInt
36 from openpower.consts import SVP64MODE
37
38 # for debug logging
39 from openpower.util import log
40
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
127
128 def decode_ffirst(encoding):
129 if encoding in ['RC1', '~RC1']:
130 return encoding
131 return decode_bo(encoding)
132
133
134 def decode_reg(field):
135 # decode the field number. "5.v" or "3.s" or "9"
136 field = field.split(".")
137 regmode = 'scalar' # default
138 if len(field) == 2:
139 if field[1] == 's':
140 regmode = 'scalar'
141 elif field[1] == 'v':
142 regmode = 'vector'
143 field = int(field[0]) # actual register number
144 return field, regmode
145
146
147 def decode_imm(field):
148 ldst_imm = "(" in field and field[-1] == ')'
149 if ldst_imm:
150 return field[:-1].split("(")
151 else:
152 return None, field
153
154
155 def crf_extra(etype, regmode, field, extras):
156 """takes a CR Field number (CR0-CR127), splits into EXTRA2/3 and v3.0
157 the scalar/vector mode (crNN.v or crNN.s) changes both the format
158 of the EXTRA2/3 encoding as well as what range of registers is possible.
159 this function can be used for both BF/BFA and BA/BB/BT by first removing
160 the bottom 2 bits of BA/BB/BT then re-instating them after encoding.
161 see https://libre-soc.org/openpower/sv/svp64/appendix/#cr_extra
162 for specification
163 """
164 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
165 # now sanity-check (and shrink afterwards)
166 if etype == 'EXTRA2':
167 # 3-bit CR Field (BF, BFA) EXTRA2 encoding
168 if regmode == 'scalar':
169 # range is CR0-CR15 in increments of 1
170 assert (sv_extra >> 1) == 0, \
171 "scalar CR %s cannot fit into EXTRA2 %s" % \
172 (rname, str(extras[extra_idx]))
173 # all good: encode as scalar
174 sv_extra = sv_extra & 0b01
175 else: # vector
176 # range is CR0-CR127 in increments of 16
177 assert sv_extra & 0b111 == 0, \
178 "vector CR %s cannot fit into EXTRA2 %s" % \
179 (rname, str(extras[extra_idx]))
180 # all good: encode as vector (bit 2 set)
181 sv_extra = 0b10 | (sv_extra >> 3)
182 else:
183 # 3-bit CR Field (BF, BFA) EXTRA3 encoding
184 if regmode == 'scalar':
185 # range is CR0-CR31 in increments of 1
186 assert (sv_extra >> 2) == 0, \
187 "scalar CR %s cannot fit into EXTRA3 %s" % \
188 (rname, str(extras[extra_idx]))
189 # all good: encode as scalar
190 sv_extra = sv_extra & 0b11
191 else: # vector
192 # range is CR0-CR127 in increments of 8
193 assert sv_extra & 0b11 == 0, \
194 "vector CR %s cannot fit into EXTRA3 %s" % \
195 (rname, str(extras[extra_idx]))
196 # all good: encode as vector (bit 3 set)
197 sv_extra = 0b100 | (sv_extra >> 2)
198 return sv_extra, field
199
200
201 # decodes svp64 assembly listings and creates EXT001 svp64 prefixes
202 class SVP64Asm:
203 def __init__(self, lst, bigendian=False, macros=None):
204 if macros is None:
205 macros = {}
206 self.macros = macros
207 self.lst = lst
208 self.trans = self.translate(lst)
209 self.isa = ISA() # reads the v3.0B pseudo-code markdown files
210 self.svp64 = SVP64RM() # reads the svp64 Remap entries for registers
211 assert bigendian == False, "error, bigendian not supported yet"
212
213 def __iter__(self):
214 yield from self.trans
215
216 def translate_one(self, insn, macros=None):
217 if macros is None:
218 macros = {}
219 macros.update(self.macros)
220 isa = self.isa
221 svp64 = self.svp64
222 # find first space, to get opcode
223 ls = insn.split(' ')
224 opcode = ls[0]
225 # now find opcode fields
226 fields = ''.join(ls[1:]).split(',')
227 mfields = list(map(str.strip, fields))
228 log("opcode, fields", ls, opcode, mfields)
229 fields = []
230 # macro substitution
231 for field in mfields:
232 fields.append(macro_subst(macros, field))
233 log("opcode, fields substed", ls, opcode, fields)
234
235 # this is a *32-bit-only* instruction. it controls SVSTATE.
236 # it is *not* a 64-bit-prefixed Vector instruction (no sv.setvl),
237 # it is a Vector *control* instruction.
238 # note: EXT022 is the "sandbox" major opcode so it's fine to add
239
240 # sigh have to do setvl here manually for now...
241 # note the subtract one from SVi.
242 if opcode in ["setvl", "setvl."]:
243 # 1.6.28 SVL-FORM - from fields.txt
244 # |0 |6 |11 |16 |23 |24 |25 |26 |31 |
245 # | PO | RT | RA | SVi |ms |vs |vf | XO |Rc |
246 insn = 22 << (31-5) # opcode 22, bits 0-5
247 fields = list(map(int, fields))
248 insn |= fields[0] << (31-10) # RT , bits 6-10
249 insn |= fields[1] << (31-15) # RA , bits 11-15
250 insn |= (fields[2]-1) << (31-22) # SVi , bits 16-22
251 insn |= fields[3] << (31-25) # vf , bit 25
252 insn |= fields[4] << (31-24) # vs , bit 24
253 insn |= fields[5] << (31-23) # ms , bit 23
254 insn |= 0b11011 << (31-30) # XO , bits 26..30
255 if opcode == 'setvl.':
256 insn |= 1 << (31-31) # Rc=1 , bit 31
257 log("setvl", bin(insn))
258 yield ".long 0x%x" % insn
259 return
260
261 # this is a 32-bit instruction. it updates SVSTATE.
262 # it *can* be SVP64-prefixed, to indicate that its registers
263 # are Vectorised.
264 # note: EXT022 is the "sandbox" major opcode so it's fine to add
265
266 # sigh have to do setvl here manually for now...
267 # note the subtract one from SVi.
268 if opcode in ["svstep", "svstep."]:
269 # 1.6.28 SVL-FORM - from fields.txt
270 # |0 |6 |11 |16 |23 |24 |25 |26 |31 |
271 # | PO | RT | RA | SVi |ms |vs |vf | XO |Rc |
272 insn = 22 << (31-5) # opcode 22, bits 0-5
273 fields = list(map(int, fields))
274 insn |= fields[0] << (31-10) # RT , bits 6-10
275 insn |= (fields[1]-1) << (31-22) # SVi , bits 16-22
276 insn |= fields[2] << (31-25) # vf , bit 25
277 insn |= 0b10011 << (31-30) # XO , bits 26..30
278 if opcode == 'svstep.':
279 insn |= 1 << (31-31) # Rc=1 , bit 31
280 log("svstep", bin(insn))
281 yield ".long 0x%x" % insn
282 return
283
284 # this is a *32-bit-only* instruction. it updates SVSHAPE and SVSTATE.
285 # it is *not* a 64-bit-prefixed Vector instruction (no sv.svshape),
286 # it is a Vector *control* instruction.
287 # note: EXT022 is the "sandbox" major opcode so it's fine to add
288
289 # and svshape. note that the dimension fields one subtracted from each
290 if opcode == 'svshape':
291 # 1.6.33 SVM-FORM from fields.txt
292 # |0 |6 |11 |16 |21 |25 |26 |31 |
293 # |PO | SVxd | SVyd | SVzd | SVRM |vf | XO | / |
294 insn = 22 << (31-5) # opcode 22, bits 0-5
295 fields = list(map(int, fields))
296 insn |= (fields[0]-1) << (31-10) # SVxd , bits 6-10
297 insn |= (fields[1]-1) << (31-15) # SVyd , bits 11-15
298 insn |= (fields[2]-1) << (31-20) # SVzd , bits 16-20
299 insn |= (fields[3]) << (31-24) # SVRM , bits 21-24
300 insn |= (fields[4]) << (31-25) # vf , bits 25
301 insn |= 0b011001 << (31-31) # XO , bits 26..31
302 #insn &= ((1<<32)-1)
303 log("svshape", bin(insn))
304 yield ".long 0x%x" % insn
305 return
306
307 # this is a *32-bit-only* instruction. it updates the SVSHAPE SPR
308 # it is *not* a 64-bit-prefixed Vector instruction (no sv.svremap),
309 # it is a Vector *control* instruction.
310 # note: EXT022 is the "sandbox" major opcode so it's fine to add
311
312 # and svremap
313 if opcode == 'svremap':
314 # 1.6.34 SVRM-FORM from fields.txt
315 # |0 |6 |11 |13 |15 |17 |19 |21 |22 |26 |31 |
316 # |PO | SVme |mi0 | mi1 | mi2 | mo0 | mo1 |pst |/// | XO | / |
317 insn = 22 << (31-5) # opcode 22, bits 0-5
318 fields = list(map(int, fields))
319 insn |= fields[0] << (31-10) # SVme , bits 6-10
320 insn |= fields[1] << (31-12) # mi0 , bits 11-12
321 insn |= fields[2] << (31-14) # mi1 , bits 13-14
322 insn |= fields[3] << (31-16) # mi2 , bits 15-16
323 insn |= fields[4] << (31-18) # m00 , bits 17-18
324 insn |= fields[5] << (31-20) # m01 , bits 19-20
325 insn |= fields[6] << (31-21) # pst , bit 21
326 insn |= 0b111001 << (31-31) # XO , bits 26..31
327 log("svremap", bin(insn))
328 yield ".long 0x%x" % insn
329 return
330
331 # ok from here-on down these are added as 32-bit instructions
332 # and are here only because binutils (at present) doesn't have
333 # them (that's being fixed!)
334 # they can - if implementations then choose - be Vectorised
335 # (sv.fsins) because they are general-purpose scalar instructions
336
337 # and fsins
338 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
339 # however we are out of space with opcode 22
340 if opcode.startswith('fsins'):
341 fields = list(map(int, fields))
342 insn = 59 << (31-5) # opcode 59, bits 0-5
343 insn |= fields[0] << (31-10) # RT , bits 6-10
344 insn |= fields[1] << (31-20) # RB , bits 16-20
345 insn |= 0b1000001110 << (31-30) # XO , bits 21..30
346 if opcode == 'fsins.':
347 insn |= 1 << (31-31) # Rc=1 , bit 31
348 log("fsins", bin(insn))
349 yield ".long 0x%x" % insn
350 return
351
352 # and fcoss
353 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
354 # however we are out of space with opcode 22
355 if opcode.startswith('fcoss'):
356 fields = list(map(int, fields))
357 insn = 59 << (31-5) # opcode 59, bits 0-5
358 insn |= fields[0] << (31-10) # RT , bits 6-10
359 insn |= fields[1] << (31-20) # RB , bits 16-20
360 insn |= 0b1000101110 << (31-30) # XO , bits 21..30
361 if opcode == 'fcoss.':
362 insn |= 1 << (31-31) # Rc=1 , bit 31
363 log("fcoss", bin(insn))
364 yield ".long 0x%x" % insn
365 return
366
367 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
368 # however we are out of space with opcode 22
369 if opcode in ('ternlogi', 'ternlogi.'):
370 po = 5
371 xo = 0
372 rt = int(fields[0])
373 ra = int(fields[1])
374 rb = int(fields[2])
375 imm = int(fields[3])
376 rc = '.' in opcode
377 instr = po
378 instr = (instr << 5) | rt
379 instr = (instr << 5) | ra
380 instr = (instr << 5) | rb
381 instr = (instr << 8) | imm
382 instr = (instr << 2) | xo
383 instr = (instr << 1) | rc
384 asm = f"{opcode} {rt}, {ra}, {rb}, {imm}"
385 yield f".4byte {hex(instr)} # {asm}"
386 return
387
388 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
389 # however we are out of space with opcode 22
390 if opcode in ('grev', 'grevi', 'grevw', 'grevwi',
391 'grev.', 'grevi.', 'grevw.', 'grevwi.'):
392 po = 5
393 # _ matches fields in table at:
394 # https://libre-soc.org/openpower/sv/bitmanip/
395 xo = 0b1_0010_110
396 if 'w' in opcode:
397 xo |= 0b100_000
398 if 'i' in opcode:
399 xo |= 0b1000_000
400 Rc = 1 if '.' in opcode else 0
401 rt = int(fields[0])
402 ra = int(fields[1])
403 rb_imm = int(fields[2])
404 instr = po
405 instr = (instr << 5) | rt
406 instr = (instr << 5) | ra
407 if opcode == 'grevi' or opcode == 'grevi.':
408 assert 0 <= rb_imm < 64
409 instr = (instr << 6) | rb_imm
410 instr = (instr << 9) | xo
411 else:
412 assert 0 <= rb_imm < 32
413 instr = (instr << 5) | rb_imm
414 instr = (instr << 10) | xo
415 instr = (instr << 1) | Rc
416 asm = f"{opcode} {rt}, {ra}, {rb_imm}"
417 yield f".4byte {hex(instr)} # {asm}"
418 return
419
420 # and min/max
421 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
422 if opcode in ['mins', 'maxs', 'minu', 'maxu',
423 'mins.', 'maxs.', 'minu.', 'maxu.']:
424 if opcode[:4] == 'maxs':
425 XO = 0b0111001110
426 if opcode[:4] == 'maxu':
427 XO = 0b0011001110
428 if opcode[:4] == 'mins':
429 XO = 0b0101001110
430 if opcode[:4] == 'minu':
431 XO = 0b0001001110
432 fields = list(map(int, fields))
433 insn = 22 << (31-5) # opcode 22, bits 0-5
434 insn |= fields[0] << (31-10) # RT , bits 6-10
435 insn |= fields[1] << (31-15) # RA , bits 11-15
436 insn |= fields[2] << (31-20) # RB , bits 16-20
437 insn |= XO << (31-30) # XO , bits 21..30
438 if opcode.endswith('.'):
439 insn |= 1 << (31-31) # Rc=1 , bit 31
440 log("maxs", bin(insn))
441 yield ".long 0x%x" % insn
442 return
443
444 # and avgadd
445 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
446 if opcode in ['avgadd', ]:
447 if opcode[:6] == 'avgadd':
448 XO = 0b1101001110
449 fields = list(map(int, fields))
450 insn = 22 << (31-5) # opcode 22, bits 0-5
451 insn |= fields[0] << (31-10) # RT , bits 6-10
452 insn |= fields[1] << (31-15) # RA , bits 11-15
453 insn |= fields[2] << (31-20) # RB , bits 16-20
454 insn |= XO << (31-30) # XO , bits 21..30
455 if opcode.endswith('.'):
456 insn |= 1 << (31-31) # Rc=1 , bit 31
457 log("maxs", bin(insn))
458 yield ".long 0x%x" % insn
459 return
460
461 # identify if is a svp64 mnemonic
462 if not opcode.startswith('sv.'):
463 yield insn # unaltered
464 return
465 opcode = opcode[3:] # strip leading "sv"
466
467 # start working on decoding the svp64 op: sv.basev30Bop/vec2/mode
468 opmodes = opcode.split("/") # split at "/"
469 v30b_op = opmodes.pop(0) # first is the v3.0B
470 # check instruction ends with dot
471 rc_mode = v30b_op.endswith('.')
472 if rc_mode:
473 v30b_op = v30b_op[:-1]
474
475 # sigh again, have to recognised LD/ST bit-reverse instructions
476 # this has to be "processed" to fit into a v3.0B without the "sh"
477 # e.g. ldsh is actually ld
478 ldst_shift = v30b_op.startswith("l") and v30b_op.endswith("sh")
479
480 if v30b_op not in isa.instr:
481 raise Exception("opcode %s of '%s' not supported" %
482 (v30b_op, insn))
483
484 if ldst_shift:
485 # okaay we need to process the fields and make this:
486 # ldsh RT, SVD(RA), RC - 11 bits for SVD, 5 for RC
487 # into this:
488 # ld RT, D(RA) - 16 bits
489 # likewise same for SVDS (9 bits for SVDS, 5 for RC, 14 bits for DS)
490 form = isa.instr[v30b_op].form # get form (SVD-Form, SVDS-Form)
491
492 newfields = []
493 for field in fields:
494 # identify if this is a ld/st immediate(reg) thing
495 ldst_imm = "(" in field and field[-1] == ')'
496 if ldst_imm:
497 newfields.append(field[:-1].split("("))
498 else:
499 newfields.append(field)
500
501 immed, RA = newfields[1]
502 immed = int(immed)
503 RC = int(newfields.pop(2)) # better be an integer number!
504 if form == 'SVD': # 16 bit: immed 11 bits, RC shift up 11
505 immed = (immed & 0b11111111111) | (RC << 11)
506 if immed & (1 << 15): # should be negative
507 immed -= 1 << 16
508 if form == 'SVDS': # 14 bit: immed 9 bits, RC shift up 9
509 immed = (immed & 0b111111111) | (RC << 9)
510 if immed & (1 << 13): # should be negative
511 immed -= 1 << 14
512 newfields[1] = "%d(%s)" % (immed, RA)
513 fields = newfields
514
515 # and strip off "sh" from end, and add "sh" to opmodes, instead
516 v30b_op = v30b_op[:-2]
517 opmodes.append("sh")
518 log("rewritten", v30b_op, opmodes, fields)
519
520 if v30b_op not in svp64.instrs:
521 raise Exception("opcode %s of '%s' not an svp64 instruction" %
522 (v30b_op, insn))
523 v30b_regs = isa.instr[v30b_op].regs[0] # get regs info "RT, RA, RB"
524 rm = svp64.instrs[v30b_op] # one row of the svp64 RM CSV
525 log("v3.0B op", v30b_op, "Rc=1" if rc_mode else '')
526 log("v3.0B regs", opcode, v30b_regs)
527 log("RM", rm)
528
529 # right. the first thing to do is identify the ordering of
530 # the registers, by name. the EXTRA2/3 ordering is in
531 # rm['0']..rm['3'] but those fields contain the names RA, BB
532 # etc. we have to read the pseudocode to understand which
533 # reg is which in our instruction. sigh.
534
535 # first turn the svp64 rm into a "by name" dict, recording
536 # which position in the RM EXTRA it goes into
537 # also: record if the src or dest was a CR, for sanity-checking
538 # (elwidth overrides on CRs are banned)
539 decode = decode_extra(rm)
540 dest_reg_cr, src_reg_cr, svp64_src, svp64_dest = decode
541
542 log("EXTRA field index, src", svp64_src)
543 log("EXTRA field index, dest", svp64_dest)
544
545 # okaaay now we identify the field value (opcode N,N,N) with
546 # the pseudo-code info (opcode RT, RA, RB)
547 assert len(fields) == len(v30b_regs), \
548 "length of fields %s must match insn `%s` fields %s" % \
549 (str(v30b_regs), insn, str(fields))
550 opregfields = zip(fields, v30b_regs) # err that was easy
551
552 # now for each of those find its place in the EXTRA encoding
553 # note there is the possibility (for LD/ST-with-update) of
554 # RA occurring **TWICE**. to avoid it getting added to the
555 # v3.0B suffix twice, we spot it as a duplicate, here
556 extras = OrderedDict()
557 for idx, (field, regname) in enumerate(opregfields):
558 imm, regname = decode_imm(regname)
559 rtype = get_regtype(regname)
560 log(" idx find", rtype, idx, field, regname, imm)
561 if rtype is None:
562 # probably an immediate field, append it straight
563 extras[('imm', idx, False)] = (idx, field, None, None, None)
564 continue
565 extra = svp64_src.get(regname, None)
566 if extra is not None:
567 extra = ('s', extra, False) # not a duplicate
568 extras[extra] = (idx, field, regname, rtype, imm)
569 log(" idx src", idx, extra, extras[extra])
570 dextra = svp64_dest.get(regname, None)
571 log("regname in", regname, dextra)
572 if dextra is not None:
573 is_a_duplicate = extra is not None # duplicate spotted
574 dextra = ('d', dextra, is_a_duplicate)
575 extras[dextra] = (idx, field, regname, rtype, imm)
576 log(" idx dst", idx, extra, extras[dextra])
577
578 # great! got the extra fields in their associated positions:
579 # also we know the register type. now to create the EXTRA encodings
580 etype = rm['Etype'] # Extra type: EXTRA3/EXTRA2
581 ptype = rm['Ptype'] # Predication type: Twin / Single
582 extra_bits = 0
583 v30b_newfields = []
584 for extra_idx, (idx, field, rname, rtype, iname) in extras.items():
585 # is it a field we don't alter/examine? if so just put it
586 # into newfields
587 if rtype is None:
588 v30b_newfields.append(field)
589 continue
590
591 # identify if this is a ld/st immediate(reg) thing
592 ldst_imm = "(" in field and field[-1] == ')'
593 if ldst_imm:
594 immed, field = field[:-1].split("(")
595
596 field, regmode = decode_reg(field)
597 log(" ", extra_idx, rname, rtype,
598 regmode, iname, field, end=" ")
599
600 # see Mode field https://libre-soc.org/openpower/sv/svp64/
601 # XXX TODO: the following is a bit of a laborious repeated
602 # mess, which could (and should) easily be parameterised.
603 # XXX also TODO: the LD/ST modes which are different
604 # https://libre-soc.org/openpower/sv/ldst/
605
606 # rright. SVP64 register numbering is from 0 to 127
607 # for GPRs, FPRs *and* CR Fields, where for v3.0 the GPRs and RPFs
608 # are 0-31 and CR Fields are only 0-7. the SVP64 RM "Extra"
609 # area is used to extend the numbering from the 32-bit
610 # instruction, and also to record whether the register
611 # is scalar or vector. on a per-operand basis. this
612 # results in a slightly finnicky encoding: here we go...
613
614 # encode SV-GPR and SV-FPR field into extra, v3.0field
615 if rtype in ['GPR', 'FPR']:
616 sv_extra, field = get_extra_gpr(etype, regmode, field)
617 # now sanity-check. EXTRA3 is ok, EXTRA2 has limits
618 # (and shrink to a single bit if ok)
619 if etype == 'EXTRA2':
620 if regmode == 'scalar':
621 # range is r0-r63 in increments of 1
622 assert (sv_extra >> 1) == 0, \
623 "scalar GPR %s cannot fit into EXTRA2 %s" % \
624 (rname, str(extras[extra_idx]))
625 # all good: encode as scalar
626 sv_extra = sv_extra & 0b01
627 else:
628 # range is r0-r127 in increments of 2 (r0 r2 ... r126)
629 assert sv_extra & 0b01 == 0, \
630 "%s: vector field %s cannot fit " \
631 "into EXTRA2 %s" % \
632 (insn, rname, str(extras[extra_idx]))
633 # all good: encode as vector (bit 2 set)
634 sv_extra = 0b10 | (sv_extra >> 1)
635 elif regmode == 'vector':
636 # EXTRA3 vector bit needs marking
637 sv_extra |= 0b100
638
639 # encode SV-CR 3-bit field into extra, v3.0field.
640 # 3-bit is for things like BF and BFA
641 elif rtype == 'CR_3bit':
642 sv_extra, field = crf_extra(etype, regmode, field, extras)
643
644 # encode SV-CR 5-bit field into extra, v3.0field
645 # 5-bit is for things like BA BB BC BT etc.
646 # *sigh* this is the same as 3-bit except the 2 LSBs of the
647 # 5-bit field are passed through unaltered.
648 elif rtype == 'CR_5bit':
649 cr_subfield = field & 0b11 # record bottom 2 bits for later
650 field = field >> 2 # strip bottom 2 bits
651 # use the exact same 3-bit function for the top 3 bits
652 sv_extra, field = crf_extra(etype, regmode, field, extras)
653 # reconstruct the actual 5-bit CR field (preserving the
654 # bottom 2 bits, unaltered)
655 field = (field << 2) | cr_subfield
656
657 else:
658 raise Exception("no type match: %s" % rtype)
659
660 # capture the extra field info
661 log("=>", "%5s" % bin(sv_extra), field)
662 extras[extra_idx] = sv_extra
663
664 # append altered field value to v3.0b, differs for LDST
665 # note that duplicates are skipped e.g. EXTRA2 contains
666 # *BOTH* s:RA *AND* d:RA which happens on LD/ST-with-update
667 srcdest, idx, duplicate = extra_idx
668 if duplicate: # skip adding to v3.0b fields, already added
669 continue
670 if ldst_imm:
671 v30b_newfields.append(("%s(%s)" % (immed, str(field))))
672 else:
673 v30b_newfields.append(str(field))
674
675 log("new v3.0B fields", v30b_op, v30b_newfields)
676 log("extras", extras)
677
678 # rright. now we have all the info. start creating SVP64 RM
679 svp64_rm = SVP64RMFields()
680
681 # begin with EXTRA fields
682 for idx, sv_extra in extras.items():
683 log(idx)
684 if idx is None:
685 continue
686 if idx[0] == 'imm':
687 continue
688 srcdest, idx, duplicate = idx
689 if etype == 'EXTRA2':
690 svp64_rm.extra2[idx].eq(
691 SelectableInt(sv_extra, SVP64RM_EXTRA2_SPEC_SIZE))
692 else:
693 svp64_rm.extra3[idx].eq(
694 SelectableInt(sv_extra, SVP64RM_EXTRA3_SPEC_SIZE))
695
696 # identify if the op is a LD/ST. the "blegh" way. copied
697 # from power_enums. TODO, split the list _insns down.
698 is_ld = v30b_op in [
699 "lbarx", "lbz", "lbzu", "lbzux", "lbzx", # load byte
700 "ld", "ldarx", "ldbrx", "ldu", "ldux", "ldx", # load double
701 "lfs", "lfsx", "lfsu", "lfsux", # FP load single
702 "lfd", "lfdx", "lfdu", "lfdux", "lfiwzx", "lfiwax", # FP load dbl
703 "lha", "lharx", "lhau", "lhaux", "lhax", # load half
704 "lhbrx", "lhz", "lhzu", "lhzux", "lhzx", # more load half
705 "lwa", "lwarx", "lwaux", "lwax", "lwbrx", # load word
706 "lwz", "lwzcix", "lwzu", "lwzux", "lwzx", # more load word
707 ]
708 is_st = v30b_op in [
709 "stb", "stbcix", "stbcx", "stbu", "stbux", "stbx",
710 "std", "stdbrx", "stdcx", "stdu", "stdux", "stdx",
711 "stfs", "stfsx", "stfsu", "stfux", # FP store sgl
712 "stfd", "stfdx", "stfdu", "stfdux", "stfiwx", # FP store dbl
713 "sth", "sthbrx", "sthcx", "sthu", "sthux", "sthx",
714 "stw", "stwbrx", "stwcx", "stwu", "stwux", "stwx",
715 ]
716 # use this to determine if the SVP64 RM format is different.
717 # see https://libre-soc.org/openpower/sv/ldst/
718 is_ldst = is_ld or is_st
719
720 # branch-conditional detection
721 is_bc = v30b_op in [
722 "bc", "bclr",
723 ]
724
725 # parts of svp64_rm
726 mmode = 0 # bit 0
727 pmask = 0 # bits 1-3
728 destwid = 0 # bits 4-5
729 srcwid = 0 # bits 6-7
730 subvl = 0 # bits 8-9
731 smask = 0 # bits 16-18 but only for twin-predication
732 mode = 0 # bits 19-23
733
734 mask_m_specified = False
735 has_pmask = False
736 has_smask = False
737
738 saturation = None
739 src_zero = 0
740 dst_zero = 0
741 sv_mode = None
742
743 mapreduce = False
744 reverse_gear = False
745 mapreduce_crm = False
746 mapreduce_svm = False
747
748 predresult = False
749 failfirst = False
750 ldst_elstride = 0
751
752 # branch-conditional bits
753 bc_all = 0
754 bc_lru = 0
755 bc_brc = 0
756 bc_svstep = 0
757 bc_vsb = 0
758 bc_vlset = 0
759 bc_vli = 0
760 bc_snz = 0
761
762 # ok let's start identifying opcode augmentation fields
763 for encmode in opmodes:
764 # predicate mask (src and dest)
765 if encmode.startswith("m="):
766 pme = encmode
767 pmmode, pmask = decode_predicate(encmode[2:])
768 smmode, smask = pmmode, pmask
769 mmode = pmmode
770 mask_m_specified = True
771 # predicate mask (dest)
772 elif encmode.startswith("dm="):
773 pme = encmode
774 pmmode, pmask = decode_predicate(encmode[3:])
775 mmode = pmmode
776 has_pmask = True
777 # predicate mask (src, twin-pred)
778 elif encmode.startswith("sm="):
779 sme = encmode
780 smmode, smask = decode_predicate(encmode[3:])
781 mmode = smmode
782 has_smask = True
783 # shifted LD/ST
784 elif encmode.startswith("sh"):
785 ldst_shift = True
786 # vec2/3/4
787 elif encmode.startswith("vec"):
788 subvl = decode_subvl(encmode[3:])
789 # elwidth
790 elif encmode.startswith("ew="):
791 destwid = decode_elwidth(encmode[3:])
792 elif encmode.startswith("sw="):
793 srcwid = decode_elwidth(encmode[3:])
794 # element-strided LD/ST
795 elif encmode == 'els':
796 ldst_elstride = 1
797 # saturation
798 elif encmode == 'sats':
799 assert sv_mode is None
800 saturation = 1
801 sv_mode = 0b10
802 elif encmode == 'satu':
803 assert sv_mode is None
804 sv_mode = 0b10
805 saturation = 0
806 # predicate zeroing
807 elif encmode == 'sz':
808 src_zero = 1
809 elif encmode == 'dz':
810 dst_zero = 1
811 # failfirst
812 elif encmode.startswith("ff="):
813 assert sv_mode is None
814 sv_mode = 0b01
815 failfirst = decode_ffirst(encmode[3:])
816 # predicate-result, interestingly same as fail-first
817 elif encmode.startswith("pr="):
818 assert sv_mode is None
819 sv_mode = 0b11
820 predresult = decode_ffirst(encmode[3:])
821 # map-reduce mode, reverse-gear
822 elif encmode == 'mrr':
823 assert sv_mode is None
824 sv_mode = 0b00
825 mapreduce = True
826 reverse_gear = True
827 # map-reduce mode
828 elif encmode == 'mr':
829 assert sv_mode is None
830 sv_mode = 0b00
831 mapreduce = True
832 elif encmode == 'crm': # CR on map-reduce
833 assert sv_mode is None
834 sv_mode = 0b00
835 mapreduce_crm = True
836 elif encmode == 'svm': # sub-vector mode
837 mapreduce_svm = True
838 elif is_bc:
839 if encmode == 'all':
840 bc_all = 1
841 elif encmode == 'st': # svstep mode
842 bc_step = 1
843 elif encmode == 'sr': # svstep BRc mode
844 bc_step = 1
845 bc_brc = 1
846 elif encmode == 'vs': # VLSET mode
847 bc_vlset = 1
848 elif encmode == 'vsi': # VLSET mode with VLI (VL inclusives)
849 bc_vlset = 1
850 bc_vli = 1
851 elif encmode == 'vsb': # VLSET mode with VSb
852 bc_vlset = 1
853 bc_vsb = 1
854 elif encmode == 'vsbi': # VLSET mode with VLI and VSb
855 bc_vlset = 1
856 bc_vli = 1
857 bc_vsb = 1
858 elif encmode == 'snz': # sz (only) already set above
859 src_zero = 1
860 bc_snz = 1
861 elif encmode == 'lu': # LR update mode
862 bc_lru = 1
863 else:
864 raise AssertionError("unknown encmode %s" % encmode)
865 else:
866 raise AssertionError("unknown encmode %s" % encmode)
867
868 if ptype == '2P':
869 # since m=xx takes precedence (overrides) sm=xx and dm=xx,
870 # treat them as mutually exclusive
871 if mask_m_specified:
872 assert not has_smask,\
873 "cannot have both source-mask and predicate mask"
874 assert not has_pmask,\
875 "cannot have both dest-mask and predicate mask"
876 # since the default is INT predication (ALWAYS), if you
877 # specify one CR mask, you must specify both, to avoid
878 # mixing INT and CR reg types
879 if has_pmask and pmmode == 1:
880 assert has_smask, \
881 "need explicit source-mask in CR twin predication"
882 if has_smask and smmode == 1:
883 assert has_pmask, \
884 "need explicit dest-mask in CR twin predication"
885 # sanity-check that 2Pred mask is same mode
886 if has_pmask and has_smask:
887 assert smmode == pmmode, \
888 "predicate masks %s and %s must be same reg type" % \
889 (pme, sme)
890
891 # sanity-check that twin-predication mask only specified in 2P mode
892 if ptype == '1P':
893 assert not has_smask, \
894 "source-mask can only be specified on Twin-predicate ops"
895 assert not has_pmask, \
896 "dest-mask can only be specified on Twin-predicate ops"
897
898 # construct the mode field, doing sanity-checking along the way
899 if mapreduce_svm:
900 assert sv_mode == 0b00, "sub-vector mode in mapreduce only"
901 assert subvl != 0, "sub-vector mode not possible on SUBVL=1"
902
903 if src_zero:
904 assert has_smask or mask_m_specified, \
905 "src zeroing requires a source predicate"
906 if dst_zero:
907 assert has_pmask or mask_m_specified, \
908 "dest zeroing requires a dest predicate"
909
910 # check LDST shifted, only available in "normal" mode
911 if is_ldst and ldst_shift:
912 assert sv_mode is None, \
913 "LD shift cannot have modes (%s) applied" % sv_mode
914
915 # okaaay, so there are 4 different modes, here, which will be
916 # partly-merged-in: is_ldst is merged in with "normal", but
917 # is_bc is so different it's done separately. likewise is_cr
918 # (when it is done). here are the maps:
919
920 # for "normal" arithmetic: https://libre-soc.org/openpower/sv/normal/
921 """
922 | 0-1 | 2 | 3 4 | description |
923 | --- | --- |---------|-------------------------- |
924 | 00 | 0 | dz sz | normal mode |
925 | 00 | 1 | 0 RG | scalar reduce mode (mapreduce), SUBVL=1 |
926 | 00 | 1 | 1 / | parallel reduce mode (mapreduce), SUBVL=1 |
927 | 00 | 1 | SVM RG | subvector reduce mode, SUBVL>1 |
928 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
929 | 01 | inv | VLi RC1 | Rc=0: ffirst z/nonz |
930 | 10 | N | dz sz | sat mode: N=0/1 u/s |
931 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
932 | 11 | inv | dz RC1 | Rc=0: pred-result z/nonz |
933 """
934
935 # https://libre-soc.org/openpower/sv/ldst/
936 # for LD/ST-immediate:
937 """
938 | 0-1 | 2 | 3 4 | description |
939 | --- | --- |---------|--------------------------- |
940 | 00 | 0 | dz els | normal mode |
941 | 00 | 1 | dz shf | shift mode |
942 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
943 | 01 | inv | els RC1 | Rc=0: ffirst z/nonz |
944 | 10 | N | dz els | sat mode: N=0/1 u/s |
945 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
946 | 11 | inv | els RC1 | Rc=0: pred-result z/nonz |
947 """
948
949 # for LD/ST-indexed (RA+RB):
950 """
951 | 0-1 | 2 | 3 4 | description |
952 | --- | --- |---------|-------------------------- |
953 | 00 | SEA | dz sz | normal mode |
954 | 01 | SEA | dz sz | Strided (scalar only source) |
955 | 10 | N | dz sz | sat mode: N=0/1 u/s |
956 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
957 | 11 | inv | dz RC1 | Rc=0: pred-result z/nonz |
958 """
959
960 # and leaving out branches and cr_ops for now because they're
961 # under development
962 """ TODO branches and cr_ops
963 """
964
965 # now create mode and (overridden) src/dst widths
966 # XXX TODO: sanity-check bc modes
967 if is_bc:
968 sv_mode = ((bc_svstep << SVP64MODE.MOD2_MSB) |
969 (bc_vlset << SVP64MODE.MOD2_LSB) |
970 (bc_snz << SVP64MODE.BC_SNZ))
971 srcwid = (bc_vsb << 1) | bc_lru
972 destwid = (bc_lru << 1) | bc_all
973
974 else:
975
976 ######################################
977 # "normal" mode
978 if sv_mode is None:
979 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
980 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
981 if is_ldst:
982 # TODO: for now, LD/ST-indexed is ignored.
983 mode |= ldst_elstride << SVP64MODE.ELS_NORMAL # el-strided
984 # shifted mode
985 if ldst_shift:
986 mode |= 1 << SVP64MODE.LDST_SHIFT
987 else:
988 # TODO, reduce and subvector mode
989 # 00 1 dz CRM reduce mode (mapreduce), SUBVL=1
990 # 00 1 SVM CRM subvector reduce mode, SUBVL>1
991 pass
992 sv_mode = 0b00
993
994 ######################################
995 # "mapreduce" modes
996 elif sv_mode == 0b00:
997 mode |= (0b1 << SVP64MODE.REDUCE) # sets mapreduce
998 assert dst_zero == 0, "dest-zero not allowed in mapreduce mode"
999 if reverse_gear:
1000 mode |= (0b1 << SVP64MODE.RG) # sets Reverse-gear mode
1001 if mapreduce_crm:
1002 mode |= (0b1 << SVP64MODE.CRM) # sets CRM mode
1003 assert rc_mode, "CRM only allowed when Rc=1"
1004 # bit of weird encoding to jam zero-pred or SVM mode in.
1005 # SVM mode can be enabled only when SUBVL=2/3/4 (vec2/3/4)
1006 if subvl == 0:
1007 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
1008 elif mapreduce_svm:
1009 mode |= (0b1 << SVP64MODE.SVM) # sets SVM mode
1010
1011 ######################################
1012 # "failfirst" modes
1013 elif sv_mode == 0b01:
1014 assert src_zero == 0, "dest-zero not allowed in failfirst mode"
1015 if failfirst == 'RC1':
1016 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1017 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1018 assert rc_mode == False, "ffirst RC1 only ok when Rc=0"
1019 elif failfirst == '~RC1':
1020 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1021 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1022 mode |= (0b1 << SVP64MODE.INV) # ... with inversion
1023 assert rc_mode == False, "ffirst RC1 only ok when Rc=0"
1024 else:
1025 assert dst_zero == 0, "dst-zero not allowed in ffirst BO"
1026 assert rc_mode, "ffirst BO only possible when Rc=1"
1027 mode |= (failfirst << SVP64MODE.BO_LSB) # set BO
1028
1029 ######################################
1030 # "saturation" modes
1031 elif sv_mode == 0b10:
1032 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
1033 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
1034 mode |= (saturation << SVP64MODE.N) # signed/us saturation
1035
1036 ######################################
1037 # "predicate-result" modes. err... code-duplication from ffirst
1038 elif sv_mode == 0b11:
1039 assert src_zero == 0, "dest-zero not allowed in predresult mode"
1040 if predresult == 'RC1':
1041 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1042 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1043 assert rc_mode == False, "pr-mode RC1 only ok when Rc=0"
1044 elif predresult == '~RC1':
1045 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1046 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1047 mode |= (0b1 << SVP64MODE.INV) # ... with inversion
1048 assert rc_mode == False, "pr-mode RC1 only ok when Rc=0"
1049 else:
1050 assert dst_zero == 0, "dst-zero not allowed in pr-mode BO"
1051 assert rc_mode, "pr-mode BO only possible when Rc=1"
1052 mode |= (predresult << SVP64MODE.BO_LSB) # set BO
1053
1054 # whewww.... modes all done :)
1055 # now put into svp64_rm
1056 mode |= sv_mode
1057 # mode: bits 19-23
1058 svp64_rm.mode.eq(SelectableInt(mode, SVP64RM_MODE_SIZE))
1059
1060 # put in predicate masks into svp64_rm
1061 if ptype == '2P':
1062 # source pred: bits 16-18
1063 svp64_rm.smask.eq(SelectableInt(smask, SVP64RM_SMASK_SIZE))
1064 # mask mode: bit 0
1065 svp64_rm.mmode.eq(SelectableInt(mmode, SVP64RM_MMODE_SIZE))
1066 # 1-pred: bits 1-3
1067 svp64_rm.mask.eq(SelectableInt(pmask, SVP64RM_MASK_SIZE))
1068
1069 # and subvl: bits 8-9
1070 svp64_rm.subvl.eq(SelectableInt(subvl, SVP64RM_SUBVL_SIZE))
1071
1072 # put in elwidths
1073 # srcwid: bits 6-7
1074 svp64_rm.ewsrc.eq(SelectableInt(srcwid, SVP64RM_EWSRC_SIZE))
1075 # destwid: bits 4-5
1076 svp64_rm.elwidth.eq(SelectableInt(destwid, SVP64RM_ELWIDTH_SIZE))
1077
1078 # nice debug printout. (and now for something completely different)
1079 # https://youtu.be/u0WOIwlXE9g?t=146
1080 svp64_rm_value = svp64_rm.spr.value
1081 log("svp64_rm", hex(svp64_rm_value), bin(svp64_rm_value))
1082 log(" mmode 0 :", bin(mmode))
1083 log(" pmask 1-3 :", bin(pmask))
1084 log(" dstwid 4-5 :", bin(destwid))
1085 log(" srcwid 6-7 :", bin(srcwid))
1086 log(" subvl 8-9 :", bin(subvl))
1087 log(" mode 19-23:", bin(mode))
1088 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
1089 for idx, sv_extra in extras.items():
1090 if idx is None:
1091 continue
1092 if idx[0] == 'imm':
1093 continue
1094 srcdest, idx, duplicate = idx
1095 start = (10+idx*offs)
1096 end = start + offs-1
1097 log(" extra%d %2d-%2d:" % (idx, start, end),
1098 bin(sv_extra))
1099 if ptype == '2P':
1100 log(" smask 16-17:", bin(smask))
1101 log()
1102
1103 # first, construct the prefix from its subfields
1104 svp64_prefix = SVP64PrefixFields()
1105 svp64_prefix.major.eq(SelectableInt(0x1, SV64P_MAJOR_SIZE))
1106 svp64_prefix.pid.eq(SelectableInt(0b11, SV64P_PID_SIZE))
1107 svp64_prefix.rm.eq(svp64_rm.spr)
1108
1109 # fiinally yield the svp64 prefix and the thingy. v3.0b opcode
1110 rc = '.' if rc_mode else ''
1111 yield ".long 0x%08x" % svp64_prefix.insn.value
1112 log(v30b_newfields)
1113 # argh, sv.fmadds etc. need to be done manually
1114 if v30b_op == 'ffmadds':
1115 opcode = 59 << (32-6) # bits 0..6 (MSB0)
1116 opcode |= int(v30b_newfields[0]) << (32-11) # FRT
1117 opcode |= int(v30b_newfields[1]) << (32-16) # FRA
1118 opcode |= int(v30b_newfields[2]) << (32-21) # FRB
1119 opcode |= int(v30b_newfields[3]) << (32-26) # FRC
1120 opcode |= 0b00101 << (32-31) # bits 26-30
1121 if rc:
1122 opcode |= 1 # Rc, bit 31.
1123 yield ".long 0x%x" % opcode
1124 # argh, sv.fdmadds need to be done manually
1125 elif v30b_op == 'fdmadds':
1126 opcode = 59 << (32-6) # bits 0..6 (MSB0)
1127 opcode |= int(v30b_newfields[0]) << (32-11) # FRT
1128 opcode |= int(v30b_newfields[1]) << (32-16) # FRA
1129 opcode |= int(v30b_newfields[2]) << (32-21) # FRB
1130 opcode |= int(v30b_newfields[3]) << (32-26) # FRC
1131 opcode |= 0b01111 << (32-31) # bits 26-30
1132 if rc:
1133 opcode |= 1 # Rc, bit 31.
1134 yield ".long 0x%x" % opcode
1135 # argh, sv.ffadds etc. need to be done manually
1136 elif v30b_op == 'ffadds':
1137 opcode = 59 << (32-6) # bits 0..6 (MSB0)
1138 opcode |= int(v30b_newfields[0]) << (32-11) # FRT
1139 opcode |= int(v30b_newfields[1]) << (32-16) # FRA
1140 opcode |= int(v30b_newfields[2]) << (32-21) # FRB
1141 opcode |= 0b01101 << (32-31) # bits 26-30
1142 if rc:
1143 opcode |= 1 # Rc, bit 31.
1144 yield ".long 0x%x" % opcode
1145 # sigh have to do svstep here manually for now...
1146 elif opcode in ["svstep", "svstep."]:
1147 insn = 22 << (31-5) # opcode 22, bits 0-5
1148 insn |= int(v30b_newfields[0]) << (31-10) # RT , bits 6-10
1149 insn |= int(v30b_newfields[1]) << (31-22) # SVi , bits 16-22
1150 insn |= int(v30b_newfields[2]) << (31-25) # vf , bit 25
1151 insn |= 0b10011 << (31-30) # XO , bits 26..30
1152 if opcode == 'svstep.':
1153 insn |= 1 << (31-31) # Rc=1 , bit 31
1154 log("svstep", bin(insn))
1155 yield ".long 0x%x" % insn
1156 # argh, sv.fcoss etc. need to be done manually
1157 elif v30b_op in ["fcoss", "fcoss."]:
1158 insn = 59 << (31-5) # opcode 59, bits 0-5
1159 insn |= int(v30b_newfields[0]) << (31-10) # RT , bits 6-10
1160 insn |= int(v30b_newfields[1]) << (31-20) # RB , bits 16-20
1161 insn |= 0b1000101110 << (31-30) # XO , bits 21..30
1162 if opcode == 'fcoss.':
1163 insn |= 1 << (31-31) # Rc=1 , bit 31
1164 log("fcoss", bin(insn))
1165 yield ".long 0x%x" % insn
1166
1167 else:
1168 yield "%s %s" % (v30b_op+rc, ", ".join(v30b_newfields))
1169 log("new v3.0B fields", v30b_op, v30b_newfields)
1170
1171 def translate(self, lst):
1172 for insn in lst:
1173 yield from self.translate_one(insn)
1174
1175
1176 def macro_subst(macros, txt):
1177 again = True
1178 log("subst", txt, macros)
1179 while again:
1180 again = False
1181 for macro, value in macros.items():
1182 if macro == txt:
1183 again = True
1184 replaced = txt.replace(macro, value)
1185 log("macro", txt, "replaced", replaced, macro, value)
1186 txt = replaced
1187 continue
1188 toreplace = '%s.s' % macro
1189 if toreplace == txt:
1190 again = True
1191 replaced = txt.replace(toreplace, "%s.s" % value)
1192 log("macro", txt, "replaced", replaced, toreplace, value)
1193 txt = replaced
1194 continue
1195 toreplace = '%s.v' % macro
1196 if toreplace == txt:
1197 again = True
1198 replaced = txt.replace(toreplace, "%s.v" % value)
1199 log("macro", txt, "replaced", replaced, toreplace, value)
1200 txt = replaced
1201 continue
1202 toreplace = '(%s)' % macro
1203 if toreplace in txt:
1204 again = True
1205 replaced = txt.replace(toreplace, '(%s)' % value)
1206 log("macro", txt, "replaced", replaced, toreplace, value)
1207 txt = replaced
1208 continue
1209 log(" processed", txt)
1210 return txt
1211
1212
1213 def get_ws(line):
1214 # find whitespace
1215 ws = ''
1216 while line:
1217 if not line[0].isspace():
1218 break
1219 ws += line[0]
1220 line = line[1:]
1221 return ws, line
1222
1223
1224 def asm_process():
1225 # get an input file and an output file
1226 args = sys.argv[1:]
1227 if len(args) == 0:
1228 infile = sys.stdin
1229 outfile = sys.stdout
1230 # read the whole lot in advance in case of in-place
1231 lines = list(infile.readlines())
1232 elif len(args) != 2:
1233 print("pysvp64asm [infile | -] [outfile | -]", file=sys.stderr)
1234 exit(0)
1235 else:
1236 if args[0] == '--':
1237 infile = sys.stdin
1238 else:
1239 infile = open(args[0], "r")
1240 # read the whole lot in advance in case of in-place overwrite
1241 lines = list(infile.readlines())
1242
1243 if args[1] == '--':
1244 outfile = sys.stdout
1245 else:
1246 outfile = open(args[1], "w")
1247
1248 # read the line, look for "sv", process it
1249 macros = {} # macros which start ".set"
1250 isa = SVP64Asm([])
1251 for line in lines:
1252 op = line.split("#")[0].strip()
1253 # identify macros
1254 if op.startswith(".set"):
1255 macro = op[4:].split(",")
1256 (macro, value) = map(str.strip, macro)
1257 macros[macro] = value
1258 if not (op.startswith("sv.") or
1259 op.startswith("setvl") or
1260 op.startswith("svshape")):
1261 outfile.write(line)
1262 continue
1263
1264 (ws, line) = get_ws(line)
1265 lst = isa.translate_one(op, macros)
1266 lst = '; '.join(lst)
1267 outfile.write("%s%s # %s\n" % (ws, lst, op))
1268
1269
1270 if __name__ == '__main__':
1271 lst = ['slw 3, 1, 4',
1272 'extsw 5, 3',
1273 'sv.extsw 5, 3',
1274 'sv.cmpi 5, 1, 3, 2',
1275 'sv.setb 5, 31',
1276 'sv.isel 64.v, 3, 2, 65.v',
1277 'sv.setb/dm=r3/sm=1<<r3 5, 31',
1278 'sv.setb/m=r3 5, 31',
1279 'sv.setb/vec2 5, 31',
1280 'sv.setb/sw=8/ew=16 5, 31',
1281 'sv.extsw./ff=eq 5, 31',
1282 'sv.extsw./satu/sz/dz/sm=r3/dm=r3 5, 31',
1283 'sv.extsw./pr=eq 5.v, 31',
1284 'sv.add. 5.v, 2.v, 1.v',
1285 'sv.add./m=r3 5.v, 2.v, 1.v',
1286 ]
1287 lst += [
1288 'sv.stw 5.v, 4(1.v)',
1289 'sv.ld 5.v, 4(1.v)',
1290 'setvl. 2, 3, 4, 0, 1, 1',
1291 'sv.setvl. 2, 3, 4, 0, 1, 1',
1292 ]
1293 lst = [
1294 "sv.stfsu 0.v, 16(4.v)",
1295 ]
1296 lst = [
1297 "sv.stfsu/els 0.v, 16(4)",
1298 ]
1299 lst = [
1300 'sv.add./mr 5.v, 2.v, 1.v',
1301 ]
1302 macros = {'win2': '50', 'win': '60'}
1303 lst = [
1304 'sv.addi win2.v, win.v, -1',
1305 'sv.add./mrr 5.v, 2.v, 1.v',
1306 #'sv.lhzsh 5.v, 11(9.v), 15',
1307 #'sv.lwzsh 5.v, 11(9.v), 15',
1308 'sv.ffmadds 6.v, 2.v, 4.v, 6.v',
1309 ]
1310 lst = [
1311 #'sv.fmadds 0.v, 8.v, 16.v, 4.v',
1312 #'sv.ffadds 0.v, 8.v, 4.v',
1313 'svremap 11, 0, 1, 2, 3, 2, 1',
1314 'svshape 8, 1, 1, 1, 0',
1315 'svshape 8, 1, 1, 1, 1',
1316 ]
1317 lst = [
1318 #'sv.lfssh 4.v, 11(8.v), 15',
1319 #'sv.lwzsh 4.v, 11(8.v), 15',
1320 #'sv.svstep. 2.v, 4, 0',
1321 #'sv.fcfids. 48.v, 64.v',
1322 'sv.fcoss. 80.v, 0.v',
1323 'sv.fcoss. 20.v, 0.v',
1324 ]
1325 lst = [
1326 'sv.bc/all 3,12,192',
1327 'sv.bclr/vsbi 3,81.v,192',
1328 'sv.ld 5.v, 4(1.v)',
1329 'sv.svstep. 2.v, 4, 0',
1330 ]
1331 lst = [
1332 'maxs 3,12,5',
1333 'maxs. 3,12,5',
1334 'avgadd 3,12,5',
1335 ]
1336 isa = SVP64Asm(lst, macros=macros)
1337 log("list", list(isa))
1338 asm_process()