can`t stand list incomprehension
[rv32.git] / pipestage.py
1 """ Example 5: Making use of PyRTL and Introspection. """
2
3 from copy import deepcopy
4 from migen import *
5 from migen.fhdl import verilog
6
7
8 # The following example shows how pyrtl can be used to make some interesting
9 # hardware structures using python introspection. In particular, this example
10 # makes a N-stage pipeline structure. Any specific pipeline is then a derived
11 # class of SimplePipeline where methods with names starting with "stage" are
12 # stages, and new members with names not starting with "_" are to be registered
13 # for the next stage.
14
15 class SimplePipeline(object):
16 """ Pipeline builder with auto generation of pipeline registers. """
17
18 def __init__(self, pipe):
19 self._pipe = pipe
20 self._pipeline_register_map = {}
21 self._current_stage_num = 0
22
23 def _setup(self):
24 stage_list = []
25 for method in dir(self):
26 if method.startswith('stage'):
27 stage_list.append(method)
28 for stage in sorted(stage_list):
29 stage_method = getattr(self, stage)
30 stage_method()
31 self._current_stage_num += 1
32
33 def __getattr__(self, name):
34 try:
35 return self._pipeline_register_map[self._current_stage_num][name]
36 except KeyError:
37 raise AttributeError(
38 'error, no pipeline register "%s" defined for stage %d'
39 % (name, self._current_stage_num))
40
41 def __setattr__(self, name, value):
42 if name.startswith('_'):
43 # do not do anything tricky with variables starting with '_'
44 object.__setattr__(self, name, value)
45 else:
46 next_stage = self._current_stage_num + 1
47 pipereg_id = str(self._current_stage_num) + 'to' + str(next_stage)
48 rname = 'pipereg_' + pipereg_id + '_' + name
49 new_pipereg = Signal(len(value), name_override=rname)
50 if next_stage not in self._pipeline_register_map:
51 self._pipeline_register_map[next_stage] = {}
52 self._pipeline_register_map[next_stage][name] = new_pipereg
53 self._pipe.sync += new_pipereg.eq(value)
54
55
56 class SimplePipelineExample(SimplePipeline):
57 """ A very simple pipeline to show how registers are inferred. """
58
59 def __init__(self, pipe):
60 super(SimplePipelineExample, self).__init__(pipe)
61 self._loopback = Signal()
62 self._setup()
63
64 def stage0(self):
65 n = Signal()
66 self.n = ~self._loopback
67
68 def stage1(self):
69 self.n = self.n
70
71 def stage2(self):
72 self.n = self.n
73
74 def stage3(self):
75 self.n = self.n
76
77 def stage4(self):
78 self._pipe.sync += self._loopback.eq(self.n)
79
80 class PipeModule(Module):
81 def __init__(self):
82 Module.__init__(self)
83
84 if __name__ == "__main__":
85 example = PipeModule()
86 pipe = SimplePipelineExample(example)
87 print(verilog.convert(example,
88 {
89 pipe._loopback,
90 }))