use singlepipe.eq function
[ieee754fpu.git] / src / add / pipeline.py
1 """ Example 5: Making use of PyRTL and Introspection. """
2
3 from nmigen import Signal
4 from nmigen.compat.fhdl.bitcontainer import value_bits_sign
5
6 # The following example shows how pyrtl can be used to make some interesting
7 # hardware structures using python introspection. In particular, this example
8 # makes a N-stage pipeline structure. Any specific pipeline is then a derived
9 # class of SimplePipeline where methods with names starting with "stage" are
10 # stages, and new members with names not starting with "_" are to be registered
11 # for the next stage.
12
13 from singlepipe import eq
14
15 class SimplePipeline(object):
16 """ Pipeline builder with auto generation of pipeline registers.
17 """
18
19 def __init__(self, pipe):
20 self._pipe = pipe
21 self._pipeline_register_map = {}
22 self._current_stage_num = 0
23
24 def _setup(self):
25 stage_list = []
26 for method in dir(self):
27 if method.startswith('stage'):
28 stage_list.append(method)
29 for stage in sorted(stage_list):
30 stage_method = getattr(self, stage)
31 stage_method()
32 self._current_stage_num += 1
33
34 def __getattr__(self, name):
35 try:
36 return self._pipeline_register_map[self._current_stage_num][name]
37 except KeyError:
38 raise AttributeError(
39 'error, no pipeline register "%s" defined for stage %d'
40 % (name, self._current_stage_num))
41
42 def __setattr__(self, name, value):
43 if name.startswith('_'):
44 # do not do anything tricky with variables starting with '_'
45 object.__setattr__(self, name, value)
46 return
47 next_stage = self._current_stage_num + 1
48 pipereg_id = str(self._current_stage_num) + 'to' + str(next_stage)
49 rname = 'pipereg_' + pipereg_id + '_' + name
50 new_pipereg = Signal(value_bits_sign(value), name=rname,
51 reset_less=True)
52 if next_stage not in self._pipeline_register_map:
53 self._pipeline_register_map[next_stage] = {}
54 self._pipeline_register_map[next_stage][name] = new_pipereg
55 self._pipe.sync += eq(new_pipereg, value)
56