identify SVP64 LD bit-reverse pattern as pseudo-assembler
[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 LDST: https://libre-soc.org/openpower/sv/ldst/
15 Bugtracker: https://bugs.libre-soc.org/show_bug.cgi?id=578
16 """
17
18 import os, sys
19 from collections import OrderedDict
20
21 from openpower.decoder.isa.caller import (SVP64PrefixFields, SV64P_MAJOR_SIZE,
22 SV64P_PID_SIZE, SVP64RMFields,
23 SVP64RM_EXTRA2_SPEC_SIZE,
24 SVP64RM_EXTRA3_SPEC_SIZE,
25 SVP64RM_MODE_SIZE, SVP64RM_SMASK_SIZE,
26 SVP64RM_MMODE_SIZE, SVP64RM_MASK_SIZE,
27 SVP64RM_SUBVL_SIZE, SVP64RM_EWSRC_SIZE,
28 SVP64RM_ELWIDTH_SIZE)
29 from openpower.decoder.pseudo.pagereader import ISA
30 from openpower.decoder.power_svp64 import SVP64RM, get_regtype, decode_extra
31 from openpower.decoder.selectable_int import SelectableInt
32 from openpower.consts import SVP64MODE
33
34 # for debug logging
35 from openpower.util import log
36
37
38 # decode GPR into sv extra
39 def get_extra_gpr(etype, regmode, field):
40 if regmode == 'scalar':
41 # cut into 2-bits 5-bits SS FFFFF
42 sv_extra = field >> 5
43 field = field & 0b11111
44 else:
45 # cut into 5-bits 2-bits FFFFF SS
46 sv_extra = field & 0b11
47 field = field >> 2
48 return sv_extra, field
49
50
51 # decode 3-bit CR into sv extra
52 def get_extra_cr_3bit(etype, regmode, field):
53 if regmode == 'scalar':
54 # cut into 2-bits 3-bits SS FFF
55 sv_extra = field >> 3
56 field = field & 0b111
57 else:
58 # cut into 3-bits 4-bits FFF SSSS but will cut 2 zeros off later
59 sv_extra = field & 0b1111
60 field = field >> 4
61 return sv_extra, field
62
63
64 # decodes SUBVL
65 def decode_subvl(encoding):
66 pmap = {'2': 0b01, '3': 0b10, '4': 0b11}
67 assert encoding in pmap, \
68 "encoding %s for SUBVL not recognised" % encoding
69 return pmap[encoding]
70
71
72 # decodes elwidth
73 def decode_elwidth(encoding):
74 pmap = {'8': 0b11, '16': 0b10, '32': 0b01}
75 assert encoding in pmap, \
76 "encoding %s for elwidth not recognised" % encoding
77 return pmap[encoding]
78
79
80 # decodes predicate register encoding
81 def decode_predicate(encoding):
82 pmap = { # integer
83 '1<<r3': (0, 0b001),
84 'r3' : (0, 0b010),
85 '~r3' : (0, 0b011),
86 'r10' : (0, 0b100),
87 '~r10' : (0, 0b101),
88 'r30' : (0, 0b110),
89 '~r30' : (0, 0b111),
90 # CR
91 'lt' : (1, 0b000),
92 'nl' : (1, 0b001), 'ge' : (1, 0b001), # same value
93 'gt' : (1, 0b010),
94 'ng' : (1, 0b011), 'le' : (1, 0b011), # same value
95 'eq' : (1, 0b100),
96 'ne' : (1, 0b101),
97 'so' : (1, 0b110), 'un' : (1, 0b110), # same value
98 'ns' : (1, 0b111), 'nu' : (1, 0b111), # same value
99 }
100 assert encoding in pmap, \
101 "encoding %s for predicate not recognised" % encoding
102 return pmap[encoding]
103
104
105 # decodes "Mode" in similar way to BO field (supposed to, anyway)
106 def decode_bo(encoding):
107 pmap = { # TODO: double-check that these are the same as Branch BO
108 'lt' : 0b000,
109 'nl' : 0b001, 'ge' : 0b001, # same value
110 'gt' : 0b010,
111 'ng' : 0b011, 'le' : 0b011, # same value
112 'eq' : 0b100,
113 'ne' : 0b101,
114 'so' : 0b110, 'un' : 0b110, # same value
115 'ns' : 0b111, 'nu' : 0b111, # same value
116 }
117 assert encoding in pmap, \
118 "encoding %s for BO Mode not recognised" % encoding
119 return pmap[encoding]
120
121 # partial-decode fail-first mode
122 def decode_ffirst(encoding):
123 if encoding in ['RC1', '~RC1']:
124 return encoding
125 return decode_bo(encoding)
126
127
128 def decode_reg(field):
129 # decode the field number. "5.v" or "3.s" or "9"
130 field = field.split(".")
131 regmode = 'scalar' # default
132 if len(field) == 2:
133 if field[1] == 's':
134 regmode = 'scalar'
135 elif field[1] == 'v':
136 regmode = 'vector'
137 field = int(field[0]) # actual register number
138 return field, regmode
139
140
141 def decode_imm(field):
142 ldst_imm = "(" in field and field[-1] == ')'
143 if ldst_imm:
144 return field[:-1].split("(")
145 else:
146 return None, field
147
148
149 # decodes svp64 assembly listings and creates EXT001 svp64 prefixes
150 class SVP64Asm:
151 def __init__(self, lst, bigendian=False, macros=None):
152 if macros is None:
153 macros = {}
154 self.macros = macros
155 self.lst = lst
156 self.trans = self.translate(lst)
157 self.isa = ISA() # reads the v3.0B pseudo-code markdown files
158 self.svp64 = SVP64RM() # reads the svp64 Remap entries for registers
159 assert bigendian == False, "error, bigendian not supported yet"
160
161 def __iter__(self):
162 yield from self.trans
163
164 def translate_one(self, insn, macros=None):
165 if macros is None:
166 macros = {}
167 macros.update(self.macros)
168 isa = self.isa
169 svp64 = self.svp64
170 # find first space, to get opcode
171 ls = insn.split(' ')
172 opcode = ls[0]
173 # now find opcode fields
174 fields = ''.join(ls[1:]).split(',')
175 mfields = list(map(str.strip, fields))
176 log ("opcode, fields", ls, opcode, mfields)
177 fields = []
178 # macro substitution
179 for field in mfields:
180 fields.append(macro_subst(macros, field))
181 log ("opcode, fields substed", ls, opcode, fields)
182
183 # sigh have to do setvl here manually for now...
184 if opcode in ["setvl", "setvl."]:
185 insn = 22 << (31-5) # opcode 22, bits 0-5
186 fields = list(map(int, fields))
187 insn |= fields[0] << (31-10) # RT , bits 6-10
188 insn |= fields[1] << (31-15) # RA , bits 11-15
189 insn |= fields[2] << (31-23) # SVi , bits 16-23
190 insn |= fields[3] << (31-24) # vs , bit 24
191 insn |= fields[4] << (31-25) # ms , bit 25
192 insn |= 0b00000 << (31-30) # XO , bits 26..30
193 if opcode == 'setvl.':
194 insn |= 1 << (31-31) # Rc=1 , bit 31
195 log ("setvl", bin(insn))
196 yield ".long 0x%x" % insn
197 return
198
199 # identify if is a svp64 mnemonic
200 if not opcode.startswith('sv.'):
201 yield insn # unaltered
202 return
203 opcode = opcode[3:] # strip leading "sv"
204
205 # start working on decoding the svp64 op: sv.basev30Bop/vec2/mode
206 opmodes = opcode.split("/") # split at "/"
207 v30b_op = opmodes.pop(0) # first is the v3.0B
208 # check instruction ends with dot
209 rc_mode = v30b_op.endswith('.')
210 if rc_mode:
211 v30b_op = v30b_op[:-1]
212
213 # sigh again, have to recognised LD/ST bit-reverse instructions
214 # this has to be "processed" to fit into a v3.0B without the "br"
215 # e.g. ldbr is actually ld
216 ldst_bitreverse = v30b_op.startswith("l") and v30b_op.endswith("br")
217
218 if v30b_op not in isa.instr:
219 raise Exception("opcode %s of '%s' not supported" % \
220 (v30b_op, insn))
221
222 if ldst_bitreverse:
223 # okaay we need to process the fields and make this:
224 # ldbr RT, SVD(RA), RC - 11 bits for SVD, 5 for RC
225 # into this:
226 # ld RT, D(RA) - 16 bits
227 # likewise same for SVDS (9 bits for SVDS, 5 for RC, 14 bits for DS)
228 form = isa.instr[v30b_op].form # get form (SVD-Form, SVDS-Form)
229
230 newfields = []
231 for field in fields:
232 # identify if this is a ld/st immediate(reg) thing
233 ldst_imm = "(" in field and field[-1] == ')'
234 if ldst_imm:
235 newfields.append(field[:-1].split("("))
236 else:
237 newfields.append(field)
238
239 immed, RA = newfields[1]
240 immed = int(immed)
241 RC = int(newfields.pop(2)) # better be an integer number!
242 if form == 'SVD': # 16 bit: immed 11 bits, RC shift up 11
243 immed = (immed & 0b11111111111) | (RC<<11)
244 if immed & (1<<15): # should be negative
245 immed -= 1<<16
246 if form == 'SVDS': # 14 bit: immed 9 bits, RC shift up 9
247 immed = (immed & 0b111111111) | (RC<<9)
248 if immed & (1<<13): # should be negative
249 immed -= 1<<14
250 newfields[1] = "%d(%s)" % (immed, RA)
251 fields = newfields
252
253 # and strip off "br" from end, and add "br" to opmodes, instead
254 v30b_op = v30b_op[:-2]
255 opmodes.append("br")
256 log ("rewritten", v30b_op, opmodes, fields)
257
258 if v30b_op not in svp64.instrs:
259 raise Exception("opcode %s of '%s' not an svp64 instruction" % \
260 (v30b_op, insn))
261 v30b_regs = isa.instr[v30b_op].regs[0] # get regs info "RT, RA, RB"
262 rm = svp64.instrs[v30b_op] # one row of the svp64 RM CSV
263 log ("v3.0B op", v30b_op, "Rc=1" if rc_mode else '')
264 log ("v3.0B regs", opcode, v30b_regs)
265 log ("RM", rm)
266
267 # right. the first thing to do is identify the ordering of
268 # the registers, by name. the EXTRA2/3 ordering is in
269 # rm['0']..rm['3'] but those fields contain the names RA, BB
270 # etc. we have to read the pseudocode to understand which
271 # reg is which in our instruction. sigh.
272
273 # first turn the svp64 rm into a "by name" dict, recording
274 # which position in the RM EXTRA it goes into
275 # also: record if the src or dest was a CR, for sanity-checking
276 # (elwidth overrides on CRs are banned)
277 decode = decode_extra(rm)
278 dest_reg_cr, src_reg_cr, svp64_src, svp64_dest = decode
279
280 log ("EXTRA field index, src", svp64_src)
281 log ("EXTRA field index, dest", svp64_dest)
282
283 # okaaay now we identify the field value (opcode N,N,N) with
284 # the pseudo-code info (opcode RT, RA, RB)
285 assert len(fields) == len(v30b_regs), \
286 "length of fields %s must match insn `%s`" % \
287 (str(v30b_regs), insn)
288 opregfields = zip(fields, v30b_regs) # err that was easy
289
290 # now for each of those find its place in the EXTRA encoding
291 # note there is the possibility (for LD/ST-with-update) of
292 # RA occurring **TWICE**. to avoid it getting added to the
293 # v3.0B suffix twice, we spot it as a duplicate, here
294 extras = OrderedDict()
295 for idx, (field, regname) in enumerate(opregfields):
296 imm, regname = decode_imm(regname)
297 rtype = get_regtype(regname)
298 log (" idx find", rtype, idx, field, regname, imm)
299 if rtype is None:
300 # probably an immediate field, append it straight
301 extras[('imm', idx, False)] = (idx, field, None, None, None)
302 continue
303 extra = svp64_src.get(regname, None)
304 if extra is not None:
305 extra = ('s', extra, False) # not a duplicate
306 extras[extra] = (idx, field, regname, rtype, imm)
307 log (" idx src", idx, extra, extras[extra])
308 dextra = svp64_dest.get(regname, None)
309 log ("regname in", regname, dextra)
310 if dextra is not None:
311 is_a_duplicate = extra is not None # duplicate spotted
312 dextra = ('d', dextra, is_a_duplicate)
313 extras[dextra] = (idx, field, regname, rtype, imm)
314 log (" idx dst", idx, extra, extras[dextra])
315
316 # great! got the extra fields in their associated positions:
317 # also we know the register type. now to create the EXTRA encodings
318 etype = rm['Etype'] # Extra type: EXTRA3/EXTRA2
319 ptype = rm['Ptype'] # Predication type: Twin / Single
320 extra_bits = 0
321 v30b_newfields = []
322 for extra_idx, (idx, field, rname, rtype, iname) in extras.items():
323 # is it a field we don't alter/examine? if so just put it
324 # into newfields
325 if rtype is None:
326 v30b_newfields.append(field)
327 continue
328
329 # identify if this is a ld/st immediate(reg) thing
330 ldst_imm = "(" in field and field[-1] == ')'
331 if ldst_imm:
332 immed, field = field[:-1].split("(")
333
334 field, regmode = decode_reg(field)
335 log (" ", extra_idx, rname, rtype,
336 regmode, iname, field, end=" ")
337
338 # see Mode field https://libre-soc.org/openpower/sv/svp64/
339 # XXX TODO: the following is a bit of a laborious repeated
340 # mess, which could (and should) easily be parameterised.
341 # XXX also TODO: the LD/ST modes which are different
342 # https://libre-soc.org/openpower/sv/ldst/
343
344 # encode SV-GPR and SV-FPR field into extra, v3.0field
345 if rtype in ['GPR', 'FPR']:
346 sv_extra, field = get_extra_gpr(etype, regmode, field)
347 # now sanity-check. EXTRA3 is ok, EXTRA2 has limits
348 # (and shrink to a single bit if ok)
349 if etype == 'EXTRA2':
350 if regmode == 'scalar':
351 # range is r0-r63 in increments of 1
352 assert (sv_extra >> 1) == 0, \
353 "scalar GPR %s cannot fit into EXTRA2 %s" % \
354 (rname, str(extras[extra_idx]))
355 # all good: encode as scalar
356 sv_extra = sv_extra & 0b01
357 else:
358 # range is r0-r127 in increments of 4
359 assert sv_extra & 0b01 == 0, \
360 "%s: vector field %s cannot fit " \
361 "into EXTRA2 %s" % \
362 (insn, rname, str(extras[extra_idx]))
363 # all good: encode as vector (bit 2 set)
364 sv_extra = 0b10 | (sv_extra >> 1)
365 elif regmode == 'vector':
366 # EXTRA3 vector bit needs marking
367 sv_extra |= 0b100
368
369 # encode SV-CR 3-bit field into extra, v3.0field
370 elif rtype == 'CR_3bit':
371 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
372 # now sanity-check (and shrink afterwards)
373 if etype == 'EXTRA2':
374 if regmode == 'scalar':
375 # range is CR0-CR15 in increments of 1
376 assert (sv_extra >> 1) == 0, \
377 "scalar CR %s cannot fit into EXTRA2 %s" % \
378 (rname, str(extras[extra_idx]))
379 # all good: encode as scalar
380 sv_extra = sv_extra & 0b01
381 else:
382 # range is CR0-CR127 in increments of 16
383 assert sv_extra & 0b111 == 0, \
384 "vector CR %s cannot fit into EXTRA2 %s" % \
385 (rname, str(extras[extra_idx]))
386 # all good: encode as vector (bit 2 set)
387 sv_extra = 0b10 | (sv_extra >> 3)
388 else:
389 if regmode == 'scalar':
390 # range is CR0-CR31 in increments of 1
391 assert (sv_extra >> 2) == 0, \
392 "scalar CR %s cannot fit into EXTRA2 %s" % \
393 (rname, str(extras[extra_idx]))
394 # all good: encode as scalar
395 sv_extra = sv_extra & 0b11
396 else:
397 # range is CR0-CR127 in increments of 8
398 assert sv_extra & 0b11 == 0, \
399 "vector CR %s cannot fit into EXTRA2 %s" % \
400 (rname, str(extras[extra_idx]))
401 # all good: encode as vector (bit 3 set)
402 sv_extra = 0b100 | (sv_extra >> 2)
403
404 # encode SV-CR 5-bit field into extra, v3.0field
405 # *sigh* this is the same as 3-bit except the 2 LSBs are
406 # passed through
407 elif rtype == 'CR_5bit':
408 cr_subfield = field & 0b11
409 field = field >> 2 # strip bottom 2 bits
410 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
411 # now sanity-check (and shrink afterwards)
412 if etype == 'EXTRA2':
413 if regmode == 'scalar':
414 # range is CR0-CR15 in increments of 1
415 assert (sv_extra >> 1) == 0, \
416 "scalar CR %s cannot fit into EXTRA2 %s" % \
417 (rname, str(extras[extra_idx]))
418 # all good: encode as scalar
419 sv_extra = sv_extra & 0b01
420 else:
421 # range is CR0-CR127 in increments of 16
422 assert sv_extra & 0b111 == 0, \
423 "vector CR %s cannot fit into EXTRA2 %s" % \
424 (rname, str(extras[extra_idx]))
425 # all good: encode as vector (bit 2 set)
426 sv_extra = 0b10 | (sv_extra >> 3)
427 else:
428 if regmode == 'scalar':
429 # range is CR0-CR31 in increments of 1
430 assert (sv_extra >> 2) == 0, \
431 "scalar CR %s cannot fit into EXTRA2 %s" % \
432 (rname, str(extras[extra_idx]))
433 # all good: encode as scalar
434 sv_extra = sv_extra & 0b11
435 else:
436 # range is CR0-CR127 in increments of 8
437 assert sv_extra & 0b11 == 0, \
438 "vector CR %s cannot fit into EXTRA2 %s" % \
439 (rname, str(extras[extra_idx]))
440 # all good: encode as vector (bit 3 set)
441 sv_extra = 0b100 | (sv_extra >> 2)
442 # reconstruct the actual 5-bit CR field
443 field = (field << 2) | cr_subfield
444
445 else:
446 print ("no type match", rtype)
447
448 # capture the extra field info
449 log ("=>", "%5s" % bin(sv_extra), field)
450 extras[extra_idx] = sv_extra
451
452 # append altered field value to v3.0b, differs for LDST
453 # note that duplicates are skipped e.g. EXTRA2 contains
454 # *BOTH* s:RA *AND* d:RA which happens on LD/ST-with-update
455 srcdest, idx, duplicate = extra_idx
456 if duplicate: # skip adding to v3.0b fields, already added
457 continue
458 if ldst_imm:
459 v30b_newfields.append(("%s(%s)" % (immed, str(field))))
460 else:
461 v30b_newfields.append(str(field))
462
463 log ("new v3.0B fields", v30b_op, v30b_newfields)
464 log ("extras", extras)
465
466 # rright. now we have all the info. start creating SVP64 RM
467 svp64_rm = SVP64RMFields()
468
469 # begin with EXTRA fields
470 for idx, sv_extra in extras.items():
471 log (idx)
472 if idx is None: continue
473 if idx[0] == 'imm': continue
474 srcdest, idx, duplicate = idx
475 if etype == 'EXTRA2':
476 svp64_rm.extra2[idx].eq(
477 SelectableInt(sv_extra, SVP64RM_EXTRA2_SPEC_SIZE))
478 else:
479 svp64_rm.extra3[idx].eq(
480 SelectableInt(sv_extra, SVP64RM_EXTRA3_SPEC_SIZE))
481
482 # identify if the op is a LD/ST. the "blegh" way. copied
483 # from power_enums. TODO, split the list _insns down.
484 is_ld = v30b_op in [
485 "lbarx", "lbz", "lbzu", "lbzux", "lbzx", # load byte
486 "ld", "ldarx", "ldbrx", "ldu", "ldux", "ldx", # load double
487 "lfs", "lfsx", "lfsu", "lfsux", # FP load single
488 "lfd", "lfdx", "lfdu", "lfdux", "lfiwzx", "lfiwax", # FP load double
489 "lha", "lharx", "lhau", "lhaux", "lhax", # load half
490 "lhbrx", "lhz", "lhzu", "lhzux", "lhzx", # more load half
491 "lwa", "lwarx", "lwaux", "lwax", "lwbrx", # load word
492 "lwz", "lwzcix", "lwzu", "lwzux", "lwzx", # more load word
493 ]
494 is_st = v30b_op in [
495 "stb", "stbcix", "stbcx", "stbu", "stbux", "stbx",
496 "std", "stdbrx", "stdcx", "stdu", "stdux", "stdx",
497 "stfs", "stfsx", "stfsu", "stfux", # FP store single
498 "stfd", "stfdx", "stfdu", "stfdux", "stfiwx", # FP store double
499 "sth", "sthbrx", "sthcx", "sthu", "sthux", "sthx",
500 "stw", "stwbrx", "stwcx", "stwu", "stwux", "stwx",
501 ]
502 # use this to determine if the SVP64 RM format is different.
503 # see https://libre-soc.org/openpower/sv/ldst/
504 is_ldst = is_ld or is_st
505
506 # parts of svp64_rm
507 mmode = 0 # bit 0
508 pmask = 0 # bits 1-3
509 destwid = 0 # bits 4-5
510 srcwid = 0 # bits 6-7
511 subvl = 0 # bits 8-9
512 smask = 0 # bits 16-18 but only for twin-predication
513 mode = 0 # bits 19-23
514
515 mask_m_specified = False
516 has_pmask = False
517 has_smask = False
518
519 saturation = None
520 src_zero = 0
521 dst_zero = 0
522 sv_mode = None
523
524 mapreduce = False
525 reverse_gear = False
526 mapreduce_crm = False
527 mapreduce_svm = False
528
529 predresult = False
530 failfirst = False
531 ldst_elstride = 0
532
533 # ok let's start identifying opcode augmentation fields
534 for encmode in opmodes:
535 # predicate mask (src and dest)
536 if encmode.startswith("m="):
537 pme = encmode
538 pmmode, pmask = decode_predicate(encmode[2:])
539 smmode, smask = pmmode, pmask
540 mmode = pmmode
541 mask_m_specified = True
542 # predicate mask (dest)
543 elif encmode.startswith("dm="):
544 pme = encmode
545 pmmode, pmask = decode_predicate(encmode[3:])
546 mmode = pmmode
547 has_pmask = True
548 # predicate mask (src, twin-pred)
549 elif encmode.startswith("sm="):
550 sme = encmode
551 smmode, smask = decode_predicate(encmode[3:])
552 mmode = smmode
553 has_smask = True
554 # bitreverse LD/ST
555 elif encmode.startswith("br"):
556 ldst_bitreverse = True
557 # vec2/3/4
558 elif encmode.startswith("vec"):
559 subvl = decode_subvl(encmode[3:])
560 # elwidth
561 elif encmode.startswith("ew="):
562 destwid = decode_elwidth(encmode[3:])
563 elif encmode.startswith("sw="):
564 srcwid = decode_elwidth(encmode[3:])
565 # element-strided LD/ST
566 elif encmode == 'els':
567 ldst_elstride = 1
568 # saturation
569 elif encmode == 'sats':
570 assert sv_mode is None
571 saturation = 1
572 sv_mode = 0b10
573 elif encmode == 'satu':
574 assert sv_mode is None
575 sv_mode = 0b10
576 saturation = 0
577 # predicate zeroing
578 elif encmode == 'sz':
579 src_zero = 1
580 elif encmode == 'dz':
581 dst_zero = 1
582 # failfirst
583 elif encmode.startswith("ff="):
584 assert sv_mode is None
585 sv_mode = 0b01
586 failfirst = decode_ffirst(encmode[3:])
587 # predicate-result, interestingly same as fail-first
588 elif encmode.startswith("pr="):
589 assert sv_mode is None
590 sv_mode = 0b11
591 predresult = decode_ffirst(encmode[3:])
592 # map-reduce mode, reverse-gear
593 elif encmode == 'mrr':
594 assert sv_mode is None
595 sv_mode = 0b00
596 mapreduce = True
597 reverse_gear = True
598 # map-reduce mode
599 elif encmode == 'mr':
600 assert sv_mode is None
601 sv_mode = 0b00
602 mapreduce = True
603 elif encmode == 'crm': # CR on map-reduce
604 assert sv_mode is None
605 sv_mode = 0b00
606 mapreduce_crm = True
607 elif encmode == 'svm': # sub-vector mode
608 mapreduce_svm = True
609 else:
610 raise AssertionError("unknown encmode %s" % encmode)
611
612 if ptype == '2P':
613 # since m=xx takes precedence (overrides) sm=xx and dm=xx,
614 # treat them as mutually exclusive
615 if mask_m_specified:
616 assert not has_smask,\
617 "cannot have both source-mask and predicate mask"
618 assert not has_pmask,\
619 "cannot have both dest-mask and predicate mask"
620 # since the default is INT predication (ALWAYS), if you
621 # specify one CR mask, you must specify both, to avoid
622 # mixing INT and CR reg types
623 if has_pmask and pmmode == 1:
624 assert has_smask, \
625 "need explicit source-mask in CR twin predication"
626 if has_smask and smmode == 1:
627 assert has_pmask, \
628 "need explicit dest-mask in CR twin predication"
629 # sanity-check that 2Pred mask is same mode
630 if has_pmask and has_smask:
631 assert smmode == pmmode, \
632 "predicate masks %s and %s must be same reg type" % \
633 (pme, sme)
634
635 # sanity-check that twin-predication mask only specified in 2P mode
636 if ptype == '1P':
637 assert not has_smask, \
638 "source-mask can only be specified on Twin-predicate ops"
639 assert not has_pmask, \
640 "dest-mask can only be specified on Twin-predicate ops"
641
642 # construct the mode field, doing sanity-checking along the way
643 if mapreduce_svm:
644 assert sv_mode == 0b00, "sub-vector mode in mapreduce only"
645 assert subvl != 0, "sub-vector mode not possible on SUBVL=1"
646
647 if src_zero:
648 assert has_smask or mask_m_specified, \
649 "src zeroing requires a source predicate"
650 if dst_zero:
651 assert has_pmask or mask_m_specified, \
652 "dest zeroing requires a dest predicate"
653
654 # check LDST bitreverse, only available in "normal" mode
655 if is_ldst and ldst_bitreverse:
656 assert sv_mode is None, \
657 "LD bit-reverse cannot have modes (%s) applied" % sv_mode
658
659 ######################################
660 # "normal" mode
661 if sv_mode is None:
662 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
663 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
664 if is_ldst:
665 # TODO: for now, LD/ST-indexed is ignored.
666 mode |= ldst_elstride << SVP64MODE.ELS_NORMAL # element-strided
667 # bitreverse mode
668 if ldst_bitreverse:
669 mode |= 1 << SVP64MODE.LDST_BITREV
670 else:
671 # TODO, reduce and subvector mode
672 # 00 1 dz CRM reduce mode (mapreduce), SUBVL=1
673 # 00 1 SVM CRM subvector reduce mode, SUBVL>1
674 pass
675 sv_mode = 0b00
676
677 ######################################
678 # "mapreduce" modes
679 elif sv_mode == 0b00:
680 mode |= (0b1<<SVP64MODE.REDUCE) # sets mapreduce
681 assert dst_zero == 0, "dest-zero not allowed in mapreduce mode"
682 if reverse_gear:
683 mode |= (0b1<<SVP64MODE.RG) # sets Reverse-gear mode
684 if mapreduce_crm:
685 mode |= (0b1<<SVP64MODE.CRM) # sets CRM mode
686 assert rc_mode, "CRM only allowed when Rc=1"
687 # bit of weird encoding to jam zero-pred or SVM mode in.
688 # SVM mode can be enabled only when SUBVL=2/3/4 (vec2/3/4)
689 if subvl == 0:
690 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
691 elif mapreduce_svm:
692 mode |= (0b1<<SVP64MODE.SVM) # sets SVM mode
693
694 ######################################
695 # "failfirst" modes
696 elif sv_mode == 0b01:
697 assert src_zero == 0, "dest-zero not allowed in failfirst mode"
698 if failfirst == 'RC1':
699 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
700 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
701 assert rc_mode==False, "ffirst RC1 only possible when Rc=0"
702 elif failfirst == '~RC1':
703 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
704 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
705 mode |= (0b1<<SVP64MODE.INV) # ... with inversion
706 assert rc_mode==False, "ffirst RC1 only possible when Rc=0"
707 else:
708 assert dst_zero == 0, "dst-zero not allowed in ffirst BO"
709 assert rc_mode, "ffirst BO only possible when Rc=1"
710 mode |= (failfirst << SVP64MODE.BO_LSB) # set BO
711
712 ######################################
713 # "saturation" modes
714 elif sv_mode == 0b10:
715 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
716 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
717 mode |= (saturation << SVP64MODE.N) # signed/unsigned saturation
718
719 ######################################
720 # "predicate-result" modes. err... code-duplication from ffirst
721 elif sv_mode == 0b11:
722 assert src_zero == 0, "dest-zero not allowed in predresult mode"
723 if predresult == 'RC1':
724 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
725 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
726 assert rc_mode==False, "pr-mode RC1 only possible when Rc=0"
727 elif predresult == '~RC1':
728 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
729 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
730 mode |= (0b1<<SVP64MODE.INV) # ... with inversion
731 assert rc_mode==False, "pr-mode RC1 only possible when Rc=0"
732 else:
733 assert dst_zero == 0, "dst-zero not allowed in pr-mode BO"
734 assert rc_mode, "pr-mode BO only possible when Rc=1"
735 mode |= (predresult << SVP64MODE.BO_LSB) # set BO
736
737 # whewww.... modes all done :)
738 # now put into svp64_rm
739 mode |= sv_mode
740 # mode: bits 19-23
741 svp64_rm.mode.eq(SelectableInt(mode, SVP64RM_MODE_SIZE))
742
743 # put in predicate masks into svp64_rm
744 if ptype == '2P':
745 # source pred: bits 16-18
746 svp64_rm.smask.eq(SelectableInt(smask, SVP64RM_SMASK_SIZE))
747 # mask mode: bit 0
748 svp64_rm.mmode.eq(SelectableInt(mmode, SVP64RM_MMODE_SIZE))
749 # 1-pred: bits 1-3
750 svp64_rm.mask.eq(SelectableInt(pmask, SVP64RM_MASK_SIZE))
751
752 # and subvl: bits 8-9
753 svp64_rm.subvl.eq(SelectableInt(subvl, SVP64RM_SUBVL_SIZE))
754
755 # put in elwidths
756 # srcwid: bits 6-7
757 svp64_rm.ewsrc.eq(SelectableInt(srcwid, SVP64RM_EWSRC_SIZE))
758 # destwid: bits 4-5
759 svp64_rm.elwidth.eq(SelectableInt(destwid, SVP64RM_ELWIDTH_SIZE))
760
761 # nice debug printout. (and now for something completely different)
762 # https://youtu.be/u0WOIwlXE9g?t=146
763 svp64_rm_value = svp64_rm.spr.value
764 log ("svp64_rm", hex(svp64_rm_value), bin(svp64_rm_value))
765 log (" mmode 0 :", bin(mmode))
766 log (" pmask 1-3 :", bin(pmask))
767 log (" dstwid 4-5 :", bin(destwid))
768 log (" srcwid 6-7 :", bin(srcwid))
769 log (" subvl 8-9 :", bin(subvl))
770 log (" mode 19-23:", bin(mode))
771 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
772 for idx, sv_extra in extras.items():
773 if idx is None: continue
774 if idx[0] == 'imm': continue
775 srcdest, idx, duplicate = idx
776 start = (10+idx*offs)
777 end = start + offs-1
778 log (" extra%d %2d-%2d:" % (idx, start, end),
779 bin(sv_extra))
780 if ptype == '2P':
781 log (" smask 16-17:", bin(smask))
782 log ()
783
784 # first, construct the prefix from its subfields
785 svp64_prefix = SVP64PrefixFields()
786 svp64_prefix.major.eq(SelectableInt(0x1, SV64P_MAJOR_SIZE))
787 svp64_prefix.pid.eq(SelectableInt(0b11, SV64P_PID_SIZE))
788 svp64_prefix.rm.eq(svp64_rm.spr)
789
790 # fiinally yield the svp64 prefix and the thingy. v3.0b opcode
791 rc = '.' if rc_mode else ''
792 yield ".long 0x%x" % svp64_prefix.insn.value
793 log(v30b_newfields)
794 yield "%s %s" % (v30b_op+rc, ", ".join(v30b_newfields))
795 log ("new v3.0B fields", v30b_op, v30b_newfields)
796
797 def translate(self, lst):
798 for insn in lst:
799 yield from self.translate_one(insn)
800
801
802 def macro_subst(macros, txt):
803 again = True
804 print ("subst", txt, macros)
805 while again:
806 again = False
807 for macro, value in macros.items():
808 if macro == txt:
809 again = True
810 replaced = txt.replace(macro, value)
811 print ("macro", txt, "replaced", replaced, macro, value)
812 txt = replaced
813 continue
814 toreplace = '%s.s' % macro
815 if toreplace == txt:
816 again = True
817 replaced = txt.replace(toreplace, "%s.s" % value)
818 print ("macro", txt, "replaced", replaced, toreplace, value)
819 txt = replaced
820 continue
821 toreplace = '%s.v' % macro
822 if toreplace == txt:
823 again = True
824 replaced = txt.replace(toreplace, "%s.v" % value)
825 print ("macro", txt, "replaced", replaced, toreplace, value)
826 txt = replaced
827 continue
828 toreplace = '(%s)' % macro
829 if toreplace in txt:
830 again = True
831 replaced = txt.replace(toreplace, '(%s)' % value)
832 print ("macro", txt, "replaced", replaced, toreplace, value)
833 txt = replaced
834 continue
835 print (" processed", txt)
836 return txt
837
838
839 def get_ws(line):
840 # find whitespace
841 ws = ''
842 while line:
843 if not line[0].isspace():
844 break
845 ws += line[0]
846 line = line[1:]
847 return ws, line
848
849
850 def asm_process():
851
852 # get an input file and an output file
853 args = sys.argv[1:]
854 if len(args) == 0:
855 infile = sys.stdin
856 outfile = sys.stdout
857 # read the whole lot in advance in case of in-place
858 lines = list(infile.readlines())
859 elif len(args) != 2:
860 print ("pysvp64asm [infile | -] [outfile | -]")
861 exit(0)
862 else:
863 if args[0] == '--':
864 infile = sys.stdin
865 else:
866 infile = open(args[0], "r")
867 # read the whole lot in advance in case of in-place overwrite
868 lines = list(infile.readlines())
869
870 if args[1] == '--':
871 outfile = sys.stdout
872 else:
873 outfile = open(args[1], "w")
874
875 # read the line, look for "sv", process it
876 macros = {} # macros which start ".set"
877 isa = SVP64Asm([])
878 for line in lines:
879 ls = line.split("#")
880 # identify macros
881 if ls[0].strip().startswith("setvl"):
882 ws, line = get_ws(ls[0])
883 lst = list(isa.translate_one(ls[0].strip(), macros))
884 lst = '; '.join(lst)
885 outfile.write("%s%s # %s\n" % (ws, lst, ls[0]))
886 continue
887 if ls[0].startswith(".set"):
888 macro = ls[0][4:].split(",")
889 macro, value = list(map(str.strip, macro))
890 macros[macro] = value
891 if len(ls) != 2:
892 outfile.write(line)
893 continue
894 potential= ls[1].strip()
895 if not potential.startswith("sv."):
896 outfile.write(line)
897 continue
898
899 ws, line = get_ws(line)
900 # SV line indentified
901 lst = list(isa.translate_one(potential, macros))
902 lst = '; '.join(lst)
903 outfile.write("%s%s # %s\n" % (ws, lst, potential))
904
905
906 if __name__ == '__main__':
907 lst = ['slw 3, 1, 4',
908 'extsw 5, 3',
909 'sv.extsw 5, 3',
910 'sv.cmpi 5, 1, 3, 2',
911 'sv.setb 5, 31',
912 'sv.isel 64.v, 3, 2, 65.v',
913 'sv.setb/dm=r3/sm=1<<r3 5, 31',
914 'sv.setb/m=r3 5, 31',
915 'sv.setb/vec2 5, 31',
916 'sv.setb/sw=8/ew=16 5, 31',
917 'sv.extsw./ff=eq 5, 31',
918 'sv.extsw./satu/sz/dz/sm=r3/dm=r3 5, 31',
919 'sv.extsw./pr=eq 5.v, 31',
920 'sv.add. 5.v, 2.v, 1.v',
921 'sv.add./m=r3 5.v, 2.v, 1.v',
922 ]
923 lst += [
924 'sv.stw 5.v, 4(1.v)',
925 'sv.ld 5.v, 4(1.v)',
926 'setvl. 2, 3, 4, 1, 1',
927 ]
928 lst = [
929 "sv.stfsu 0.v, 16(4.v)",
930 ]
931 lst = [
932 "sv.stfsu/els 0.v, 16(4)",
933 ]
934 lst = [
935 'sv.add./mr 5.v, 2.v, 1.v',
936 ]
937 macros = {'win2': '50', 'win': '60'}
938 lst = [
939 'sv.addi win2.v, win.v, -1',
940 'sv.add./mrr 5.v, 2.v, 1.v',
941 'sv.lhzbr 5.v, 11(9.v), 15',
942 ]
943 isa = SVP64Asm(lst, macros=macros)
944 print ("list", list(isa))
945 csvs = SVP64RM()
946 #asm_process()