1 """ Example 5: Making use of PyRTL and Introspection. """
3 from copy
import deepcopy
4 from migen
import Module
, Signal
5 from migen
.fhdl
import verilog
6 from migen
.fhdl
.bitcontainer
import value_bits_sign
9 # The following example shows how pyrtl can be used to make some interesting
10 # hardware structures using python introspection. In particular, this example
11 # makes a N-stage pipeline structure. Any specific pipeline is then a derived
12 # class of SimplePipeline where methods with names starting with "stage" are
13 # stages, and new members with names not starting with "_" are to be registered
16 class SimplePipeline(object):
17 """ Pipeline builder with auto generation of pipeline registers. """
19 def __init__(self
, pipe
):
21 self
._pipeline
_register
_map
= {}
22 self
._current
_stage
_num
= 0
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
)
32 self
._current
_stage
_num
+= 1
34 def __getattr__(self
, name
):
36 return self
._pipeline
_register
_map
[self
._current
_stage
_num
][name
]
39 'error, no pipeline register "%s" defined for stage %d'
40 % (name
, self
._current
_stage
_num
))
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
)
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_override
=rname
)
51 if next_stage
not in self
._pipeline
_register
_map
:
52 self
._pipeline
_register
_map
[next_stage
] = {}
53 self
._pipeline
_register
_map
[next_stage
][name
] = new_pipereg
54 self
._pipe
.sync
+= new_pipereg
.eq(value
)
57 class SimplePipelineExample(SimplePipeline
):
58 """ A very simple pipeline to show how registers are inferred. """
60 def __init__(self
, pipe
):
61 super(SimplePipelineExample
, self
).__init
__(pipe
)
62 self
._loopback
= Signal(4)
66 self
.n
= ~self
._loopback
78 self
._pipe
.sync
+= self
._loopback
.eq(self
.n
+ 3)
80 class PipeModule(Module
):
84 if __name__
== "__main__":
85 example
= PipeModule()
86 pipe
= SimplePipelineExample(example
)
87 print(verilog
.convert(example
,