note possible BE/LE mode needed for memory reads/writes
[soc.git] / src / soc / decoder / isa / caller.py
1 """core of the python-based POWER9 simulator
2
3 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
4 not speed, it is for both learning and educational purposes, as well as
5 a method of verifying the HDL.
6 """
7
8 from functools import wraps
9 from soc.decoder.orderedset import OrderedSet
10 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
11 selectconcat)
12 from soc.decoder.power_enums import spr_dict, XER_bits
13 from soc.decoder.helpers import exts
14 from collections import namedtuple
15 import math
16
17 instruction_info = namedtuple('instruction_info',
18 'func read_regs uninit_regs write_regs ' + \
19 'special_regs op_fields form asmregs')
20
21 special_sprs = {
22 'LR': 8,
23 'CTR': 9,
24 'TAR': 815,
25 'XER': 1,
26 'VRSAVE': 256}
27
28
29 def create_args(reglist, extra=None):
30 args = OrderedSet()
31 for reg in reglist:
32 args.add(reg)
33 args = list(args)
34 if extra:
35 args = [extra] + args
36 return args
37
38
39 class Mem:
40
41 def __init__(self, bytes_per_word=8, initial_mem=None):
42 self.mem = {}
43 self.bytes_per_word = bytes_per_word
44 self.word_log2 = math.ceil(math.log2(bytes_per_word))
45 if not initial_mem:
46 return
47 print ("Sim-Mem", initial_mem, self.bytes_per_word)
48 for addr, (val, width) in initial_mem.items():
49 self.st(addr, val, width)
50
51 def _get_shifter_mask(self, wid, remainder):
52 shifter = ((self.bytes_per_word - wid) - remainder) * \
53 8 # bits per byte
54 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
55 # BE/LE mode?
56 # shifter = remainder * 8
57 mask = (1 << (wid * 8)) - 1
58 print ("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
59 return shifter, mask
60
61 # TODO: Implement ld/st of lesser width
62 def ld(self, address, width=8):
63 print("ld from addr 0x{:x} width {:d}".format(address, width))
64 remainder = address & (self.bytes_per_word - 1)
65 address = address >> self.word_log2
66 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
67 if address in self.mem:
68 val = self.mem[address]
69 else:
70 val = 0
71 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
72
73 if width != self.bytes_per_word:
74 shifter, mask = self._get_shifter_mask(width, remainder)
75 print ("masking", hex(val), hex(mask<<shifter), shifter)
76 val = val & (mask << shifter)
77 val >>= shifter
78 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
79 return val
80
81 def st(self, addr, v, width=8):
82 staddr = addr
83 remainder = addr & (self.bytes_per_word - 1)
84 addr = addr >> self.word_log2
85 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v,
86 staddr, addr, remainder))
87 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
88 if width != self.bytes_per_word:
89 if addr in self.mem:
90 val = self.mem[addr]
91 else:
92 val = 0
93 shifter, mask = self._get_shifter_mask(width, remainder)
94 val &= ~(mask << shifter)
95 val |= v << shifter
96 self.mem[addr] = val
97 else:
98 self.mem[addr] = v
99 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
100
101 def __call__(self, addr, sz):
102 val = self.ld(addr.value, sz)
103 print ("memread", addr, sz, val)
104 return SelectableInt(val, sz*8)
105
106 def memassign(self, addr, sz, val):
107 print ("memassign", addr, sz, val)
108 self.st(addr.value, val.value, sz)
109
110
111 class GPR(dict):
112 def __init__(self, decoder, regfile):
113 dict.__init__(self)
114 self.sd = decoder
115 for i in range(32):
116 self[i] = SelectableInt(regfile[i], 64)
117
118 def __call__(self, ridx):
119 return self[ridx]
120
121 def set_form(self, form):
122 self.form = form
123
124 def getz(self, rnum):
125 #rnum = rnum.value # only SelectableInt allowed
126 print("GPR getzero", rnum)
127 if rnum == 0:
128 return SelectableInt(0, 64)
129 return self[rnum]
130
131 def _get_regnum(self, attr):
132 getform = self.sd.sigforms[self.form]
133 rnum = getattr(getform, attr)
134 return rnum
135
136 def ___getitem__(self, attr):
137 print("GPR getitem", attr)
138 rnum = self._get_regnum(attr)
139 return self.regfile[rnum]
140
141 def dump(self):
142 for i in range(0, len(self), 8):
143 s = []
144 for j in range(8):
145 s.append("%08x" % self[i+j].value)
146 s = ' '.join(s)
147 print("reg", "%2d" % i, s)
148
149 class PC:
150 def __init__(self, pc_init=0):
151 self.CIA = SelectableInt(pc_init, 64)
152 self.NIA = self.CIA + SelectableInt(4, 64)
153
154 def update(self, namespace):
155 self.CIA = namespace['NIA'].narrow(64)
156 self.NIA = self.CIA + SelectableInt(4, 64)
157 namespace['CIA'] = self.CIA
158 namespace['NIA'] = self.NIA
159
160
161 class SPR(dict):
162 def __init__(self, dec2, initial_sprs={}):
163 self.sd = dec2
164 dict.__init__(self)
165 self.update(initial_sprs)
166
167 def __getitem__(self, key):
168 # if key in special_sprs get the special spr, otherwise return key
169 if isinstance(key, SelectableInt):
170 key = key.value
171 key = special_sprs.get(key, key)
172 if key in self:
173 return dict.__getitem__(self, key)
174 else:
175 info = spr_dict[key]
176 dict.__setitem__(self, key, SelectableInt(0, info.length))
177 return dict.__getitem__(self, key)
178
179 def __setitem__(self, key, value):
180 if isinstance(key, SelectableInt):
181 key = key.value
182 key = special_sprs.get(key, key)
183 dict.__setitem__(self, key, value)
184
185 def __call__(self, ridx):
186 return self[ridx]
187
188
189
190 class ISACaller:
191 # decoder2 - an instance of power_decoder2
192 # regfile - a list of initial values for the registers
193 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
194 initial_mem=None, initial_msr=0):
195 if initial_sprs is None:
196 initial_sprs = {}
197 if initial_mem is None:
198 initial_mem = {}
199 self.gpr = GPR(decoder2, regfile)
200 self.mem = Mem(bytes_per_word=8, initial_mem=initial_mem)
201 self.pc = PC()
202 self.spr = SPR(decoder2, initial_sprs)
203 self.msr = SelectableInt(initial_msr, 64) # underlying reg
204 # TODO, needed here:
205 # FPR (same as GPR except for FP nums)
206 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
207 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
208 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
209 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
210 # -- Done
211 # 2.3.2 LR (actually SPR #8) -- Done
212 # 2.3.3 CTR (actually SPR #9) -- Done
213 # 2.3.4 TAR (actually SPR #815)
214 # 3.2.2 p45 XER (actually SPR #1) -- Done
215 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
216
217 # create CR then allow portions of it to be "selectable" (below)
218 self._cr = SelectableInt(initial_cr, 64) # underlying reg
219 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
220
221 # "undefined", just set to variable-bit-width int (use exts "max")
222 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
223
224 self.namespace = {'GPR': self.gpr,
225 'MEM': self.mem,
226 'SPR': self.spr,
227 'memassign': self.memassign,
228 'NIA': self.pc.NIA,
229 'CIA': self.pc.CIA,
230 'CR': self.cr,
231 'MSR': self.msr,
232 'undefined': self.undefined,
233 'mode_is_64bit': True,
234 'SO': XER_bits['SO']
235 }
236
237 # field-selectable versions of Condition Register TODO check bitranges?
238 self.crl = []
239 for i in range(8):
240 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
241 _cr = FieldSelectableInt(self.cr, bits)
242 self.crl.append(_cr)
243 self.namespace["CR%d" % i] = _cr
244
245 self.decoder = decoder2.dec
246 self.dec2 = decoder2
247
248 def TRAP(self, trap_addr=0x700):
249 print ("TRAP: TODO")
250 # store CIA(+4?) in SRR0, set NIA to 0x700
251 # store MSR in SRR1, set MSR to um errr something, have to check spec
252
253 def memassign(self, ea, sz, val):
254 self.mem.memassign(ea, sz, val)
255
256 def prep_namespace(self, formname, op_fields):
257 # TODO: get field names from form in decoder*1* (not decoder2)
258 # decoder2 is hand-created, and decoder1.sigform is auto-generated
259 # from spec
260 # then "yield" fields only from op_fields rather than hard-coded
261 # list, here.
262 fields = self.decoder.sigforms[formname]
263 for name in op_fields:
264 if name == 'spr':
265 sig = getattr(fields, name.upper())
266 else:
267 sig = getattr(fields, name)
268 val = yield sig
269 if name in ['BF', 'BFA']:
270 self.namespace[name] = val
271 else:
272 self.namespace[name] = SelectableInt(val, sig.width)
273
274 self.namespace['XER'] = self.spr['XER']
275 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
276 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
277
278 def handle_carry_(self, inputs, outputs, already_done):
279 inv_a = yield self.dec2.e.invert_a
280 if inv_a:
281 inputs[0] = ~inputs[0]
282
283 imm_ok = yield self.dec2.e.imm_data.ok
284 if imm_ok:
285 imm = yield self.dec2.e.imm_data.data
286 inputs.append(SelectableInt(imm, 64))
287 assert len(outputs) >= 1
288 output = outputs[0]
289 gts = [(x > output) for x in inputs]
290 print(gts)
291 cy = 1 if any(gts) else 0
292 if not (1 & already_done):
293 self.spr['XER'][XER_bits['CA']] = cy
294
295 print ("inputs", inputs)
296 # 32 bit carry
297 gts = [(x[32:64] > output[32:64]) == SelectableInt(1, 1)
298 for x in inputs]
299 cy32 = 1 if any(gts) else 0
300 if not (2 & already_done):
301 self.spr['XER'][XER_bits['CA32']] = cy32
302
303 def handle_overflow(self, inputs, outputs):
304 inv_a = yield self.dec2.e.invert_a
305 if inv_a:
306 inputs[0] = ~inputs[0]
307
308 imm_ok = yield self.dec2.e.imm_data.ok
309 if imm_ok:
310 imm = yield self.dec2.e.imm_data.data
311 inputs.append(SelectableInt(imm, 64))
312 assert len(outputs) >= 1
313 if len(inputs) >= 2:
314 output = outputs[0]
315
316 # OV (64-bit)
317 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
318 output_sgn = exts(output.value, output.bits) < 0
319 ov = 1 if input_sgn[0] == input_sgn[1] and \
320 output_sgn != input_sgn[0] else 0
321
322 # OV (32-bit)
323 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
324 output32_sgn = exts(output.value, 32) < 0
325 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
326 output32_sgn != input32_sgn[0] else 0
327
328 self.spr['XER'][XER_bits['OV']] = ov
329 self.spr['XER'][XER_bits['OV32']] = ov32
330 so = self.spr['XER'][XER_bits['SO']]
331 so = so | ov
332 self.spr['XER'][XER_bits['SO']] = so
333
334
335
336 def handle_comparison(self, outputs):
337 out = outputs[0]
338 out = exts(out.value, out.bits)
339 zero = SelectableInt(out == 0, 1)
340 positive = SelectableInt(out > 0, 1)
341 negative = SelectableInt(out < 0, 1)
342 SO = self.spr['XER'][XER_bits['SO']]
343 cr_field = selectconcat(negative, positive, zero, SO)
344 self.crl[0].eq(cr_field)
345
346 def set_pc(self, pc_val):
347 self.namespace['NIA'] = SelectableInt(pc_val, 64)
348 self.pc.update(self.namespace)
349
350
351 def call(self, name):
352 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
353 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
354 info = self.instrs[name]
355 yield from self.prep_namespace(info.form, info.op_fields)
356
357 # preserve order of register names
358 input_names = create_args(list(info.read_regs) + list(info.uninit_regs))
359 print(input_names)
360
361 # main registers (RT, RA ...)
362 inputs = []
363 for name in input_names:
364 regnum = yield getattr(self.decoder, name)
365 regname = "_" + name
366 self.namespace[regname] = regnum
367 print('reading reg %d' % regnum)
368 inputs.append(self.gpr(regnum))
369
370 # "special" registers
371 for special in info.special_regs:
372 if special in special_sprs:
373 inputs.append(self.spr[special])
374 else:
375 inputs.append(self.namespace[special])
376
377 print(inputs)
378 results = info.func(self, *inputs)
379 print(results)
380
381 # detect if CA/CA32 already in outputs (sra*, basically)
382 already_done = 0
383 if info.write_regs:
384 output_names = create_args(info.write_regs)
385 for name in output_names:
386 if name == 'CA':
387 already_done |= 1
388 if name == 'CA32':
389 already_done |= 2
390
391 print ("carry already done?", bin(already_done))
392 carry_en = yield self.dec2.e.output_carry
393 if carry_en:
394 yield from self.handle_carry_(inputs, results, already_done)
395 ov_en = yield self.dec2.e.oe.oe
396 ov_ok = yield self.dec2.e.oe.ok
397 if ov_en & ov_ok:
398 yield from self.handle_overflow(inputs, results)
399 rc_en = yield self.dec2.e.rc.data
400 if rc_en:
401 self.handle_comparison(results)
402
403 # any modified return results?
404 if info.write_regs:
405 for name, output in zip(output_names, results):
406 if isinstance(output, int):
407 output = SelectableInt(output, 256)
408 if name in ['CA', 'CA32']:
409 if carry_en:
410 print ("writing %s to XER" % name, output)
411 self.spr['XER'][XER_bits[name]] = output.value
412 else:
413 print ("NOT writing %s to XER" % name, output)
414 elif name in info.special_regs:
415 print('writing special %s' % name, output, special_sprs)
416 if name in special_sprs:
417 self.spr[name] = output
418 else:
419 self.namespace[name].eq(output)
420 else:
421 regnum = yield getattr(self.decoder, name)
422 print('writing reg %d %s' % (regnum, str(output)))
423 if output.bits > 64:
424 output = SelectableInt(output.value, 64)
425 self.gpr[regnum] = output
426
427 # update program counter
428 self.pc.update(self.namespace)
429
430
431 def inject():
432 """Decorator factory.
433
434 this decorator will "inject" variables into the function's namespace,
435 from the *dictionary* in self.namespace. it therefore becomes possible
436 to make it look like a whole stack of variables which would otherwise
437 need "self." inserted in front of them (*and* for those variables to be
438 added to the instance) "appear" in the function.
439
440 "self.namespace['SI']" for example becomes accessible as just "SI" but
441 *only* inside the function, when decorated.
442 """
443 def variable_injector(func):
444 @wraps(func)
445 def decorator(*args, **kwargs):
446 try:
447 func_globals = func.__globals__ # Python 2.6+
448 except AttributeError:
449 func_globals = func.func_globals # Earlier versions.
450
451 context = args[0].namespace # variables to be injected
452 saved_values = func_globals.copy() # Shallow copy of dict.
453 func_globals.update(context)
454 result = func(*args, **kwargs)
455 args[0].namespace = func_globals
456 #exec (func.__code__, func_globals)
457
458 #finally:
459 # func_globals = saved_values # Undo changes.
460
461 return result
462
463 return decorator
464
465 return variable_injector
466