add mapreduce "reverse gear" unit tests
[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 if v30b_op not in isa.instr:
214 raise Exception("opcode %s of '%s' not supported" % \
215 (v30b_op, insn))
216 if v30b_op not in svp64.instrs:
217 raise Exception("opcode %s of '%s' not an svp64 instruction" % \
218 (v30b_op, insn))
219 v30b_regs = isa.instr[v30b_op].regs[0] # get regs info "RT, RA, RB"
220 rm = svp64.instrs[v30b_op] # one row of the svp64 RM CSV
221 log ("v3.0B op", v30b_op, "Rc=1" if rc_mode else '')
222 log ("v3.0B regs", opcode, v30b_regs)
223 log ("RM", rm)
224
225 # right. the first thing to do is identify the ordering of
226 # the registers, by name. the EXTRA2/3 ordering is in
227 # rm['0']..rm['3'] but those fields contain the names RA, BB
228 # etc. we have to read the pseudocode to understand which
229 # reg is which in our instruction. sigh.
230
231 # first turn the svp64 rm into a "by name" dict, recording
232 # which position in the RM EXTRA it goes into
233 # also: record if the src or dest was a CR, for sanity-checking
234 # (elwidth overrides on CRs are banned)
235 decode = decode_extra(rm)
236 dest_reg_cr, src_reg_cr, svp64_src, svp64_dest = decode
237
238 log ("EXTRA field index, src", svp64_src)
239 log ("EXTRA field index, dest", svp64_dest)
240
241 # okaaay now we identify the field value (opcode N,N,N) with
242 # the pseudo-code info (opcode RT, RA, RB)
243 assert len(fields) == len(v30b_regs), \
244 "length of fields %s must match insn `%s`" % \
245 (str(v30b_regs), insn)
246 opregfields = zip(fields, v30b_regs) # err that was easy
247
248 # now for each of those find its place in the EXTRA encoding
249 # note there is the possibility (for LD/ST-with-update) of
250 # RA occurring **TWICE**. to avoid it getting added to the
251 # v3.0B suffix twice, we spot it as a duplicate, here
252 extras = OrderedDict()
253 for idx, (field, regname) in enumerate(opregfields):
254 imm, regname = decode_imm(regname)
255 rtype = get_regtype(regname)
256 log (" idx find", rtype, idx, field, regname, imm)
257 if rtype is None:
258 # probably an immediate field, append it straight
259 extras[('imm', idx, False)] = (idx, field, None, None, None)
260 continue
261 extra = svp64_src.get(regname, None)
262 if extra is not None:
263 extra = ('s', extra, False) # not a duplicate
264 extras[extra] = (idx, field, regname, rtype, imm)
265 log (" idx src", idx, extra, extras[extra])
266 dextra = svp64_dest.get(regname, None)
267 log ("regname in", regname, dextra)
268 if dextra is not None:
269 is_a_duplicate = extra is not None # duplicate spotted
270 dextra = ('d', dextra, is_a_duplicate)
271 extras[dextra] = (idx, field, regname, rtype, imm)
272 log (" idx dst", idx, extra, extras[dextra])
273
274 # great! got the extra fields in their associated positions:
275 # also we know the register type. now to create the EXTRA encodings
276 etype = rm['Etype'] # Extra type: EXTRA3/EXTRA2
277 ptype = rm['Ptype'] # Predication type: Twin / Single
278 extra_bits = 0
279 v30b_newfields = []
280 for extra_idx, (idx, field, rname, rtype, iname) in extras.items():
281 # is it a field we don't alter/examine? if so just put it
282 # into newfields
283 if rtype is None:
284 v30b_newfields.append(field)
285 continue
286
287 # identify if this is a ld/st immediate(reg) thing
288 ldst_imm = "(" in field and field[-1] == ')'
289 if ldst_imm:
290 immed, field = field[:-1].split("(")
291
292 field, regmode = decode_reg(field)
293 log (" ", extra_idx, rname, rtype,
294 regmode, iname, field, end=" ")
295
296 # see Mode field https://libre-soc.org/openpower/sv/svp64/
297 # XXX TODO: the following is a bit of a laborious repeated
298 # mess, which could (and should) easily be parameterised.
299 # XXX also TODO: the LD/ST modes which are different
300 # https://libre-soc.org/openpower/sv/ldst/
301
302 # encode SV-GPR and SV-FPR field into extra, v3.0field
303 if rtype in ['GPR', 'FPR']:
304 sv_extra, field = get_extra_gpr(etype, regmode, field)
305 # now sanity-check. EXTRA3 is ok, EXTRA2 has limits
306 # (and shrink to a single bit if ok)
307 if etype == 'EXTRA2':
308 if regmode == 'scalar':
309 # range is r0-r63 in increments of 1
310 assert (sv_extra >> 1) == 0, \
311 "scalar GPR %s cannot fit into EXTRA2 %s" % \
312 (rname, str(extras[extra_idx]))
313 # all good: encode as scalar
314 sv_extra = sv_extra & 0b01
315 else:
316 # range is r0-r127 in increments of 4
317 assert sv_extra & 0b01 == 0, \
318 "%s: vector field %s cannot fit " \
319 "into EXTRA2 %s" % \
320 (insn, rname, str(extras[extra_idx]))
321 # all good: encode as vector (bit 2 set)
322 sv_extra = 0b10 | (sv_extra >> 1)
323 elif regmode == 'vector':
324 # EXTRA3 vector bit needs marking
325 sv_extra |= 0b100
326
327 # encode SV-CR 3-bit field into extra, v3.0field
328 elif rtype == 'CR_3bit':
329 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
330 # now sanity-check (and shrink afterwards)
331 if etype == 'EXTRA2':
332 if regmode == 'scalar':
333 # range is CR0-CR15 in increments of 1
334 assert (sv_extra >> 1) == 0, \
335 "scalar CR %s cannot fit into EXTRA2 %s" % \
336 (rname, str(extras[extra_idx]))
337 # all good: encode as scalar
338 sv_extra = sv_extra & 0b01
339 else:
340 # range is CR0-CR127 in increments of 16
341 assert sv_extra & 0b111 == 0, \
342 "vector CR %s cannot fit into EXTRA2 %s" % \
343 (rname, str(extras[extra_idx]))
344 # all good: encode as vector (bit 2 set)
345 sv_extra = 0b10 | (sv_extra >> 3)
346 else:
347 if regmode == 'scalar':
348 # range is CR0-CR31 in increments of 1
349 assert (sv_extra >> 2) == 0, \
350 "scalar CR %s cannot fit into EXTRA2 %s" % \
351 (rname, str(extras[extra_idx]))
352 # all good: encode as scalar
353 sv_extra = sv_extra & 0b11
354 else:
355 # range is CR0-CR127 in increments of 8
356 assert sv_extra & 0b11 == 0, \
357 "vector CR %s cannot fit into EXTRA2 %s" % \
358 (rname, str(extras[extra_idx]))
359 # all good: encode as vector (bit 3 set)
360 sv_extra = 0b100 | (sv_extra >> 2)
361
362 # encode SV-CR 5-bit field into extra, v3.0field
363 # *sigh* this is the same as 3-bit except the 2 LSBs are
364 # passed through
365 elif rtype == 'CR_5bit':
366 cr_subfield = field & 0b11
367 field = field >> 2 # strip bottom 2 bits
368 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
369 # now sanity-check (and shrink afterwards)
370 if etype == 'EXTRA2':
371 if regmode == 'scalar':
372 # range is CR0-CR15 in increments of 1
373 assert (sv_extra >> 1) == 0, \
374 "scalar CR %s cannot fit into EXTRA2 %s" % \
375 (rname, str(extras[extra_idx]))
376 # all good: encode as scalar
377 sv_extra = sv_extra & 0b01
378 else:
379 # range is CR0-CR127 in increments of 16
380 assert sv_extra & 0b111 == 0, \
381 "vector CR %s cannot fit into EXTRA2 %s" % \
382 (rname, str(extras[extra_idx]))
383 # all good: encode as vector (bit 2 set)
384 sv_extra = 0b10 | (sv_extra >> 3)
385 else:
386 if regmode == 'scalar':
387 # range is CR0-CR31 in increments of 1
388 assert (sv_extra >> 2) == 0, \
389 "scalar CR %s cannot fit into EXTRA2 %s" % \
390 (rname, str(extras[extra_idx]))
391 # all good: encode as scalar
392 sv_extra = sv_extra & 0b11
393 else:
394 # range is CR0-CR127 in increments of 8
395 assert sv_extra & 0b11 == 0, \
396 "vector CR %s cannot fit into EXTRA2 %s" % \
397 (rname, str(extras[extra_idx]))
398 # all good: encode as vector (bit 3 set)
399 sv_extra = 0b100 | (sv_extra >> 2)
400 # reconstruct the actual 5-bit CR field
401 field = (field << 2) | cr_subfield
402
403 else:
404 print ("no type match", rtype)
405
406 # capture the extra field info
407 log ("=>", "%5s" % bin(sv_extra), field)
408 extras[extra_idx] = sv_extra
409
410 # append altered field value to v3.0b, differs for LDST
411 # note that duplicates are skipped e.g. EXTRA2 contains
412 # *BOTH* s:RA *AND* d:RA which happens on LD/ST-with-update
413 srcdest, idx, duplicate = extra_idx
414 if duplicate: # skip adding to v3.0b fields, already added
415 continue
416 if ldst_imm:
417 v30b_newfields.append(("%s(%s)" % (immed, str(field))))
418 else:
419 v30b_newfields.append(str(field))
420
421 log ("new v3.0B fields", v30b_op, v30b_newfields)
422 log ("extras", extras)
423
424 # rright. now we have all the info. start creating SVP64 RM
425 svp64_rm = SVP64RMFields()
426
427 # begin with EXTRA fields
428 for idx, sv_extra in extras.items():
429 log (idx)
430 if idx is None: continue
431 if idx[0] == 'imm': continue
432 srcdest, idx, duplicate = idx
433 if etype == 'EXTRA2':
434 svp64_rm.extra2[idx].eq(
435 SelectableInt(sv_extra, SVP64RM_EXTRA2_SPEC_SIZE))
436 else:
437 svp64_rm.extra3[idx].eq(
438 SelectableInt(sv_extra, SVP64RM_EXTRA3_SPEC_SIZE))
439
440 # identify if the op is a LD/ST. the "blegh" way. copied
441 # from power_enums. TODO, split the list _insns down.
442 is_ld = v30b_op in [
443 "lbarx", "lbz", "lbzu", "lbzux", "lbzx", # load byte
444 "ld", "ldarx", "ldbrx", "ldu", "ldux", "ldx", # load double
445 "lfs", "lfsx", "lfsu", "lfsux", # FP load single
446 "lfd", "lfdx", "lfdu", "lfdux", "lfiwzx", "lfiwax", # FP load double
447 "lha", "lharx", "lhau", "lhaux", "lhax", # load half
448 "lhbrx", "lhz", "lhzu", "lhzux", "lhzx", # more load half
449 "lwa", "lwarx", "lwaux", "lwax", "lwbrx", # load word
450 "lwz", "lwzcix", "lwzu", "lwzux", "lwzx", # more load word
451 ]
452 is_st = v30b_op in [
453 "stb", "stbcix", "stbcx", "stbu", "stbux", "stbx",
454 "std", "stdbrx", "stdcx", "stdu", "stdux", "stdx",
455 "stfs", "stfsx", "stfsu", "stfux", # FP store single
456 "stfd", "stfdx", "stfdu", "stfdux", "stfiwx", # FP store double
457 "sth", "sthbrx", "sthcx", "sthu", "sthux", "sthx",
458 "stw", "stwbrx", "stwcx", "stwu", "stwux", "stwx",
459 ]
460 # use this to determine if the SVP64 RM format is different.
461 # see https://libre-soc.org/openpower/sv/ldst/
462 is_ldst = is_ld or is_st
463
464 # parts of svp64_rm
465 mmode = 0 # bit 0
466 pmask = 0 # bits 1-3
467 destwid = 0 # bits 4-5
468 srcwid = 0 # bits 6-7
469 subvl = 0 # bits 8-9
470 smask = 0 # bits 16-18 but only for twin-predication
471 mode = 0 # bits 19-23
472
473 mask_m_specified = False
474 has_pmask = False
475 has_smask = False
476
477 saturation = None
478 src_zero = 0
479 dst_zero = 0
480 sv_mode = None
481
482 mapreduce = False
483 reverse_gear = False
484 mapreduce_crm = False
485 mapreduce_svm = False
486
487 predresult = False
488 failfirst = False
489 ldst_elstride = 0
490
491 # ok let's start identifying opcode augmentation fields
492 for encmode in opmodes:
493 # predicate mask (src and dest)
494 if encmode.startswith("m="):
495 pme = encmode
496 pmmode, pmask = decode_predicate(encmode[2:])
497 smmode, smask = pmmode, pmask
498 mmode = pmmode
499 mask_m_specified = True
500 # predicate mask (dest)
501 elif encmode.startswith("dm="):
502 pme = encmode
503 pmmode, pmask = decode_predicate(encmode[3:])
504 mmode = pmmode
505 has_pmask = True
506 # predicate mask (src, twin-pred)
507 elif encmode.startswith("sm="):
508 sme = encmode
509 smmode, smask = decode_predicate(encmode[3:])
510 mmode = smmode
511 has_smask = True
512 # vec2/3/4
513 elif encmode.startswith("vec"):
514 subvl = decode_subvl(encmode[3:])
515 # elwidth
516 elif encmode.startswith("ew="):
517 destwid = decode_elwidth(encmode[3:])
518 elif encmode.startswith("sw="):
519 srcwid = decode_elwidth(encmode[3:])
520 # element-strided LD/ST
521 elif encmode == 'els':
522 ldst_elstride = 1
523 # saturation
524 elif encmode == 'sats':
525 assert sv_mode is None
526 saturation = 1
527 sv_mode = 0b10
528 elif encmode == 'satu':
529 assert sv_mode is None
530 sv_mode = 0b10
531 saturation = 0
532 # predicate zeroing
533 elif encmode == 'sz':
534 src_zero = 1
535 elif encmode == 'dz':
536 dst_zero = 1
537 # failfirst
538 elif encmode.startswith("ff="):
539 assert sv_mode is None
540 sv_mode = 0b01
541 failfirst = decode_ffirst(encmode[3:])
542 # predicate-result, interestingly same as fail-first
543 elif encmode.startswith("pr="):
544 assert sv_mode is None
545 sv_mode = 0b11
546 predresult = decode_ffirst(encmode[3:])
547 # map-reduce mode, reverse-gear
548 elif encmode == 'mrr':
549 assert sv_mode is None
550 sv_mode = 0b00
551 mapreduce = True
552 reverse_gear = True
553 # map-reduce mode
554 elif encmode == 'mr':
555 assert sv_mode is None
556 sv_mode = 0b00
557 mapreduce = True
558 elif encmode == 'crm': # CR on map-reduce
559 assert sv_mode is None
560 sv_mode = 0b00
561 mapreduce_crm = True
562 elif encmode == 'svm': # sub-vector mode
563 mapreduce_svm = True
564 else:
565 raise AssertionError("unknown encmode %s" % encmode)
566
567 if ptype == '2P':
568 # since m=xx takes precedence (overrides) sm=xx and dm=xx,
569 # treat them as mutually exclusive
570 if mask_m_specified:
571 assert not has_smask,\
572 "cannot have both source-mask and predicate mask"
573 assert not has_pmask,\
574 "cannot have both dest-mask and predicate mask"
575 # since the default is INT predication (ALWAYS), if you
576 # specify one CR mask, you must specify both, to avoid
577 # mixing INT and CR reg types
578 if has_pmask and pmmode == 1:
579 assert has_smask, \
580 "need explicit source-mask in CR twin predication"
581 if has_smask and smmode == 1:
582 assert has_pmask, \
583 "need explicit dest-mask in CR twin predication"
584 # sanity-check that 2Pred mask is same mode
585 if has_pmask and has_smask:
586 assert smmode == pmmode, \
587 "predicate masks %s and %s must be same reg type" % \
588 (pme, sme)
589
590 # sanity-check that twin-predication mask only specified in 2P mode
591 if ptype == '1P':
592 assert not has_smask, \
593 "source-mask can only be specified on Twin-predicate ops"
594 assert not has_pmask, \
595 "dest-mask can only be specified on Twin-predicate ops"
596
597 # construct the mode field, doing sanity-checking along the way
598 if mapreduce_svm:
599 assert sv_mode == 0b00, "sub-vector mode in mapreduce only"
600 assert subvl != 0, "sub-vector mode not possible on SUBVL=1"
601
602 if src_zero:
603 assert has_smask or mask_m_specified, \
604 "src zeroing requires a source predicate"
605 if dst_zero:
606 assert has_pmask or mask_m_specified, \
607 "dest zeroing requires a dest predicate"
608
609 ######################################
610 # "normal" mode
611 if sv_mode is None:
612 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
613 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
614 if is_ldst:
615 # TODO: for now, LD/ST-indexed is ignored.
616 mode |= ldst_elstride << SVP64MODE.ELS_NORMAL # element-strided
617 else:
618 # TODO, reduce and subvector mode
619 # 00 1 dz CRM reduce mode (mapreduce), SUBVL=1
620 # 00 1 SVM CRM subvector reduce mode, SUBVL>1
621 pass
622 sv_mode = 0b00
623
624 ######################################
625 # "mapreduce" modes
626 elif sv_mode == 0b00:
627 mode |= (0b1<<SVP64MODE.REDUCE) # sets mapreduce
628 assert dst_zero == 0, "dest-zero not allowed in mapreduce mode"
629 if reverse_gear:
630 mode |= (0b1<<SVP64MODE.RG) # sets Reverse-gear mode
631 if mapreduce_crm:
632 mode |= (0b1<<SVP64MODE.CRM) # sets CRM mode
633 assert rc_mode, "CRM only allowed when Rc=1"
634 # bit of weird encoding to jam zero-pred or SVM mode in.
635 # SVM mode can be enabled only when SUBVL=2/3/4 (vec2/3/4)
636 if subvl == 0:
637 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
638 elif mapreduce_svm:
639 mode |= (0b1<<SVP64MODE.SVM) # sets SVM mode
640
641 ######################################
642 # "failfirst" modes
643 elif sv_mode == 0b01:
644 assert src_zero == 0, "dest-zero not allowed in failfirst mode"
645 if failfirst == 'RC1':
646 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
647 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
648 assert rc_mode==False, "ffirst RC1 only possible when Rc=0"
649 elif failfirst == '~RC1':
650 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
651 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
652 mode |= (0b1<<SVP64MODE.INV) # ... with inversion
653 assert rc_mode==False, "ffirst RC1 only possible when Rc=0"
654 else:
655 assert dst_zero == 0, "dst-zero not allowed in ffirst BO"
656 assert rc_mode, "ffirst BO only possible when Rc=1"
657 mode |= (failfirst << SVP64MODE.BO_LSB) # set BO
658
659 ######################################
660 # "saturation" modes
661 elif sv_mode == 0b10:
662 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
663 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
664 mode |= (saturation << SVP64MODE.N) # signed/unsigned saturation
665
666 ######################################
667 # "predicate-result" modes. err... code-duplication from ffirst
668 elif sv_mode == 0b11:
669 assert src_zero == 0, "dest-zero not allowed in predresult mode"
670 if predresult == 'RC1':
671 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
672 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
673 assert rc_mode==False, "pr-mode RC1 only possible when Rc=0"
674 elif predresult == '~RC1':
675 mode |= (0b1<<SVP64MODE.RC1) # sets RC1 mode
676 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
677 mode |= (0b1<<SVP64MODE.INV) # ... with inversion
678 assert rc_mode==False, "pr-mode RC1 only possible when Rc=0"
679 else:
680 assert dst_zero == 0, "dst-zero not allowed in pr-mode BO"
681 assert rc_mode, "pr-mode BO only possible when Rc=1"
682 mode |= (predresult << SVP64MODE.BO_LSB) # set BO
683
684 # whewww.... modes all done :)
685 # now put into svp64_rm
686 mode |= sv_mode
687 # mode: bits 19-23
688 svp64_rm.mode.eq(SelectableInt(mode, SVP64RM_MODE_SIZE))
689
690 # put in predicate masks into svp64_rm
691 if ptype == '2P':
692 # source pred: bits 16-18
693 svp64_rm.smask.eq(SelectableInt(smask, SVP64RM_SMASK_SIZE))
694 # mask mode: bit 0
695 svp64_rm.mmode.eq(SelectableInt(mmode, SVP64RM_MMODE_SIZE))
696 # 1-pred: bits 1-3
697 svp64_rm.mask.eq(SelectableInt(pmask, SVP64RM_MASK_SIZE))
698
699 # and subvl: bits 8-9
700 svp64_rm.subvl.eq(SelectableInt(subvl, SVP64RM_SUBVL_SIZE))
701
702 # put in elwidths
703 # srcwid: bits 6-7
704 svp64_rm.ewsrc.eq(SelectableInt(srcwid, SVP64RM_EWSRC_SIZE))
705 # destwid: bits 4-5
706 svp64_rm.elwidth.eq(SelectableInt(destwid, SVP64RM_ELWIDTH_SIZE))
707
708 # nice debug printout. (and now for something completely different)
709 # https://youtu.be/u0WOIwlXE9g?t=146
710 svp64_rm_value = svp64_rm.spr.value
711 log ("svp64_rm", hex(svp64_rm_value), bin(svp64_rm_value))
712 log (" mmode 0 :", bin(mmode))
713 log (" pmask 1-3 :", bin(pmask))
714 log (" dstwid 4-5 :", bin(destwid))
715 log (" srcwid 6-7 :", bin(srcwid))
716 log (" subvl 8-9 :", bin(subvl))
717 log (" mode 19-23:", bin(mode))
718 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
719 for idx, sv_extra in extras.items():
720 if idx is None: continue
721 if idx[0] == 'imm': continue
722 srcdest, idx, duplicate = idx
723 start = (10+idx*offs)
724 end = start + offs-1
725 log (" extra%d %2d-%2d:" % (idx, start, end),
726 bin(sv_extra))
727 if ptype == '2P':
728 log (" smask 16-17:", bin(smask))
729 log ()
730
731 # first, construct the prefix from its subfields
732 svp64_prefix = SVP64PrefixFields()
733 svp64_prefix.major.eq(SelectableInt(0x1, SV64P_MAJOR_SIZE))
734 svp64_prefix.pid.eq(SelectableInt(0b11, SV64P_PID_SIZE))
735 svp64_prefix.rm.eq(svp64_rm.spr)
736
737 # fiinally yield the svp64 prefix and the thingy. v3.0b opcode
738 rc = '.' if rc_mode else ''
739 yield ".long 0x%x" % svp64_prefix.insn.value
740 yield "%s %s" % (v30b_op+rc, ", ".join(v30b_newfields))
741 log ("new v3.0B fields", v30b_op, v30b_newfields)
742
743 def translate(self, lst):
744 for insn in lst:
745 yield from self.translate_one(insn)
746
747
748 def macro_subst(macros, txt):
749 again = True
750 print ("subst", txt, macros)
751 while again:
752 again = False
753 for macro, value in macros.items():
754 if macro == txt:
755 again = True
756 replaced = txt.replace(macro, value)
757 print ("macro", txt, "replaced", replaced, macro, value)
758 txt = replaced
759 continue
760 toreplace = '%s.s' % macro
761 if toreplace == txt:
762 again = True
763 replaced = txt.replace(toreplace, "%s.s" % value)
764 print ("macro", txt, "replaced", replaced, toreplace, value)
765 txt = replaced
766 continue
767 toreplace = '%s.v' % macro
768 if toreplace == txt:
769 again = True
770 replaced = txt.replace(toreplace, "%s.v" % value)
771 print ("macro", txt, "replaced", replaced, toreplace, value)
772 txt = replaced
773 continue
774 toreplace = '(%s)' % macro
775 if toreplace in txt:
776 again = True
777 replaced = txt.replace(toreplace, '(%s)' % value)
778 print ("macro", txt, "replaced", replaced, toreplace, value)
779 txt = replaced
780 continue
781 print (" processed", txt)
782 return txt
783
784
785 def get_ws(line):
786 # find whitespace
787 ws = ''
788 while line:
789 if not line[0].isspace():
790 break
791 ws += line[0]
792 line = line[1:]
793 return ws, line
794
795
796 def asm_process():
797
798 # get an input file and an output file
799 args = sys.argv[1:]
800 if len(args) == 0:
801 infile = sys.stdin
802 outfile = sys.stdout
803 # read the whole lot in advance in case of in-place
804 lines = list(infile.readlines())
805 elif len(args) != 2:
806 print ("pysvp64asm [infile | -] [outfile | -]")
807 exit(0)
808 else:
809 if args[0] == '--':
810 infile = sys.stdin
811 else:
812 infile = open(args[0], "r")
813 # read the whole lot in advance in case of in-place overwrite
814 lines = list(infile.readlines())
815
816 if args[1] == '--':
817 outfile = sys.stdout
818 else:
819 outfile = open(args[1], "w")
820
821 # read the line, look for "sv", process it
822 macros = {} # macros which start ".set"
823 isa = SVP64Asm([])
824 for line in lines:
825 ls = line.split("#")
826 # identify macros
827 if ls[0].strip().startswith("setvl"):
828 ws, line = get_ws(ls[0])
829 lst = list(isa.translate_one(ls[0].strip(), macros))
830 lst = '; '.join(lst)
831 outfile.write("%s%s # %s\n" % (ws, lst, ls[0]))
832 continue
833 if ls[0].startswith(".set"):
834 macro = ls[0][4:].split(",")
835 macro, value = list(map(str.strip, macro))
836 macros[macro] = value
837 if len(ls) != 2:
838 outfile.write(line)
839 continue
840 potential= ls[1].strip()
841 if not potential.startswith("sv."):
842 outfile.write(line)
843 continue
844
845 ws, line = get_ws(line)
846 # SV line indentified
847 lst = list(isa.translate_one(potential, macros))
848 lst = '; '.join(lst)
849 outfile.write("%s%s # %s\n" % (ws, lst, potential))
850
851
852 if __name__ == '__main__':
853 lst = ['slw 3, 1, 4',
854 'extsw 5, 3',
855 'sv.extsw 5, 3',
856 'sv.cmpi 5, 1, 3, 2',
857 'sv.setb 5, 31',
858 'sv.isel 64.v, 3, 2, 65.v',
859 'sv.setb/dm=r3/sm=1<<r3 5, 31',
860 'sv.setb/m=r3 5, 31',
861 'sv.setb/vec2 5, 31',
862 'sv.setb/sw=8/ew=16 5, 31',
863 'sv.extsw./ff=eq 5, 31',
864 'sv.extsw./satu/sz/dz/sm=r3/dm=r3 5, 31',
865 'sv.extsw./pr=eq 5.v, 31',
866 'sv.add. 5.v, 2.v, 1.v',
867 'sv.add./m=r3 5.v, 2.v, 1.v',
868 ]
869 lst += [
870 'sv.stw 5.v, 4(1.v)',
871 'sv.ld 5.v, 4(1.v)',
872 'setvl. 2, 3, 4, 1, 1',
873 ]
874 lst = [
875 "sv.stfsu 0.v, 16(4.v)",
876 ]
877 lst = [
878 "sv.stfsu/els 0.v, 16(4)",
879 ]
880 lst = [
881 'sv.add./mr 5.v, 2.v, 1.v',
882 ]
883 macros = {'win2': '50', 'win': '60'}
884 lst = [
885 'sv.addi win2.v, win.v, -1',
886 'sv.add./mrr 5.v, 2.v, 1.v',
887 ]
888 isa = SVP64Asm(lst, macros=macros)
889 print ("list", list(isa))
890 csvs = SVP64RM()
891 #asm_process()