use some namedtuples to make things clearer in core.py
[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 Const)
24 from nmigen.cli import rtlil
25
26 from openpower.decoder.power_decoder2 import PowerDecodeSubset
27 from openpower.decoder.power_regspec_map import regspec_decode_read
28 from openpower.decoder.power_regspec_map import regspec_decode_write
29 from openpower.sv.svp64 import SVP64Rec
30
31 from nmutil.picker import PriorityPicker
32 from nmutil.util import treereduce
33 from nmutil.singlepipe import ControlBase
34
35 from soc.fu.compunits.compunits import AllFunctionUnits, LDSTFunctionUnit
36 from soc.regfile.regfiles import RegFiles
37 from openpower.decoder.power_decoder2 import get_rdflags
38 from soc.experiment.l0_cache import TstL0CacheBuffer # test only
39 from soc.config.test.test_loadstore import TestMemPspec
40 from openpower.decoder.power_enums import MicrOp, Function
41 from soc.simple.core_data import CoreInput, CoreOutput
42
43 from collections import defaultdict, namedtuple
44 import operator
45
46 from nmutil.util import rising_edge
47
48 FUSpec = namedtuple("FUSpec", ["funame", "fu", "idx"])
49 ByRegSpec = namedtuple("ByRegSpec", ["rdflag", "wrport", "read",
50 "write", "wid", "specs"])
51
52 # helper function for reducing a list of signals down to a parallel
53 # ORed single signal.
54 def ortreereduce(tree, attr="o_data"):
55 return treereduce(tree, operator.or_, lambda x: getattr(x, attr))
56
57
58 def ortreereduce_sig(tree):
59 return treereduce(tree, operator.or_, lambda x: x)
60
61
62 # helper function to place full regs declarations first
63 def sort_fuspecs(fuspecs):
64 res = []
65 for (regname, fspec) in fuspecs.items():
66 if regname.startswith("full"):
67 res.append((regname, fspec))
68 for (regname, fspec) in fuspecs.items():
69 if not regname.startswith("full"):
70 res.append((regname, fspec))
71 return res # enumerate(res)
72
73
74 # derive from ControlBase rather than have a separate Stage instance,
75 # this is simpler to do
76 class NonProductionCore(ControlBase):
77 def __init__(self, pspec):
78 self.pspec = pspec
79
80 # test is SVP64 is to be enabled
81 self.svp64_en = hasattr(pspec, "svp64") and (pspec.svp64 == True)
82
83 # test to see if regfile ports should be reduced
84 self.regreduce_en = (hasattr(pspec, "regreduce") and
85 (pspec.regreduce == True))
86
87 # test to see if overlapping of instructions is allowed
88 # (not normally enabled for TestIssuer FSM but useful for checking
89 # the bitvector hazard detection, before doing In-Order)
90 self.allow_overlap = (hasattr(pspec, "allow_overlap") and
91 (pspec.allow_overlap == True))
92
93 # test core type
94 self.make_hazard_vecs = True
95 self.core_type = "fsm"
96 if hasattr(pspec, "core_type"):
97 self.core_type = pspec.core_type
98
99 super().__init__(stage=self)
100
101 # single LD/ST funnel for memory access
102 self.l0 = l0 = TstL0CacheBuffer(pspec, n_units=1)
103 pi = l0.l0.dports[0]
104
105 # function units (only one each)
106 # only include mmu if enabled in pspec
107 self.fus = AllFunctionUnits(pspec, pilist=[pi])
108
109 # link LoadStore1 into MMU
110 mmu = self.fus.get_fu('mmu0')
111 print ("core pspec", pspec.ldst_ifacetype)
112 print ("core mmu", mmu)
113 if mmu is not None:
114 print ("core lsmem.lsi", l0.cmpi.lsmem.lsi)
115 mmu.alu.set_ldst_interface(l0.cmpi.lsmem.lsi)
116
117 # register files (yes plural)
118 self.regs = RegFiles(pspec, make_hazard_vecs=self.make_hazard_vecs)
119
120 # set up input and output: unusual requirement to set data directly
121 # (due to the way that the core is set up in a different domain,
122 # see TestIssuer.setup_peripherals
123 self.p.i_data, self.n.o_data = self.new_specs(None)
124 self.i, self.o = self.p.i_data, self.n.o_data
125
126 # actual internal input data used (captured)
127 self.ireg = self.ispec()
128
129 # create per-FU instruction decoders (subsetted). these "satellite"
130 # decoders reduce wire fan-out from the one (main) PowerDecoder2
131 # (used directly by the trap unit) to the *twelve* (or more)
132 # Function Units. we can either have 32 wires (the instruction)
133 # to each, or we can have well over a 200 wire fan-out (to 12
134 # ALUs). it's an easy choice to make.
135 self.decoders = {}
136 self.des = {}
137
138 for funame, fu in self.fus.fus.items():
139 f_name = fu.fnunit.name
140 fnunit = fu.fnunit.value
141 opkls = fu.opsubsetkls
142 if f_name == 'TRAP':
143 # TRAP decoder is the *main* decoder
144 self.trapunit = funame
145 continue
146 self.decoders[funame] = PowerDecodeSubset(None, opkls, f_name,
147 final=True,
148 state=self.ireg.state,
149 svp64_en=self.svp64_en,
150 regreduce_en=self.regreduce_en)
151 self.des[funame] = self.decoders[funame].do
152
153 # share the SPR decoder with the MMU if it exists
154 if "mmu0" in self.decoders:
155 self.decoders["mmu0"].mmu0_spr_dec = self.decoders["spr0"]
156
157 # next 3 functions are Stage API Compliance
158 def setup(self, m, i):
159 pass
160
161 def ispec(self):
162 return CoreInput(self.pspec, self.svp64_en, self.regreduce_en)
163
164 def ospec(self):
165 return CoreOutput()
166
167 # elaborate function to create HDL
168 def elaborate(self, platform):
169 m = super().elaborate(platform)
170
171 # for testing purposes, to cut down on build time in coriolis2
172 if hasattr(self.pspec, "nocore") and self.pspec.nocore == True:
173 x = Signal() # dummy signal
174 m.d.sync += x.eq(~x)
175 return m
176 comb = m.d.comb
177
178 m.submodules.fus = self.fus
179 m.submodules.l0 = l0 = self.l0
180 self.regs.elaborate_into(m, platform)
181 regs = self.regs
182 fus = self.fus.fus
183
184 # connect decoders
185 self.connect_satellite_decoders(m)
186
187 # ssh, cheat: trap uses the main decoder because of the rewriting
188 self.des[self.trapunit] = self.ireg.e.do
189
190 # connect up Function Units, then read/write ports, and hazard conflict
191 self.issue_conflict = Signal()
192 fu_bitdict, fu_selected = self.connect_instruction(m)
193 raw_hazard = self.connect_rdports(m, fu_bitdict, fu_selected)
194 self.connect_wrports(m, fu_bitdict, fu_selected)
195 if self.allow_overlap:
196 comb += self.issue_conflict.eq(raw_hazard)
197
198 # note if an exception happened. in a pipelined or OoO design
199 # this needs to be accompanied by "shadowing" (or stalling)
200 el = []
201 for exc in self.fus.excs.values():
202 el.append(exc.happened)
203 if len(el) > 0: # at least one exception
204 comb += self.o.exc_happened.eq(Cat(*el).bool())
205
206 return m
207
208 def connect_satellite_decoders(self, m):
209 comb = m.d.comb
210 for k, v in self.decoders.items():
211 # connect each satellite decoder and give it the instruction.
212 # as subset decoders this massively reduces wire fanout given
213 # the large number of ALUs
214 setattr(m.submodules, "dec_%s" % v.fn_name, v)
215 comb += v.dec.raw_opcode_in.eq(self.ireg.raw_insn_i)
216 comb += v.dec.bigendian.eq(self.ireg.bigendian_i)
217 # sigh due to SVP64 RA_OR_ZERO detection connect these too
218 comb += v.sv_a_nz.eq(self.ireg.sv_a_nz)
219 if self.svp64_en:
220 comb += v.pred_sm.eq(self.ireg.sv_pred_sm)
221 comb += v.pred_dm.eq(self.ireg.sv_pred_dm)
222 if k != self.trapunit:
223 comb += v.sv_rm.eq(self.ireg.sv_rm) # pass through SVP64 RM
224 comb += v.is_svp64_mode.eq(self.ireg.is_svp64_mode)
225 # only the LDST PowerDecodeSubset *actually* needs to
226 # know to use the alternative decoder. this is all
227 # a terrible hack
228 if k.lower().startswith("ldst"):
229 comb += v.use_svp64_ldst_dec.eq(
230 self.ireg.use_svp64_ldst_dec)
231
232 def connect_instruction(self, m):
233 """connect_instruction
234
235 uses decoded (from PowerOp) function unit information from CSV files
236 to ascertain which Function Unit should deal with the current
237 instruction.
238
239 some (such as OP_ATTN, OP_NOP) are dealt with here, including
240 ignoring it and halting the processor. OP_NOP is a bit annoying
241 because the issuer expects busy flag still to be raised then lowered.
242 (this requires a fake counter to be set).
243 """
244 comb, sync = m.d.comb, m.d.sync
245 fus = self.fus.fus
246
247 # indicate if core is busy
248 busy_o = self.o.busy_o
249 any_busy_o = self.o.any_busy_o
250
251 # connect up temporary copy of incoming instruction. the FSM will
252 # either blat the incoming instruction (if valid) into self.ireg
253 # or if the instruction could not be delivered, keep dropping the
254 # latched copy into ireg
255 ilatch = self.ispec()
256 self.instr_active = Signal()
257
258 # enable/busy-signals for each FU, get one bit for each FU (by name)
259 fu_enable = Signal(len(fus), reset_less=True)
260 fu_busy = Signal(len(fus), reset_less=True)
261 fu_bitdict = {}
262 fu_selected = {}
263 for i, funame in enumerate(fus.keys()):
264 fu_bitdict[funame] = fu_enable[i]
265 fu_selected[funame] = fu_busy[i]
266
267 # identify function units and create a list by fnunit so that
268 # PriorityPickers can be created for selecting one of them that
269 # isn't busy at the time the incoming instruction needs passing on
270 by_fnunit = defaultdict(list)
271 for fname, member in Function.__members__.items():
272 for funame, fu in fus.items():
273 fnunit = fu.fnunit.value
274 if member.value & fnunit: # this FU handles this type of op
275 by_fnunit[fname].append((funame, fu)) # add by Function
276
277 # ok now just print out the list of FUs by Function, because we can
278 for fname, fu_list in by_fnunit.items():
279 print ("FUs by type", fname, fu_list)
280
281 # now create a PriorityPicker per FU-type such that only one
282 # non-busy FU will be picked
283 issue_pps = {}
284 fu_found = Signal() # take a note if no Function Unit was available
285 for fname, fu_list in by_fnunit.items():
286 i_pp = PriorityPicker(len(fu_list))
287 m.submodules['i_pp_%s' % fname] = i_pp
288 i_l = []
289 for i, (funame, fu) in enumerate(fu_list):
290 # match the decoded instruction (e.do.fn_unit) against the
291 # "capability" of this FU, gate that by whether that FU is
292 # busy, and drop that into the PriorityPicker.
293 # this will give us an output of the first available *non-busy*
294 # Function Unit (Reservation Statio) capable of handling this
295 # instruction.
296 fnunit = fu.fnunit.value
297 en_req = Signal(name="issue_en_%s" % funame, reset_less=True)
298 fnmatch = (self.ireg.e.do.fn_unit & fnunit).bool()
299 comb += en_req.eq(fnmatch & ~fu.busy_o &
300 self.instr_active)
301 i_l.append(en_req) # store in list for doing the Cat-trick
302 # picker output, gated by enable: store in fu_bitdict
303 po = Signal(name="o_issue_pick_"+funame) # picker output
304 comb += po.eq(i_pp.o[i] & i_pp.en_o)
305 comb += fu_bitdict[funame].eq(po)
306 comb += fu_selected[funame].eq(fu.busy_o | po)
307 # if we don't do this, then when there are no FUs available,
308 # the "p.o_ready" signal will go back "ok we accepted this
309 # instruction" which of course isn't true.
310 with m.If(i_pp.en_o):
311 comb += fu_found.eq(1)
312 # for each input, Cat them together and drop them into the picker
313 comb += i_pp.i.eq(Cat(*i_l))
314
315 # rdmask, which is for registers needs to come from the *main* decoder
316 for funame, fu in fus.items():
317 rdmask = get_rdflags(self.ireg.e, fu)
318 comb += fu.rdmaskn.eq(~rdmask)
319
320 # sigh - need a NOP counter
321 counter = Signal(2)
322 with m.If(counter != 0):
323 sync += counter.eq(counter - 1)
324 comb += busy_o.eq(1)
325
326 # default to reading from incoming instruction: may be overridden
327 # by copy from latch when "waiting"
328 comb += self.ireg.eq(self.i)
329 # always say "ready" except if overridden
330 comb += self.p.o_ready.eq(1)
331
332 with m.FSM():
333 with m.State("READY"):
334 with m.If(self.p.i_valid): # run only when valid
335 with m.Switch(self.ireg.e.do.insn_type):
336 # check for ATTN: halt if true
337 with m.Case(MicrOp.OP_ATTN):
338 m.d.sync += self.o.core_terminate_o.eq(1)
339
340 # fake NOP - this isn't really used (Issuer detects NOP)
341 with m.Case(MicrOp.OP_NOP):
342 sync += counter.eq(2)
343 comb += busy_o.eq(1)
344
345 with m.Default():
346 comb += self.instr_active.eq(1)
347 comb += self.p.o_ready.eq(0)
348 # connect instructions. only one enabled at a time
349 for funame, fu in fus.items():
350 do = self.des[funame]
351 enable = fu_bitdict[funame]
352
353 # run this FunctionUnit if enabled route op,
354 # issue, busy, read flags and mask to FU
355 with m.If(enable):
356 # operand comes from the *local* decoder
357 comb += fu.oper_i.eq_from(do)
358 comb += fu.issue_i.eq(1) # issue when valid
359 # instruction ok, indicate ready
360 comb += self.p.o_ready.eq(1)
361
362 if self.allow_overlap:
363 with m.If(~fu_found):
364 # latch copy of instruction
365 sync += ilatch.eq(self.i)
366 comb += self.p.o_ready.eq(1) # accept
367 comb += busy_o.eq(1)
368 m.next = "WAITING"
369
370 with m.State("WAITING"):
371 comb += self.instr_active.eq(1)
372 comb += self.p.o_ready.eq(0)
373 comb += busy_o.eq(1)
374 # using copy of instruction, keep waiting until an FU is free
375 comb += self.ireg.eq(ilatch)
376 with m.If(fu_found): # wait for conflict to clear
377 # connect instructions. only one enabled at a time
378 for funame, fu in fus.items():
379 do = self.des[funame]
380 enable = fu_bitdict[funame]
381
382 # run this FunctionUnit if enabled route op,
383 # issue, busy, read flags and mask to FU
384 with m.If(enable):
385 # operand comes from the *local* decoder
386 comb += fu.oper_i.eq_from(do)
387 comb += fu.issue_i.eq(1) # issue when valid
388 comb += self.p.o_ready.eq(1)
389 comb += busy_o.eq(0)
390 m.next = "READY"
391
392 print ("core: overlap allowed", self.allow_overlap)
393 busys = map(lambda fu: fu.busy_o, fus.values())
394 comb += any_busy_o.eq(Cat(*busys).bool())
395 if not self.allow_overlap:
396 # for simple non-overlap, if any instruction is busy, set
397 # busy output for core.
398 comb += busy_o.eq(any_busy_o)
399 else:
400 # sigh deal with a fun situation that needs to be investigated
401 # and resolved
402 with m.If(self.issue_conflict):
403 comb += busy_o.eq(1)
404
405 # return both the function unit "enable" dict as well as the "busy".
406 # the "busy-or-issued" can be passed in to the Read/Write port
407 # connecters to give them permission to request access to regfiles
408 return fu_bitdict, fu_selected
409
410 def connect_rdport(self, m, fu_bitdict, fu_selected,
411 rdpickers, regfile, regname, fspec):
412 comb, sync = m.d.comb, m.d.sync
413 fus = self.fus.fus
414 regs = self.regs
415
416 rpidx = regname
417
418 # select the required read port. these are pre-defined sizes
419 rfile = regs.rf[regfile.lower()]
420 rport = rfile.r_ports[rpidx]
421 print("read regfile", rpidx, regfile, regs.rf.keys(),
422 rfile, rfile.unary)
423
424 # for checking if the read port has an outstanding write
425 if self.make_hazard_vecs:
426 wv = regs.wv[regfile.lower()]
427 wvchk = wv.r_ports["issue"] # write-vec bit-level hazard check
428
429 # if a hazard is detected on this read port, simply blithely block
430 # every FU from reading on it. this is complete overkill but very
431 # simple for now.
432 hazard_detected = Signal(name="raw_%s_%s" % (regfile, rpidx))
433
434 fspecs = fspec
435 if not isinstance(fspecs, list):
436 fspecs = [fspecs]
437
438 rdflags = []
439 pplen = 0
440 ppoffs = []
441 for i, fspec in enumerate(fspecs):
442 # get the regfile specs for this regfile port
443 (rf, wf, read, write, wid, fuspec) = fspec
444 print ("fpsec", i, fspec, len(fuspec))
445 ppoffs.append(pplen) # record offset for picker
446 pplen += len(fuspec)
447 name = "rdflag_%s_%s_%d" % (regfile, regname, i)
448 rdflag = Signal(name=name, reset_less=True)
449 comb += rdflag.eq(rf)
450 rdflags.append(rdflag)
451
452 print ("pplen", pplen)
453
454 # create a priority picker to manage this port
455 rdpickers[regfile][rpidx] = rdpick = PriorityPicker(pplen)
456 setattr(m.submodules, "rdpick_%s_%s" % (regfile, rpidx), rdpick)
457
458 rens = []
459 addrs = []
460 wvens = []
461
462 for i, fspec in enumerate(fspecs):
463 (rf, wf, _read, _write, wid, fuspec) = fspec
464 # connect up the FU req/go signals, and the reg-read to the FU
465 # and create a Read Broadcast Bus
466 for pi, (funame, fu, idx) in enumerate(fuspec):
467 pi += ppoffs[i]
468 name = "%s_%s_%s_%i" % (regfile, rpidx, funame, pi)
469 fu_active = fu_selected[funame]
470 fu_issued = fu_bitdict[funame]
471
472 # get (or set up) a latched copy of read register number
473 rname = "%s_%s_%s_%d" % (funame, regfile, regname, pi)
474 read = Signal.like(_read, name="read_"+name)
475 if rname not in fu.rd_latches:
476 rdl = Signal.like(_read, name="rdlatch_"+rname)
477 fu.rd_latches[rname] = rdl
478 with m.If(fu.issue_i):
479 sync += rdl.eq(_read)
480 else:
481 rdl = fu.rd_latches[rname]
482 # latch to make the read immediately available on issue cycle
483 # after the read cycle, use the latched copy
484 with m.If(fu.issue_i):
485 comb += read.eq(_read)
486 with m.Else():
487 comb += read.eq(rdl)
488
489 # connect request-read to picker input, and output to go-rd
490 addr_en = Signal.like(read, name="addr_en_"+name)
491 pick = Signal(name="pick_"+name) # picker input
492 rp = Signal(name="rp_"+name) # picker output
493 delay_pick = Signal(name="dp_"+name) # read-enable "underway"
494 rhazard = Signal(name="rhaz_"+name)
495
496 # exclude any currently-enabled read-request (mask out active)
497 comb += pick.eq(fu.rd_rel_o[idx] & fu_active & rdflags[i] &
498 ~delay_pick & ~rhazard)
499 # entirely block anything hazarded from being picked
500 comb += rdpick.i[pi].eq(pick)
501 comb += fu.go_rd_i[idx].eq(delay_pick) # pass in *delayed* pick
502
503 # if picked, select read-port "reg select" number to port
504 comb += rp.eq(rdpick.o[pi] & rdpick.en_o)
505 sync += delay_pick.eq(rp) # delayed "pick"
506 comb += addr_en.eq(Mux(rp, read, 0))
507
508 # the read-enable happens combinatorially (see mux-bus below)
509 # but it results in the data coming out on a one-cycle delay.
510 if rfile.unary:
511 rens.append(addr_en)
512 else:
513 addrs.append(addr_en)
514 rens.append(rp)
515
516 # use the *delayed* pick signal to put requested data onto bus
517 with m.If(delay_pick):
518 # connect regfile port to input, creating fan-out Bus
519 src = fu.src_i[idx]
520 print("reg connect widths",
521 regfile, regname, pi, funame,
522 src.shape(), rport.o_data.shape())
523 # all FUs connect to same port
524 comb += src.eq(rport.o_data)
525
526 if not self.make_hazard_vecs:
527 continue
528
529 # read the write-hazard bitvector (wv) for any bit that is
530 wvchk_en = Signal(len(wvchk.ren), name="wv_chk_addr_en_"+name)
531 issue_active = Signal(name="rd_iactive_"+name)
532 # XXX combinatorial loop here
533 comb += issue_active.eq(fu_active & rf)
534 with m.If(issue_active):
535 if rfile.unary:
536 comb += wvchk_en.eq(read)
537 else:
538 comb += wvchk_en.eq(1<<read)
539 # if FU is busy (which doesn't get set at the same time as
540 # issue) and no hazard was detected, clear wvchk_en (i.e.
541 # stop checking for hazards)
542 with m.If(fu.busy_o & ~rhazard):
543 comb += wvchk_en.eq(0)
544
545 comb += rhazard.eq((wvchk.o_data & wvchk_en).bool())
546
547 wvens.append(wvchk_en)
548
549 # or-reduce the muxed read signals
550 if rfile.unary:
551 # for unary-addressed
552 comb += rport.ren.eq(ortreereduce_sig(rens))
553 else:
554 # for binary-addressed
555 comb += rport.addr.eq(ortreereduce_sig(addrs))
556 comb += rport.ren.eq(Cat(*rens).bool())
557 print ("binary", regfile, rpidx, rport, rport.ren, rens, addrs)
558
559 if not self.make_hazard_vecs:
560 return Const(0) # declare "no hazards"
561
562 # enable the read bitvectors for this issued instruction
563 # and return whether any write-hazard bit is set
564 comb += wvchk.ren.eq(ortreereduce_sig(wvens))
565 comb += hazard_detected.eq(wvchk.o_data.bool())
566 return hazard_detected
567
568 def connect_rdports(self, m, fu_bitdict, fu_selected):
569 """connect read ports
570
571 orders the read regspecs into a dict-of-dicts, by regfile, by
572 regport name, then connects all FUs that want that regport by
573 way of a PriorityPicker.
574 """
575 comb, sync = m.d.comb, m.d.sync
576 fus = self.fus.fus
577 regs = self.regs
578 rd_hazard = []
579
580 # dictionary of lists of regfile read ports
581 byregfiles_rd, byregfiles_rdspec = self.get_byregfiles(True)
582
583 # okaay, now we need a PriorityPicker per regfile per regfile port
584 # loootta pickers... peter piper picked a pack of pickled peppers...
585 rdpickers = {}
586 for regfile, spec in byregfiles_rd.items():
587 fuspecs = byregfiles_rdspec[regfile]
588 rdpickers[regfile] = {}
589
590 # argh. an experiment to merge RA and RB in the INT regfile
591 # (we have too many read/write ports)
592 if self.regreduce_en:
593 if regfile == 'INT':
594 fuspecs['rabc'] = [fuspecs.pop('rb')]
595 fuspecs['rabc'].append(fuspecs.pop('rc'))
596 fuspecs['rabc'].append(fuspecs.pop('ra'))
597 if regfile == 'FAST':
598 fuspecs['fast1'] = [fuspecs.pop('fast1')]
599 if 'fast2' in fuspecs:
600 fuspecs['fast1'].append(fuspecs.pop('fast2'))
601 if 'fast3' in fuspecs:
602 fuspecs['fast1'].append(fuspecs.pop('fast3'))
603
604 # for each named regfile port, connect up all FUs to that port
605 # also return (and collate) hazard detection)
606 for (regname, fspec) in sort_fuspecs(fuspecs):
607 print("connect rd", regname, fspec)
608 rh = self.connect_rdport(m, fu_bitdict, fu_selected,
609 rdpickers, regfile,
610 regname, fspec)
611 rd_hazard.append(rh)
612
613 return Cat(*rd_hazard).bool()
614
615 def make_hazards(self, m, regfile, rfile, wvclr, wvset,
616 funame, regname, idx,
617 addr_en, wp, fu, fu_active, wrflag, write,
618 fu_wrok):
619 """make_hazards: a setter and a clearer for the regfile write ports
620
621 setter is at issue time (using PowerDecoder2 regfile write numbers)
622 clearer is at regfile write time (when FU has said what to write to)
623
624 there is *one* unusual case here which has to be dealt with:
625 when the Function Unit does *NOT* request a write to the regfile
626 (has its data.ok bit CLEARED). this is perfectly legitimate.
627 and a royal pain.
628 """
629 comb, sync = m.d.comb, m.d.sync
630 name = "%s_%s_%d" % (funame, regname, idx)
631
632 # connect up the bitvector write hazard. unlike the
633 # regfile writeports, a ONE must be written to the corresponding
634 # bit of the hazard bitvector (to indicate the existence of
635 # the hazard)
636
637 # the detection of what shall be written to is based
638 # on *issue*
639 print ("write vector (for regread)", regfile, wvset)
640 wviaddr_en = Signal(len(wvset.wen), name="wv_issue_addr_en_"+name)
641 issue_active = Signal(name="iactive_"+name)
642 comb += issue_active.eq(fu.issue_i & fu_active & wrflag)
643 with m.If(issue_active):
644 if rfile.unary:
645 comb += wviaddr_en.eq(write)
646 else:
647 comb += wviaddr_en.eq(1<<write)
648
649 # deal with write vector clear: this kicks in when the regfile
650 # is written to, and clears the corresponding bitvector entry
651 print ("write vector", regfile, wvclr)
652 wvaddr_en = Signal(len(wvclr.wen), name="wvaddr_en_"+name)
653 if rfile.unary:
654 comb += wvaddr_en.eq(addr_en)
655 else:
656 with m.If(wp):
657 comb += wvaddr_en.eq(1<<addr_en)
658
659 # XXX ASSUME that LDSTFunctionUnit always sets the data it intends to
660 # this may NOT be the case when an exception occurs
661 if isinstance(fu, LDSTFunctionUnit):
662 return wvaddr_en, wviaddr_en
663
664 # okaaay, this is preparation for the awkward case.
665 # * latch a copy of wrflag when issue goes high.
666 # * when the fu_wrok (data.ok) flag is NOT set,
667 # but the FU is done, the FU is NEVER going to write
668 # so the bitvector has to be cleared.
669 latch_wrflag = Signal(name="latch_wrflag_"+name)
670 with m.If(~fu.busy_o):
671 sync += latch_wrflag.eq(0)
672 with m.If(fu.issue_i & fu_active):
673 sync += latch_wrflag.eq(wrflag)
674 with m.If(fu.alu_done_o & latch_wrflag & ~fu_wrok):
675 if rfile.unary:
676 comb += wvaddr_en.eq(write) # addr_en gated with wp, don't use
677 else:
678 comb += wvaddr_en.eq(1<<addr_en) # binary addr_en not gated
679
680 return wvaddr_en, wviaddr_en
681
682 def connect_wrport(self, m, fu_bitdict, fu_selected,
683 wrpickers, regfile, regname, fspec):
684 comb, sync = m.d.comb, m.d.sync
685 fus = self.fus.fus
686 regs = self.regs
687
688 rpidx = regname
689
690 # select the required write port. these are pre-defined sizes
691 rfile = regs.rf[regfile.lower()]
692 wport = rfile.w_ports[rpidx]
693
694 print("connect wr", regname, "unary", rfile.unary, fspec)
695 print(regfile, regs.rf.keys())
696
697 # select the write-protection hazard vector. note that this still
698 # requires to WRITE to the hazard bitvector! read-requests need
699 # to RAISE the bitvector (set it to 1), which, duh, requires a WRITE
700 if self.make_hazard_vecs:
701 wv = regs.wv[regfile.lower()]
702 wvset = wv.w_ports["set"] # write-vec bit-level hazard ctrl
703 wvclr = wv.w_ports["clr"] # write-vec bit-level hazard ctrl
704
705 fspecs = fspec
706 if not isinstance(fspecs, list):
707 fspecs = [fspecs]
708
709 pplen = 0
710 writes = []
711 ppoffs = []
712 rdflags = []
713 wrflags = []
714 for i, fspec in enumerate(fspecs):
715 # get the regfile specs for this regfile port
716 (rf, wf, read, write, wid, fuspec) = fspec
717 print ("fpsec", i, "wrflag", wf, fspec, len(fuspec))
718 ppoffs.append(pplen) # record offset for picker
719 pplen += len(fuspec)
720
721 name = "%s_%s_%d" % (regfile, regname, i)
722 rdflag = Signal(name="rd_flag_"+name)
723 wrflag = Signal(name="wr_flag_"+name)
724 if rf is not None:
725 comb += rdflag.eq(rf)
726 else:
727 comb += rdflag.eq(0)
728 if wf is not None:
729 comb += wrflag.eq(wf)
730 else:
731 comb += wrflag.eq(0)
732 rdflags.append(rdflag)
733 wrflags.append(wrflag)
734
735 # create a priority picker to manage this port
736 wrpickers[regfile][rpidx] = wrpick = PriorityPicker(pplen)
737 setattr(m.submodules, "wrpick_%s_%s" % (regfile, rpidx), wrpick)
738
739 wsigs = []
740 wens = []
741 wvsets = []
742 wvseten = []
743 wvclren = []
744 addrs = []
745 for i, fspec in enumerate(fspecs):
746 # connect up the FU req/go signals and the reg-read to the FU
747 # these are arbitrated by Data.ok signals
748 (rf, wf, read, _write, wid, fuspec) = fspec
749 for pi, (funame, fu, idx) in enumerate(fuspec):
750 pi += ppoffs[i]
751 name = "%s_%s_%s_%d" % (funame, regfile, regname, idx)
752 # get (or set up) a write-latched copy of write register number
753 write = Signal.like(_write, name="write_"+name)
754 rname = "%s_%s_%s" % (funame, regfile, regname)
755 if rname not in fu.wr_latches:
756 wrl = Signal.like(_write, name="wrlatch_"+rname)
757 fu.wr_latches[rname] = write
758 with m.If(fu.issue_i):
759 sync += wrl.eq(_write)
760 comb += write.eq(_write)
761 with m.Else():
762 comb += write.eq(wrl)
763 else:
764 write = fu.wr_latches[rname]
765
766 # write-request comes from dest.ok
767 dest = fu.get_out(idx)
768 fu_dest_latch = fu.get_fu_out(idx) # latched output
769 name = "fu_wrok_%s_%s_%d" % (funame, regname, idx)
770 fu_wrok = Signal(name=name, reset_less=True)
771 comb += fu_wrok.eq(dest.ok & fu.busy_o)
772
773 # connect request-write to picker input, and output to go-wr
774 fu_active = fu_selected[funame]
775 pick = fu.wr.rel_o[idx] & fu_active
776 comb += wrpick.i[pi].eq(pick)
777 # create a single-pulse go write from the picker output
778 wr_pick = Signal(name="wpick_%s_%s_%d" % (funame, regname, idx))
779 comb += wr_pick.eq(wrpick.o[pi] & wrpick.en_o)
780 comb += fu.go_wr_i[idx].eq(rising_edge(m, wr_pick))
781
782 # connect the regspec write "reg select" number to this port
783 # only if one FU actually requests (and is granted) the port
784 # will the write-enable be activated
785 wname = "waddr_en_%s_%s_%d" % (funame, regname, idx)
786 addr_en = Signal.like(write, name=wname)
787 wp = Signal()
788 comb += wp.eq(wr_pick & wrpick.en_o)
789 comb += addr_en.eq(Mux(wp, write, 0))
790 if rfile.unary:
791 wens.append(addr_en)
792 else:
793 addrs.append(addr_en)
794 wens.append(wp)
795
796 # connect regfile port to input
797 print("reg connect widths",
798 regfile, regname, pi, funame,
799 dest.shape(), wport.i_data.shape())
800 wsigs.append(fu_dest_latch)
801
802 # now connect up the bitvector write hazard
803 if not self.make_hazard_vecs:
804 continue
805 res = self.make_hazards(m, regfile, rfile, wvclr, wvset,
806 funame, regname, idx,
807 addr_en, wp, fu, fu_active,
808 wrflags[i], write, fu_wrok)
809 wvaddr_en, wv_issue_en = res
810 wvclren.append(wvaddr_en) # set only: no data => clear bit
811 wvseten.append(wv_issue_en) # set data same as enable
812 wvsets.append(wv_issue_en) # because enable needs a 1
813
814 # here is where we create the Write Broadcast Bus. simple, eh?
815 comb += wport.i_data.eq(ortreereduce_sig(wsigs))
816 if rfile.unary:
817 # for unary-addressed
818 comb += wport.wen.eq(ortreereduce_sig(wens))
819 else:
820 # for binary-addressed
821 comb += wport.addr.eq(ortreereduce_sig(addrs))
822 comb += wport.wen.eq(ortreereduce_sig(wens))
823
824 if not self.make_hazard_vecs:
825 return
826
827 # for write-vectors
828 comb += wvclr.wen.eq(ortreereduce_sig(wvclren)) # clear (regfile write)
829 comb += wvset.wen.eq(ortreereduce_sig(wvseten)) # set (issue time)
830 comb += wvset.i_data.eq(ortreereduce_sig(wvsets))
831
832 def connect_wrports(self, m, fu_bitdict, fu_selected):
833 """connect write ports
834
835 orders the write regspecs into a dict-of-dicts, by regfile,
836 by regport name, then connects all FUs that want that regport
837 by way of a PriorityPicker.
838
839 note that the write-port wen, write-port data, and go_wr_i all need to
840 be on the exact same clock cycle. as there is a combinatorial loop bug
841 at the moment, these all use sync.
842 """
843 comb, sync = m.d.comb, m.d.sync
844 fus = self.fus.fus
845 regs = self.regs
846 # dictionary of lists of regfile write ports
847 byregfiles_wr, byregfiles_wrspec = self.get_byregfiles(False)
848
849 # same for write ports.
850 # BLECH! complex code-duplication! BLECH!
851 wrpickers = {}
852 for regfile, spec in byregfiles_wr.items():
853 fuspecs = byregfiles_wrspec[regfile]
854 wrpickers[regfile] = {}
855
856 if self.regreduce_en:
857 # argh, more port-merging
858 if regfile == 'INT':
859 fuspecs['o'] = [fuspecs.pop('o')]
860 fuspecs['o'].append(fuspecs.pop('o1'))
861 if regfile == 'FAST':
862 fuspecs['fast1'] = [fuspecs.pop('fast1')]
863 if 'fast2' in fuspecs:
864 fuspecs['fast1'].append(fuspecs.pop('fast2'))
865 if 'fast3' in fuspecs:
866 fuspecs['fast1'].append(fuspecs.pop('fast3'))
867
868 for (regname, fspec) in sort_fuspecs(fuspecs):
869 self.connect_wrport(m, fu_bitdict, fu_selected, wrpickers,
870 regfile, regname, fspec)
871
872 def get_byregfiles(self, readmode):
873
874 mode = "read" if readmode else "write"
875 regs = self.regs
876 fus = self.fus.fus
877 e = self.ireg.e # decoded instruction to execute
878
879 # dictionary of dictionaries of lists/tuples of regfile ports.
880 # first key: regfile. second key: regfile port name
881 byregfiles = defaultdict(lambda: defaultdict(list))
882 byregfiles_spec = defaultdict(dict)
883
884 for (funame, fu) in fus.items():
885 # create in each FU a receptacle for the read/write register
886 # hazard numbers. to be latched in connect_rd/write_ports
887 # XXX better that this is moved into the actual FUs, but
888 # the issue there is that this function is actually better
889 # suited at the moment
890 if readmode:
891 fu.rd_latches = {}
892 else:
893 fu.wr_latches = {}
894
895 print("%s ports for %s" % (mode, funame))
896 for idx in range(fu.n_src if readmode else fu.n_dst):
897 # construct regfile specs: read uses inspec, write outspec
898 if readmode:
899 (regfile, regname, wid) = fu.get_in_spec(idx)
900 else:
901 (regfile, regname, wid) = fu.get_out_spec(idx)
902 print(" %d %s %s %s" % (idx, regfile, regname, str(wid)))
903
904 # the PowerDecoder2 (main one, not the satellites) contains
905 # the decoded regfile numbers. obtain these now
906 if readmode:
907 rdport, read = regspec_decode_read(e, regfile, regname)
908 wrport, write = None, None
909 else:
910 rdport, read = None, None
911 wrport, write = regspec_decode_write(e, regfile, regname)
912
913 # construct the dictionary of regspec information by regfile
914 if regname not in byregfiles_spec[regfile]:
915 byregfiles_spec[regfile][regname] = \
916 ByRegSpec(rdport, wrport, read, write, wid, [])
917 # here we start to create "lanes"
918 fuspec = FUSpec(funame, fu, idx)
919 byregfiles[regfile][idx].append(fuspec)
920 byregfiles_spec[regfile][regname].specs.append(fuspec)
921
922 continue
923 # append a latch Signal to the FU's list of latches
924 rname = "%s_%s" % (regfile, regname)
925 if readmode:
926 if rname not in fu.rd_latches:
927 rdl = Signal.like(read, name="rdlatch_"+rname)
928 fu.rd_latches[rname] = rdl
929 else:
930 if rname not in fu.wr_latches:
931 wrl = Signal.like(write, name="wrlatch_"+rname)
932 fu.wr_latches[rname] = wrl
933
934 # ok just print that all out, for convenience
935 for regfile, spec in byregfiles.items():
936 print("regfile %s ports:" % mode, regfile)
937 fuspecs = byregfiles_spec[regfile]
938 for regname, fspec in fuspecs.items():
939 [rdport, wrport, read, write, wid, fuspecs] = fspec
940 print(" rf %s port %s lane: %s" % (mode, regfile, regname))
941 print(" %s" % regname, wid, read, write, rdport, wrport)
942 for (funame, fu, idx) in fuspecs:
943 fusig = fu.src_i[idx] if readmode else fu.dest[idx]
944 print(" ", funame, fu.__class__.__name__, idx, fusig)
945 print()
946
947 return byregfiles, byregfiles_spec
948
949 def __iter__(self):
950 yield from self.fus.ports()
951 yield from self.i.e.ports()
952 yield from self.l0.ports()
953 # TODO: regs
954
955 def ports(self):
956 return list(self)
957
958
959 if __name__ == '__main__':
960 pspec = TestMemPspec(ldst_ifacetype='testpi',
961 imem_ifacetype='',
962 addr_wid=48,
963 mask_wid=8,
964 reg_wid=64)
965 dut = NonProductionCore(pspec)
966 vl = rtlil.convert(dut, ports=dut.ports())
967 with open("test_core.il", "w") as f:
968 f.write(vl)