enable hazard vecs in core
[soc.git] / src / soc / simple / core.py
1 """simple core
2
3 not in any way intended for production use. connects up FunctionUnits to
4 Register Files in a brain-dead fashion that only permits one and only one
5 Function Unit to be operational.
6
7 the principle here is to take the Function Units, analyse their regspecs,
8 and turn their requirements for access to register file read/write ports
9 into groupings by Register File and Register File Port name.
10
11 under each grouping - by regfile/port - a list of Function Units that
12 need to connect to that port is created. as these are a contended
13 resource a "Broadcast Bus" per read/write port is then also created,
14 with access to it managed by a PriorityPicker.
15
16 the brain-dead part of this module is that even though there is no
17 conflict of access, regfile read/write hazards are *not* analysed,
18 and consequently it is safer to wait for the Function Unit to complete
19 before allowing a new instruction to proceed.
20 """
21
22 from nmigen import Elaboratable, Module, Signal, ResetSignal, Cat, Mux
23 from nmigen.cli import rtlil
24
25 from openpower.decoder.power_decoder2 import PowerDecodeSubset
26 from openpower.decoder.power_regspec_map import regspec_decode_read
27 from openpower.decoder.power_regspec_map import regspec_decode_write
28 from openpower.sv.svp64 import SVP64Rec
29
30 from nmutil.picker import PriorityPicker
31 from nmutil.util import treereduce
32 from nmutil.singlepipe import ControlBase
33
34 from soc.fu.compunits.compunits import AllFunctionUnits
35 from soc.regfile.regfiles import RegFiles
36 from openpower.decoder.decode2execute1 import Decode2ToExecute1Type
37 from openpower.decoder.decode2execute1 import IssuerDecode2ToOperand
38 from openpower.decoder.power_decoder2 import get_rdflags
39 from openpower.decoder.decode2execute1 import Data
40 from soc.experiment.l0_cache import TstL0CacheBuffer # test only
41 from soc.config.test.test_loadstore import TestMemPspec
42 from openpower.decoder.power_enums import MicrOp, Function
43 from soc.config.state import CoreState
44
45 from collections import defaultdict
46 import operator
47
48 from nmutil.util import rising_edge
49
50
51 # helper function for reducing a list of signals down to a parallel
52 # ORed single signal.
53 def ortreereduce(tree, attr="o_data"):
54 return treereduce(tree, operator.or_, lambda x: getattr(x, attr))
55
56
57 def ortreereduce_sig(tree):
58 return treereduce(tree, operator.or_, lambda x: x)
59
60
61 # helper function to place full regs declarations first
62 def sort_fuspecs(fuspecs):
63 res = []
64 for (regname, fspec) in fuspecs.items():
65 if regname.startswith("full"):
66 res.append((regname, fspec))
67 for (regname, fspec) in fuspecs.items():
68 if not regname.startswith("full"):
69 res.append((regname, fspec))
70 return res # enumerate(res)
71
72
73 class CoreInput:
74 """CoreInput: this is the input specification for Signals coming into core.
75
76 * state. this contains PC, MSR, and SVSTATE. this is crucial information.
77 (TODO: bigendian_i should really be read from the relevant MSR bit)
78
79 * the previously-decoded instruction goes into the Decode2Execute1Type
80 data structure. no need for Core to re-decode that. however note
81 that *satellite* decoders *are* part of Core.
82
83 * the raw instruction. this is used by satellite decoders internal to
84 Core, to provide Function-Unit-specific information. really, they
85 should be part of the actual ALU itself (in order to reduce wires),
86 but hey.
87
88 * other stuff is related to SVP64. the 24-bit SV REMAP field containing
89 Vector context, etc.
90 """
91 def __init__(self, pspec, svp64_en, regreduce_en):
92 self.pspec = pspec
93 self.svp64_en = svp64_en
94 self.e = Decode2ToExecute1Type("core", opkls=IssuerDecode2ToOperand,
95 regreduce_en=regreduce_en)
96
97 # SVP64 RA_OR_ZERO needs to know if the relevant EXTRA2/3 field is zero
98 self.sv_a_nz = Signal()
99
100 # state and raw instruction (and SVP64 ReMap fields)
101 self.state = CoreState("core")
102 self.raw_insn_i = Signal(32) # raw instruction
103 self.bigendian_i = Signal() # bigendian - TODO, set by MSR.BE
104 if svp64_en:
105 self.sv_rm = SVP64Rec(name="core_svp64_rm") # SVP64 RM field
106 self.is_svp64_mode = Signal() # set if SVP64 mode is enabled
107 self.use_svp64_ldst_dec = Signal() # use alternative LDST decoder
108 self.sv_pred_sm = Signal() # TODO: SIMD width
109 self.sv_pred_dm = Signal() # TODO: SIMD width
110
111 def eq(self, i):
112 self.e.eq(i.e)
113 self.sv_a_nz.eq(i.sv_a_nz)
114 self.state.eq(i.state)
115 self.raw_insn_i.eq(i.raw_insn_i)
116 self.bigendian_i.eq(i.bigendian_i)
117 if not self.svp64_en:
118 return
119 self.sv_rm.eq(i.sv_rm)
120 self.is_svp64_mode.eq(i.is_svp64_mode)
121 self.use_svp64_ldst_dec.eq(i.use_svp64_ldst_dec)
122 self.sv_pred_sm.eq(i.sv_pred_sm)
123 self.sv_pred_dm.eq(i.sv_pred_dm)
124
125
126 class CoreOutput:
127 def __init__(self):
128 # start/stop and terminated signalling
129 self.core_terminate_o = Signal() # indicates stopped
130 self.busy_o = Signal(name="corebusy_o") # at least one ALU busy
131 self.exc_happened = Signal() # exception happened
132
133 def eq(self, i):
134 self.core_terminate_o.eq(i.core_terminate_o)
135 self.busy_o.eq(i.busy_o)
136 self.exc_happened.eq(i.exc_happened)
137
138
139 # derive from ControlBase rather than have a separate Stage instance,
140 # this is simpler to do
141 class NonProductionCore(ControlBase):
142 def __init__(self, pspec):
143 self.pspec = pspec
144
145 # test is SVP64 is to be enabled
146 self.svp64_en = hasattr(pspec, "svp64") and (pspec.svp64 == True)
147
148 # test to see if regfile ports should be reduced
149 self.regreduce_en = (hasattr(pspec, "regreduce") and
150 (pspec.regreduce == True))
151
152 # test core type
153 self.core_type = "fsm"
154 if hasattr(pspec, "core_type":
155 self.core_type = pspec.core_type
156
157 super().__init__(stage=self)
158
159 # single LD/ST funnel for memory access
160 self.l0 = l0 = TstL0CacheBuffer(pspec, n_units=1)
161 pi = l0.l0.dports[0]
162
163 # function units (only one each)
164 # only include mmu if enabled in pspec
165 self.fus = AllFunctionUnits(pspec, pilist=[pi])
166
167 # link LoadStore1 into MMU
168 mmu = self.fus.get_fu('mmu0')
169 print ("core pspec", pspec.ldst_ifacetype)
170 print ("core mmu", mmu)
171 print ("core lsmem.lsi", l0.cmpi.lsmem.lsi)
172 if mmu is not None:
173 mmu.alu.set_ldst_interface(l0.cmpi.lsmem.lsi)
174
175 # register files (yes plural)
176 self.regs = RegFiles(pspec, make_hazard_vecs=True)
177
178 # set up input and output: unusual requirement to set data directly
179 # (due to the way that the core is set up in a different domain,
180 # see TestIssuer.setup_peripherals
181 self.i, self.o = self.new_specs(None)
182 self.i, self.o = self.p.i_data, self.n.o_data
183
184 # create per-FU instruction decoders (subsetted)
185 self.decoders = {}
186 self.des = {}
187
188 for funame, fu in self.fus.fus.items():
189 f_name = fu.fnunit.name
190 fnunit = fu.fnunit.value
191 opkls = fu.opsubsetkls
192 if f_name == 'TRAP':
193 # TRAP decoder is the *main* decoder
194 self.trapunit = funame
195 continue
196 self.decoders[funame] = PowerDecodeSubset(None, opkls, f_name,
197 final=True,
198 state=self.i.state,
199 svp64_en=self.svp64_en,
200 regreduce_en=self.regreduce_en)
201 self.des[funame] = self.decoders[funame].do
202
203 if "mmu0" in self.decoders:
204 self.decoders["mmu0"].mmu0_spr_dec = self.decoders["spr0"]
205
206 def setup(self, m, i):
207 pass
208
209 def ispec(self):
210 return CoreInput(self.pspec, self.svp64_en, self.regreduce_en)
211
212 def ospec(self):
213 return CoreOutput()
214
215 def elaborate(self, platform):
216 m = super().elaborate(platform)
217
218 # for testing purposes, to cut down on build time in coriolis2
219 if hasattr(self.pspec, "nocore") and self.pspec.nocore == True:
220 x = Signal() # dummy signal
221 m.d.sync += x.eq(~x)
222 return m
223 comb = m.d.comb
224
225 m.submodules.fus = self.fus
226 m.submodules.l0 = l0 = self.l0
227 self.regs.elaborate_into(m, platform)
228 regs = self.regs
229 fus = self.fus.fus
230
231 # connect decoders
232 self.connect_satellite_decoders(m)
233
234 # ssh, cheat: trap uses the main decoder because of the rewriting
235 self.des[self.trapunit] = self.i.e.do
236
237 # connect up Function Units, then read/write ports
238 fu_bitdict, fu_selected = self.connect_instruction(m)
239 self.connect_rdports(m, fu_selected)
240 self.connect_wrports(m, fu_selected)
241
242 # note if an exception happened. in a pipelined or OoO design
243 # this needs to be accompanied by "shadowing" (or stalling)
244 el = []
245 for exc in self.fus.excs.values():
246 el.append(exc.happened)
247 if len(el) > 0: # at least one exception
248 comb += self.o.exc_happened.eq(Cat(*el).bool())
249
250 return m
251
252 def connect_satellite_decoders(self, m):
253 comb = m.d.comb
254 for k, v in self.decoders.items():
255 # connect each satellite decoder and give it the instruction.
256 # as subset decoders this massively reduces wire fanout given
257 # the large number of ALUs
258 setattr(m.submodules, "dec_%s" % v.fn_name, v)
259 comb += v.dec.raw_opcode_in.eq(self.i.raw_insn_i)
260 comb += v.dec.bigendian.eq(self.i.bigendian_i)
261 # sigh due to SVP64 RA_OR_ZERO detection connect these too
262 comb += v.sv_a_nz.eq(self.i.sv_a_nz)
263 if self.svp64_en:
264 comb += v.pred_sm.eq(self.i.sv_pred_sm)
265 comb += v.pred_dm.eq(self.i.sv_pred_dm)
266 if k != self.trapunit:
267 comb += v.sv_rm.eq(self.i.sv_rm) # pass through SVP64 ReMap
268 comb += v.is_svp64_mode.eq(self.i.is_svp64_mode)
269 # only the LDST PowerDecodeSubset *actually* needs to
270 # know to use the alternative decoder. this is all
271 # a terrible hack
272 if k.lower().startswith("ldst"):
273 comb += v.use_svp64_ldst_dec.eq(
274 self.i.use_svp64_ldst_dec)
275
276 def connect_instruction(self, m):
277 """connect_instruction
278
279 uses decoded (from PowerOp) function unit information from CSV files
280 to ascertain which Function Unit should deal with the current
281 instruction.
282
283 some (such as OP_ATTN, OP_NOP) are dealt with here, including
284 ignoring it and halting the processor. OP_NOP is a bit annoying
285 because the issuer expects busy flag still to be raised then lowered.
286 (this requires a fake counter to be set).
287 """
288 comb, sync = m.d.comb, m.d.sync
289 fus = self.fus.fus
290
291 # indicate if core is busy
292 busy_o = self.o.busy_o
293
294 # enable/busy-signals for each FU, get one bit for each FU (by name)
295 fu_enable = Signal(len(fus), reset_less=True)
296 fu_busy = Signal(len(fus), reset_less=True)
297 fu_bitdict = {}
298 fu_selected = {}
299 for i, funame in enumerate(fus.keys()):
300 fu_bitdict[funame] = fu_enable[i]
301 fu_selected[funame] = fu_busy[i]
302
303 # identify function units and create a list by fnunit so that
304 # PriorityPickers can be created for selecting one of them that
305 # isn't busy at the time the incoming instruction needs passing on
306 by_fnunit = defaultdict(list)
307 for fname, member in Function.__members__.items():
308 for funame, fu in fus.items():
309 fnunit = fu.fnunit.value
310 if member.value & fnunit: # this FU handles this type of op
311 by_fnunit[fname].append((funame, fu)) # add by Function
312
313 # ok now just print out the list of FUs by Function, because we can
314 for fname, fu_list in by_fnunit.items():
315 print ("FUs by type", fname, fu_list)
316
317 # now create a PriorityPicker per FU-type such that only one
318 # non-busy FU will be picked
319 issue_pps = {}
320 fu_found = Signal() # take a note if no Function Unit was available
321 for fname, fu_list in by_fnunit.items():
322 i_pp = PriorityPicker(len(fu_list))
323 m.submodules['i_pp_%s' % fname] = i_pp
324 i_l = []
325 for i, (funame, fu) in enumerate(fu_list):
326 # match the decoded instruction (e.do.fn_unit) against the
327 # "capability" of this FU, gate that by whether that FU is
328 # busy, and drop that into the PriorityPicker.
329 # this will give us an output of the first available *non-busy*
330 # Function Unit (Reservation Statio) capable of handling this
331 # instruction.
332 fnunit = fu.fnunit.value
333 en_req = Signal(name="issue_en_%s" % funame, reset_less=True)
334 fnmatch = (self.i.e.do.fn_unit & fnunit).bool()
335 comb += en_req.eq(fnmatch & ~fu.busy_o & self.p.i_valid)
336 i_l.append(en_req) # store in list for doing the Cat-trick
337 # picker output, gated by enable: store in fu_bitdict
338 po = Signal(name="o_issue_pick_"+funame) # picker output
339 comb += po.eq(i_pp.o[i] & i_pp.en_o)
340 comb += fu_bitdict[funame].eq(po)
341 comb += fu_selected[funame].eq(fu.busy_o | po)
342 # if we don't do this, then when there are no FUs available,
343 # the "p.o_ready" signal will go back "ok we accepted this
344 # instruction" which of course isn't true.
345 comb += fu_found.eq(~fnmatch | i_pp.en_o)
346 # for each input, Cat them together and drop them into the picker
347 comb += i_pp.i.eq(Cat(*i_l))
348
349 # sigh - need a NOP counter
350 counter = Signal(2)
351 with m.If(counter != 0):
352 sync += counter.eq(counter - 1)
353 comb += busy_o.eq(1)
354
355 with m.If(self.p.i_valid): # run only when valid
356 with m.Switch(self.i.e.do.insn_type):
357 # check for ATTN: halt if true
358 with m.Case(MicrOp.OP_ATTN):
359 m.d.sync += self.o.core_terminate_o.eq(1)
360
361 # fake NOP - this isn't really used (Issuer detects NOP)
362 with m.Case(MicrOp.OP_NOP):
363 sync += counter.eq(2)
364 comb += busy_o.eq(1)
365
366 with m.Default():
367 # connect up instructions. only one enabled at a time
368 for funame, fu in fus.items():
369 do = self.des[funame]
370 enable = fu_bitdict[funame]
371
372 # run this FunctionUnit if enabled
373 # route op, issue, busy, read flags and mask to FU
374 with m.If(enable):
375 # operand comes from the *local* decoder
376 comb += fu.oper_i.eq_from(do)
377 comb += fu.issue_i.eq(1) # issue when input valid
378 # rdmask, which is for registers, needs to come
379 # from the *main* decoder
380 rdmask = get_rdflags(self.i.e, fu)
381 comb += fu.rdmaskn.eq(~rdmask)
382
383 # if instruction is busy, set busy output for core.
384 busys = map(lambda fu: fu.busy_o, fus.values())
385 comb += busy_o.eq(Cat(*busys).bool())
386
387 # ready/valid signalling. if busy, means refuse incoming issue.
388 # (this is a global signal, TODO, change to one which allows
389 # overlapping instructions)
390 # also, if there was no fu found we must not send back a valid
391 # indicator. BUT, of course, when there is no instruction
392 # we must ignore the fu_found flag, otherwise o_ready will never
393 # be set when everything is idle
394 comb += self.p.o_ready.eq(fu_found | ~self.p.i_valid)
395
396 # return both the function unit "enable" dict as well as the "busy".
397 # the "busy-or-issued" can be passed in to the Read/Write port
398 # connecters to give them permission to request access to regfiles
399 return fu_bitdict, fu_selected
400
401 def connect_rdport(self, m, fu_bitdict, rdpickers, regfile, regname, fspec):
402 comb, sync = m.d.comb, m.d.sync
403 fus = self.fus.fus
404 regs = self.regs
405
406 rpidx = regname
407
408 # select the required read port. these are pre-defined sizes
409 rfile = regs.rf[regfile.lower()]
410 rport = rfile.r_ports[rpidx]
411 print("read regfile", rpidx, regfile, regs.rf.keys(),
412 rfile, rfile.unary)
413
414 fspecs = fspec
415 if not isinstance(fspecs, list):
416 fspecs = [fspecs]
417
418 rdflags = []
419 pplen = 0
420 reads = []
421 ppoffs = []
422 for i, fspec in enumerate(fspecs):
423 # get the regfile specs for this regfile port
424 (rf, read, write, wid, fuspec) = fspec
425 print ("fpsec", i, fspec, len(fuspec))
426 ppoffs.append(pplen) # record offset for picker
427 pplen += len(fuspec)
428 name = "rdflag_%s_%s_%d" % (regfile, regname, i)
429 rdflag = Signal(name=name, reset_less=True)
430 comb += rdflag.eq(rf)
431 rdflags.append(rdflag)
432 reads.append(read)
433
434 print ("pplen", pplen)
435
436 # create a priority picker to manage this port
437 rdpickers[regfile][rpidx] = rdpick = PriorityPicker(pplen)
438 setattr(m.submodules, "rdpick_%s_%s" % (regfile, rpidx), rdpick)
439
440 rens = []
441 addrs = []
442 for i, fspec in enumerate(fspecs):
443 (rf, read, write, wid, fuspec) = fspec
444 # connect up the FU req/go signals, and the reg-read to the FU
445 # and create a Read Broadcast Bus
446 for pi, (funame, fu, idx) in enumerate(fuspec):
447 pi += ppoffs[i]
448
449 # connect request-read to picker input, and output to go-rd
450 fu_active = fu_bitdict[funame]
451 name = "%s_%s_%s_%i" % (regfile, rpidx, funame, pi)
452 addr_en = Signal.like(reads[i], name="addr_en_"+name)
453 pick = Signal(name="pick_"+name) # picker input
454 rp = Signal(name="rp_"+name) # picker output
455 delay_pick = Signal(name="dp_"+name) # read-enable "underway"
456
457 # exclude any currently-enabled read-request (mask out active)
458 comb += pick.eq(fu.rd_rel_o[idx] & fu_active & rdflags[i] &
459 ~delay_pick)
460 comb += rdpick.i[pi].eq(pick)
461 comb += fu.go_rd_i[idx].eq(delay_pick) # pass in *delayed* pick
462
463 # if picked, select read-port "reg select" number to port
464 comb += rp.eq(rdpick.o[pi] & rdpick.en_o)
465 sync += delay_pick.eq(rp) # delayed "pick"
466 comb += addr_en.eq(Mux(rp, reads[i], 0))
467
468 # the read-enable happens combinatorially (see mux-bus below)
469 # but it results in the data coming out on a one-cycle delay.
470 if rfile.unary:
471 rens.append(addr_en)
472 else:
473 addrs.append(addr_en)
474 rens.append(rp)
475
476 # use the *delayed* pick signal to put requested data onto bus
477 with m.If(delay_pick):
478 # connect regfile port to input, creating fan-out Bus
479 src = fu.src_i[idx]
480 print("reg connect widths",
481 regfile, regname, pi, funame,
482 src.shape(), rport.o_data.shape())
483 # all FUs connect to same port
484 comb += src.eq(rport.o_data)
485
486 # or-reduce the muxed read signals
487 if rfile.unary:
488 # for unary-addressed
489 comb += rport.ren.eq(ortreereduce_sig(rens))
490 else:
491 # for binary-addressed
492 comb += rport.addr.eq(ortreereduce_sig(addrs))
493 comb += rport.ren.eq(Cat(*rens).bool())
494 print ("binary", regfile, rpidx, rport, rport.ren, rens, addrs)
495
496 def connect_rdports(self, m, fu_bitdict):
497 """connect read ports
498
499 orders the read regspecs into a dict-of-dicts, by regfile, by
500 regport name, then connects all FUs that want that regport by
501 way of a PriorityPicker.
502 """
503 comb, sync = m.d.comb, m.d.sync
504 fus = self.fus.fus
505 regs = self.regs
506
507 # dictionary of lists of regfile read ports
508 byregfiles_rd, byregfiles_rdspec = self.get_byregfiles(True)
509
510 # okaay, now we need a PriorityPicker per regfile per regfile port
511 # loootta pickers... peter piper picked a pack of pickled peppers...
512 rdpickers = {}
513 for regfile, spec in byregfiles_rd.items():
514 fuspecs = byregfiles_rdspec[regfile]
515 rdpickers[regfile] = {}
516
517 # argh. an experiment to merge RA and RB in the INT regfile
518 # (we have too many read/write ports)
519 if self.regreduce_en:
520 if regfile == 'INT':
521 fuspecs['rabc'] = [fuspecs.pop('rb')]
522 fuspecs['rabc'].append(fuspecs.pop('rc'))
523 fuspecs['rabc'].append(fuspecs.pop('ra'))
524 if regfile == 'FAST':
525 fuspecs['fast1'] = [fuspecs.pop('fast1')]
526 if 'fast2' in fuspecs:
527 fuspecs['fast1'].append(fuspecs.pop('fast2'))
528 if 'fast3' in fuspecs:
529 fuspecs['fast1'].append(fuspecs.pop('fast3'))
530
531 # for each named regfile port, connect up all FUs to that port
532 for (regname, fspec) in sort_fuspecs(fuspecs):
533 print("connect rd", regname, fspec)
534 self.connect_rdport(m, fu_bitdict, rdpickers, regfile,
535 regname, fspec)
536
537 def connect_wrport(self, m, fu_bitdict, wrpickers, regfile, regname, fspec):
538 comb, sync = m.d.comb, m.d.sync
539 fus = self.fus.fus
540 regs = self.regs
541
542 print("connect wr", regname, fspec)
543 rpidx = regname
544
545 # select the required write port. these are pre-defined sizes
546 print(regfile, regs.rf.keys())
547 rfile = regs.rf[regfile.lower()]
548 wport = rfile.w_ports[rpidx]
549
550 fspecs = fspec
551 if not isinstance(fspecs, list):
552 fspecs = [fspecs]
553
554 pplen = 0
555 writes = []
556 ppoffs = []
557 for i, fspec in enumerate(fspecs):
558 # get the regfile specs for this regfile port
559 (rf, read, write, wid, fuspec) = fspec
560 print ("fpsec", i, fspec, len(fuspec))
561 ppoffs.append(pplen) # record offset for picker
562 pplen += len(fuspec)
563
564 # create a priority picker to manage this port
565 wrpickers[regfile][rpidx] = wrpick = PriorityPicker(pplen)
566 setattr(m.submodules, "wrpick_%s_%s" % (regfile, rpidx), wrpick)
567
568 wsigs = []
569 wens = []
570 addrs = []
571 for i, fspec in enumerate(fspecs):
572 # connect up the FU req/go signals and the reg-read to the FU
573 # these are arbitrated by Data.ok signals
574 (rf, read, write, wid, fuspec) = fspec
575 for pi, (funame, fu, idx) in enumerate(fuspec):
576 pi += ppoffs[i]
577
578 # write-request comes from dest.ok
579 dest = fu.get_out(idx)
580 fu_dest_latch = fu.get_fu_out(idx) # latched output
581 name = "wrflag_%s_%s_%d" % (funame, regname, idx)
582 wrflag = Signal(name=name, reset_less=True)
583 comb += wrflag.eq(dest.ok & fu.busy_o)
584
585 # connect request-write to picker input, and output to go-wr
586 fu_active = fu_bitdict[funame]
587 pick = fu.wr.rel_o[idx] & fu_active # & wrflag
588 comb += wrpick.i[pi].eq(pick)
589 # create a single-pulse go write from the picker output
590 wr_pick = Signal(name="wpick_%s_%s_%d" % (funame, regname, idx))
591 comb += wr_pick.eq(wrpick.o[pi] & wrpick.en_o)
592 comb += fu.go_wr_i[idx].eq(rising_edge(m, wr_pick))
593
594 # connect the regspec write "reg select" number to this port
595 # only if one FU actually requests (and is granted) the port
596 # will the write-enable be activated
597 addr_en = Signal.like(write)
598 wp = Signal()
599 comb += wp.eq(wr_pick & wrpick.en_o)
600 comb += addr_en.eq(Mux(wp, write, 0))
601 if rfile.unary:
602 wens.append(addr_en)
603 else:
604 addrs.append(addr_en)
605 wens.append(wp)
606
607 # connect regfile port to input
608 print("reg connect widths",
609 regfile, regname, pi, funame,
610 dest.shape(), wport.i_data.shape())
611 wsigs.append(fu_dest_latch)
612
613 # here is where we create the Write Broadcast Bus. simple, eh?
614 comb += wport.i_data.eq(ortreereduce_sig(wsigs))
615 if rfile.unary:
616 # for unary-addressed
617 comb += wport.wen.eq(ortreereduce_sig(wens))
618 else:
619 # for binary-addressed
620 comb += wport.addr.eq(ortreereduce_sig(addrs))
621 comb += wport.wen.eq(ortreereduce_sig(wens))
622
623 def connect_wrports(self, m, fu_bitdict):
624 """connect write ports
625
626 orders the write regspecs into a dict-of-dicts, by regfile,
627 by regport name, then connects all FUs that want that regport
628 by way of a PriorityPicker.
629
630 note that the write-port wen, write-port data, and go_wr_i all need to
631 be on the exact same clock cycle. as there is a combinatorial loop bug
632 at the moment, these all use sync.
633 """
634 comb, sync = m.d.comb, m.d.sync
635 fus = self.fus.fus
636 regs = self.regs
637 # dictionary of lists of regfile write ports
638 byregfiles_wr, byregfiles_wrspec = self.get_byregfiles(False)
639
640 # same for write ports.
641 # BLECH! complex code-duplication! BLECH!
642 wrpickers = {}
643 for regfile, spec in byregfiles_wr.items():
644 fuspecs = byregfiles_wrspec[regfile]
645 wrpickers[regfile] = {}
646
647 if self.regreduce_en:
648 # argh, more port-merging
649 if regfile == 'INT':
650 fuspecs['o'] = [fuspecs.pop('o')]
651 fuspecs['o'].append(fuspecs.pop('o1'))
652 if regfile == 'FAST':
653 fuspecs['fast1'] = [fuspecs.pop('fast1')]
654 if 'fast2' in fuspecs:
655 fuspecs['fast1'].append(fuspecs.pop('fast2'))
656 if 'fast3' in fuspecs:
657 fuspecs['fast1'].append(fuspecs.pop('fast3'))
658
659 for (regname, fspec) in sort_fuspecs(fuspecs):
660 self.connect_wrport(m, fu_bitdict, wrpickers,
661 regfile, regname, fspec)
662
663 def get_byregfiles(self, readmode):
664
665 mode = "read" if readmode else "write"
666 regs = self.regs
667 fus = self.fus.fus
668 e = self.i.e # decoded instruction to execute
669
670 # dictionary of lists of regfile ports
671 byregfiles = {}
672 byregfiles_spec = {}
673 for (funame, fu) in fus.items():
674 print("%s ports for %s" % (mode, funame))
675 for idx in range(fu.n_src if readmode else fu.n_dst):
676 if readmode:
677 (regfile, regname, wid) = fu.get_in_spec(idx)
678 else:
679 (regfile, regname, wid) = fu.get_out_spec(idx)
680 print(" %d %s %s %s" % (idx, regfile, regname, str(wid)))
681 if readmode:
682 rdflag, read = regspec_decode_read(e, regfile, regname)
683 write = None
684 else:
685 rdflag, read = None, None
686 wrport, write = regspec_decode_write(e, regfile, regname)
687 if regfile not in byregfiles:
688 byregfiles[regfile] = {}
689 byregfiles_spec[regfile] = {}
690 if regname not in byregfiles_spec[regfile]:
691 byregfiles_spec[regfile][regname] = \
692 (rdflag, read, write, wid, [])
693 # here we start to create "lanes"
694 if idx not in byregfiles[regfile]:
695 byregfiles[regfile][idx] = []
696 fuspec = (funame, fu, idx)
697 byregfiles[regfile][idx].append(fuspec)
698 byregfiles_spec[regfile][regname][4].append(fuspec)
699
700 # ok just print that out, for convenience
701 for regfile, spec in byregfiles.items():
702 print("regfile %s ports:" % mode, regfile)
703 fuspecs = byregfiles_spec[regfile]
704 for regname, fspec in fuspecs.items():
705 [rdflag, read, write, wid, fuspec] = fspec
706 print(" rf %s port %s lane: %s" % (mode, regfile, regname))
707 print(" %s" % regname, wid, read, write, rdflag)
708 for (funame, fu, idx) in fuspec:
709 fusig = fu.src_i[idx] if readmode else fu.dest[idx]
710 print(" ", funame, fu, idx, fusig)
711 print()
712
713 return byregfiles, byregfiles_spec
714
715 def __iter__(self):
716 yield from self.fus.ports()
717 yield from self.i.e.ports()
718 yield from self.l0.ports()
719 # TODO: regs
720
721 def ports(self):
722 return list(self)
723
724
725 if __name__ == '__main__':
726 pspec = TestMemPspec(ldst_ifacetype='testpi',
727 imem_ifacetype='',
728 addr_wid=48,
729 mask_wid=8,
730 reg_wid=64)
731 dut = NonProductionCore(pspec)
732 vl = rtlil.convert(dut, ports=dut.ports())
733 with open("test_core.il", "w") as f:
734 f.write(vl)