1MIGEN(1)                             Migen                            MIGEN(1)
2
3
4

NAME

6       migen - Migen manual
7

INTRODUCTION

9       Migen  is  a Python-based tool that aims at automating further the VLSI
10       design process.
11
12       Migen makes it possible to apply modern software concepts such  as  ob‐
13       ject-oriented  programming and metaprogramming to design hardware. This
14       results in more elegant and easily maintained designs and  reduces  the
15       incidence of human errors.
16
17   Background
18       Even  though  the  Milkymist system-on-chip [mm] had many successes, it
19       suffers from several limitations stemming from  its  implementation  in
20       manually written Verilog HDL:
21
22       [mm] http://m-labs.hk
23
24       1. The  "event-driven"  paradigm  of today's dominant hardware descrip‐
25          tions languages (Verilog  and  VHDL,  collectively  referred  to  as
26          "V*HDL"  in the rest of this document) is often too general. Today's
27          FPGA architectures are optimized for  the  implementation  of  fully
28          synchronous  circuits.  This  means that the bulk of the code for an
29          efficient FPGA design falls into three categories:
30
31          1. Combinatorial statements
32
33          2. Synchronous statements
34
35          3. Initialization of registers at reset
36
37          V*HDL do not follow this organization. This  means  that  a  lot  of
38          repetitive  manual  coding  is needed, which brings sources of human
39          errors, petty issues, and confusion for beginners:
40
41          1. wire vs. reg in Verilog
42
43          2. forgetting to initialize a register at reset
44
45          3. deciding  whether  a  combinatorial  statement  must  go  into  a
46             process/always block or not
47
48          4. simulation mismatches with combinatorial processes/always blocks
49
50          5. and more...
51
52          A  little-known fact about FPGAs is that many of them have the abil‐
53          ity to initialize their registers from the bitstream contents.  This
54          can  be done in a portable and standard way using an "initial" block
55          in Verilog, and by affecting a value at the  signal  declaration  in
56          VHDL.  This renders an explicit reset signal unnecessary in practice
57          in some cases, which opens the way for further design  optimization.
58          However,  this  form of initialization is entirely not synthesizable
59          for ASIC targets, and it is not easy to switch between the two forms
60          of reset using V*HDL.
61
62       2. V*HDL  support for composite types is very limited. Signals having a
63          record type in VHDL are unidirectional, which makes them  clumsy  to
64          use  e.g. in bus interfaces. There is no record type support in Ver‐
65          ilog, which means that a lot of copy-and-paste has to be  done  when
66          forwarding grouped signals.
67
68       3. V*HDL support for procedurally generated logic is extremely limited.
69          The most advanced forms of procedural  generation  of  synthesizable
70          logic  that V*HDL offers are CPP-style directives in Verilog, combi‐
71          natorial functions, and generate statements. Nothing  really  fancy,
72          and it shows. To give a few examples:
73
74          1. Building  highly  flexible bus interconnect is not possible. Even
75             arbitrating any given number of bus masters for commonplace  pro‐
76             tocols  such  as  Wishbone is difficult with the tools that V*HDL
77             puts at our disposal.
78
79          2. Building a memory  infrastructure  (including  bus  interconnect,
80             bridges  and  caches) that can automatically adapt itself at com‐
81             pile-time to any word size of the SDRAM is clumsy and tedious.
82
83          3. Building register banks for control, status and interrupt manage‐
84             ment of cores can also largely benefit from automation.
85
86          4. Many  hardware  acceleration  problems  can fit into the dataflow
87             programming model. Manual dataflow implementation in  V*HDL  has,
88             again,  a  lot  of redundancy and potential for human errors. See
89             the Milkymist texture mapping unit [mthesis] [mxcell] for an  ex‐
90             ample  of  this.  The amount of detail to deal with manually also
91             makes the design space exploration difficult, and therefore  hin‐
92             ders the design of efficient architectures.
93
94          5. Pre-computation of values, such as filter coefficients for DSP or
95             even simply trigonometric tables, must often be done using exter‐
96             nal  tools  whose  results are copy-and-pasted (in the best case,
97             automatically) into the V*HDL source.
98
99       [mthesis]
100            http://m-labs.hk/thesis/thesis.pdf
101
102       [mxcell]
103            http://www.xilinx.com/publications/archives/xcell/Xcell77.pdf
104            p30-35
105
106            Enter  Migen,  a Python toolbox for building complex digital hard‐
107            ware. We could have designed a brand new programming language, but
108            that  would  have been reinventing the wheel instead of being able
109            to benefit from Python's rich features and  immense  library.  The
110            price  to pay is a slightly cluttered syntax at times when writing
111            descriptions in FHDL, but we believe this is  totally  acceptable,
112            particularly when compared to VHDL ;-)
113
114            Migen is made up of several related components:
115
116       1. the base language, FHDL
117
118       2. a library of small generic cores
119
120       3. a simulator
121
122       4. a build system
123
124   Installing Migen
125       Either run the setup.py installation script or simply set PYTHONPATH to
126       the root of the source directory.
127
128       If you wish to contribute patches, the suggest way to install is;
129
130              1. Clone      from       the       git       repository       at
131                 http://github.com/m-labs/migen
132
133              2. Install using python3 ./setup.py develop --user
134
135              3. Edit the code in your git checkout.
136
137   Alternative install methods
138          • Migen is available for the Anaconda Python distribution. The pack‐
139            age can be found at at https://anaconda.org/m-labs/migen
140
141          • Migen can be referenced in a requirements.txt file (used  for  pip
142            install         -r         requirements.txt)         via        -e
143            git+http://github.com/m-labs/migen.git#egg=migen. See the pip doc‐
144            umentation for more information.
145
146   Feedback
147       Feedback  concerning  Migen or this manual should be sent to the M-Labs
148       developers' mailing list devel on lists.m-labs.hk.
149

THE FHDL DOMAIN-SPECIFIC LANGUAGE

151       The Fragmented Hardware Description Language (FHDL) is the basis of Mi‐
152       gen. It consists of a formal system to describe signals, and combinato‐
153       rial and synchronous statements operating on them.  The  formal  system
154       itself  is  low level and close to the synthesizable subset of Verilog,
155       and we then rely on Python algorithms to build  complex  structures  by
156       combining  FHDL  elements.  The FHDL module also contains a back-end to
157       produce synthesizable Verilog, and some structure analysis and  manipu‐
158       lation functionality.
159
160       FHDL  differs from MyHDL [myhdl] in fundamental ways. MyHDL follows the
161       event-driven paradigm of traditional HDLs (see background)  while  FHDL
162       separates  the  code  into combinatorial statements, synchronous state‐
163       ments, and reset values. In MyHDL, the logic is described  directly  in
164       the  Python  AST.  The  converter  to Verilog or VHDL then examines the
165       Python AST and recognizes a subset of Python that  it  translates  into
166       V*HDL  statements.  This  seriously  impedes the capability of MyHDL to
167       generate logic procedurally. With FHDL, you  manipulate  a  custom  AST
168       from  Python, and you can more easily design algorithms that operate on
169       it.
170
171       [myhdl]
172            http://www.myhdl.org
173
174            FHDL is made of several elements, which are briefly explained  be‐
175            low. They all can be imported directly from the migen module.
176
177   Expressions
178   Constants
179       The  Constant object represents a constant, HDL-literal integer. It be‐
180       haves like specifying integers and booleans but also  supports  slicing
181       and  can  have a bit width or signedness different from what is implied
182       by the value it represents.
183
184       True and False are interpreted as 1 and 0, respectively.
185
186       Negative integers are explicitly supported. As  with  MyHDL  [countin],
187       arithmetic operations return the natural results.
188
189       To  lighten  the  syntax,  assignments and operators automatically wrap
190       Python integers and booleans into Constant. Additionally,  Constant  is
191       aliased to C. The following are valid Migen statements: a.eq(0), a.eq(a
192       + 1), a.eq(C(42)[0:1]).
193
194       [countin]
195            http://www.jandecaluwe.com/hdldesign/counting.html
196
197   Signal
198       The signal object represents a value that is expected to change in  the
199       circuit.  It  does  exactly  what Verilog's "wire" and "reg" and VHDL's
200       "signal" do.
201
202       The main point of the signal object is that it  is  identified  by  its
203       Python  ID  (as returned by the id() function), and nothing else. It is
204       the responsibility of the V*HDL back-end to establish an injective map‐
205       ping between Python IDs and the V*HDL namespace. It should perform name
206       mangling to ensure this. The consequence of this is that signal objects
207       can  safely become members of arbitrary Python classes, or be passed as
208       parameters to functions or methods that generate logic involving them.
209
210       The properties of a signal object are:
211
212       • An integer or a (integer, boolean) pair that defines  the  number  of
213         bits  and whether the bit of higher index of the signal is a sign bit
214         (i.e. the signal is signed). The defaults are one bit  and  unsigned.
215         Alternatively,  the min and max parameters can be specified to define
216         the range of the signal and determine its bit width  and  signedness.
217         As with Python ranges, min is inclusive and defaults to 0, max is ex‐
218         clusive and defaults to 2.
219
220       • A name, used as a hint for the V*HDL back-end name mangler.
221
222       • The signal's reset value. It must be an integer, and defaults  to  0.
223         When the signal's value is modified with a synchronous statement, the
224         reset value is the initialization value of the  associated  register.
225         When  the signal is assigned to in a conditional combinatorial state‐
226         ment (If or Case), the reset value is the value that the  signal  has
227         when  no  condition  that causes the signal to be driven is verified.
228         This enforces the absence of latches in designs.  If  the  signal  is
229         permanently  driven  using a combinatorial statement, the reset value
230         has no effect.
231
232       The sole purpose of the name property is to make  the  generated  V*HDL
233       code  easier to understand and debug. From a purely functional point of
234       view, it is perfectly OK to have several signals  with  the  same  name
235       property.  The back-end will generate a unique name for each object. If
236       no name property is specified, Migen will analyze the code that created
237       the  signal object, and try to extract the variable or member name from
238       there. For example, the following statements will create one or several
239       signals named "bar":
240
241          bar = Signal()
242          self.bar = Signal()
243          self.baz.bar = Signal()
244          bar = [Signal() for x in range(42)]
245
246       In  case  of  conflicts,  Migen tries first to resolve the situation by
247       prefixing the identifiers with names from the class and module  hierar‐
248       chy  that created them. If the conflict persists (which can be the case
249       if two signal objects are created with the same name in the  same  con‐
250       text), it will ultimately add number suffixes.
251
252   Operators
253       Operators  are  represented  by  the  _Operator object, which generally
254       should not be used directly. Instead, most FHDL  objects  overload  the
255       usual  Python  logic  and  arithmetic  operators,  which  allows a much
256       lighter syntax to be used. For example, the expression:
257
258          a * b + c
259
260       is equivalent to:
261
262          _Operator("+", [_Operator("*", [a, b]), c])
263
264   Slices
265       Likewise, slices are represented by  the  _Slice  object,  which  often
266       should  not  be  used in favor of the Python slice operation [x:y]. Im‐
267       plicit indices using the forms [x], [x:] and [:y]  are  supported.  Be‐
268       ware!  Slices work like Python slices, not like VHDL or Verilog slices.
269       The first bound is the index of the LSB and is  inclusive.  The  second
270       bound  is  the  index  of  MSB  and  is exclusive. In V*HDL, bounds are
271       MSB:LSB and both are inclusive.
272
273   Concatenations
274       Concatenations are done using  the  Cat  object.  To  make  the  syntax
275       lighter,  its  constructor  takes a variable number of arguments, which
276       are the signals to be concatenated together (you can use the Python "*"
277       operator  to  pass  a list instead).  To be consistent with slices, the
278       first signal is connected to the bits with the lowest  indices  in  the
279       result.  This  is  the  opposite of the way the "{}" construct works in
280       Verilog.
281
282   Replications
283       The Replicate object represents the equivalent  of  {count{expression}}
284       in Verilog.  For example, the expression:
285
286          Replicate(0, 4)
287
288       is equivalent to:
289
290          Cat(0, 0, 0, 0)
291
292   Statements
293   Assignment
294       Assignments are represented with the _Assign object. Since using it di‐
295       rectly would result in a cluttered syntax, the preferred technique  for
296       assignments is to use the eq() method provided by objects that can have
297       a value assigned to them. They are signals, and their combinations with
298       the slice and concatenation operators.  As an example, the statement:
299
300          a[0].eq(b)
301
302       is equivalent to:
303
304          _Assign(_Slice(a, 0, 1), b)
305
306   If
307       The If object takes a first parameter which must be an expression (com‐
308       bination of the Constant, Signal, _Operator, _Slice, etc. objects) rep‐
309       resenting  the  condition,  then a variable number of parameters repre‐
310       senting the statements (_Assign, If, Case, etc. objects) to be executed
311       when the condition is verified.
312
313       The  If  object  defines a Else() method, which when called defines the
314       statements to be executed when the condition is not true. Those  state‐
315       ments are passed as parameters to the variadic method.
316
317       For convenience, there is also a Elif() method.
318
319       Example:
320
321          If(tx_count16 == 0,
322              tx_bitcount.eq(tx_bitcount + 1),
323              If(tx_bitcount == 8,
324                  self.tx.eq(1)
325              ).Elif(tx_bitcount == 9,
326                  self.tx.eq(1),
327                  tx_busy.eq(0)
328              ).Else(
329                  self.tx.eq(tx_reg[0]),
330                  tx_reg.eq(Cat(tx_reg[1:], 0))
331              )
332          )
333
334   Case
335       The  Case object constructor takes as first parameter the expression to
336       be tested, and a dictionary whose keys are the values  to  be  matched,
337       and  values  the  statements to be executed in the case of a match. The
338       special value "default" can be used as match  value,  which  means  the
339       statements should be executed whenever there is no other match.
340
341   Arrays
342       The  Array object represents lists of other objects that can be indexed
343       by FHDL expressions. It is explicitly possible to:
344
345       • nest Array objects to create multidimensional tables.
346
347       • list any Python object in a Array as long as every expression appear‐
348         ing  in  a  module  ultimately evaluates to a Signal for all possible
349         values of the indices. This allows the creation of  lists  of  struc‐
350         tured data.
351
352       • use  expressions  involving Array objects in both directions (assign‐
353         ment and reading).
354
355       For example, this creates a 4x4 matrix of 1-bit signals:
356
357          my_2d_array = Array(Array(Signal() for a in range(4)) for b in range(4))
358
359       You can then read the matrix with (x and y being 2-bit signals):
360
361          out.eq(my_2d_array[x][y])
362
363       and write it with:
364
365          my_2d_array[x][y].eq(inp)
366
367       Since they have no direct equivalent in Verilog, Array objects are low‐
368       ered  into  multiplexers  and  conditional statements before the actual
369       conversion takes place. Such lowering happens automatically without any
370       user intervention.
371
372       Any out-of-bounds access performed on an Array object will refer to the
373       last element.
374
375   Specials
376   Tri-state I/O
377       A triplet (O, OE, I) of one-way signals defining a tri-state  I/O  port
378       is represented by the TSTriple object. Such objects are only containers
379       for signals that are intended to be later connected to a tri-state  I/O
380       buffer,  and  cannot be used as module specials. Such objects, however,
381       should be kept in the design as long as possible as they allow the  in‐
382       dividual one-way signals to be manipulated in a non-ambiguous way.
383
384       The  object that can be used in as a module special is Tristate, and it
385       behaves exactly like an instance of a tri-state I/O buffer  that  would
386       be defined as follows:
387
388          Instance("Tristate",
389            io_target=target,
390            i_o=o,
391            i_oe=oe,
392            o_i=i
393          )
394
395       Signals target, o and i can have any width, while oe is 1-bit wide. The
396       target signal should go to a port and not be used elsewhere in the  de‐
397       sign.  Like  modern FPGA architectures, Migen does not support internal
398       tri-states.
399
400       A Tristate object can be created from a TSTriple object by calling  the
401       get_tristate method.
402
403       By  default,  Migen  emits technology-independent behavioral code for a
404       tri-state buffer. If a specific code is needed,  the  tristate  handler
405       can  be  overriden using the appropriate parameter of the V*HDL conver‐
406       sion function.
407
408   Instances
409       Instance objects represent the parametrized instantiation  of  a  V*HDL
410       module,  and the connection of its ports to FHDL signals. They are use‐
411       ful in a number of cases:
412
413       • Reusing legacy or third-party V*HDL code.
414
415       • Using special FPGA features (DCM, ICAP, ...).
416
417       • Implementing logic that cannot be expressed with FHDL (e.g. latches).
418
419       • Breaking down a Migen system into multiple sub-systems.
420
421       The instance object constructor takes the type (i.e. name  of  the  in‐
422       stantiated module) of the instance, then multiple parameters describing
423       how to connect and parametrize the instance.
424
425       These parameters can be:
426
427Instance.Input, Instance.Output or Instance.InOut to describe  signal
428         connections  with  the  instance.  The parameters are the name of the
429         port at the instance, and the FHDL expression it should be  connected
430         to.
431
432Instance.Parameter  sets  a  parameter (with a name and value) of the
433         instance.
434
435Instance.ClockPort and Instance.ResetPort are used to  connect  clock
436         and  reset  signals  to the instance. The only mandatory parameter is
437         the name of the port at the instance. Optionally, a clock domain name
438         can  be  specified, and the invert option can be used to interface to
439         those modules that require a 180-degree clock or a active-low reset.
440
441   Memories
442       Memories (on-chip SRAM) are supported using a mechanism similar to  in‐
443       stances.
444
445       A memory object has the following parameters:
446
447       • The width, which is the number of bits in each word.
448
449       • The depth, which represents the number of words in the memory.
450
451       • An optional list of integers used to initialize the memory.
452
453       To  access the memory in hardware, ports can be obtained by calling the
454       get_port method. A port always has an address signal a and a data  read
455       signal  dat_r.  Other  signals may be available depending on the port's
456       configuration.
457
458       Options to get_port are:
459
460write_capable (default: False): if the port can be used to  write  to
461         the memory. This creates an additional we signal.
462
463async_read  (default: False): whether reads are asychronous (combina‐
464         torial) or synchronous (registered).
465
466has_re (default: False): adds a read clock-enable signal re  (ignored
467         for asychronous ports).
468
469we_granularity  (default: 0): if non-zero, writes of less than a mem‐
470         ory word can occur. The width of the we signal is increased to act as
471         a selection signal for the sub-words.
472
473mode  (default:  WRITE_FIRST, ignored for aynchronous ports).  It can
474         be:
475
476READ_FIRST: during a write, the previous value is read.
477
478WRITE_FIRST: the written value is returned.
479
480NO_CHANGE: the data read signal  keeps  its  previous  value  on  a
481           write.
482
483clock_domain  (default: "sys"): the clock domain used for reading and
484         writing from this port.
485
486       Migen generates behavioural V*HDL code that should be  compatible  with
487       all  simulators  and, if the number of ports is <= 2, most FPGA synthe‐
488       sizers. If a specific code is needed, the memory handler can be overri‐
489       den using the appropriate parameter of the V*HDL conversion function.
490
491   Modules
492       Modules  play the same role as Verilog modules and VHDL entities. Simi‐
493       larly, they are organized in a tree  structure.  A  FHDL  module  is  a
494       Python  object  that  derives from the Module class. This class defines
495       special attributes to be used by  derived  classes  to  describe  their
496       logic. They are explained below.
497
498   Combinatorial statements
499       A  combinatorial statement is a statement that is executed whenever one
500       of its inputs changes.
501
502       Combinatorial statements are added to a module by using the  comb  spe‐
503       cial  attribute.  Like  most  module special attributes, it must be ac‐
504       cessed using the += incrementation operator, and either a single state‐
505       ment,  a  tuple of statements or a list of statements can appear on the
506       right hand side.
507
508       For example, the module below implements a OR gate:
509
510          class ORGate(Module):
511            def __init__(self):
512              self.a = Signal()
513              self.b = Signal()
514              self.x = Signal()
515
516              ###
517
518              self.comb += self.x.eq(self.a | self.b)
519
520       To improve code readability, it is recommended to place  the  interface
521       of  the  module at the beginning of the __init__ function, and separate
522       it from the implementation using three hash signs.
523
524   Synchronous statements
525       A synchronous statements is a statement that is executed at  each  edge
526       of some clock signal.
527
528       They  are  added to a module by using the sync special attribute, which
529       has the same properties as the comb attribute.
530
531       The sync special attribute also has sub-attributes that  correspond  to
532       abstract  clock  domains.  For example, to add a statement to the clock
533       domain named foo, one would write self.sync.foo += statement.  The  de‐
534       fault clock domain is sys and writing self.sync += statement is equiva‐
535       lent to writing self.sync.sys += statement.
536
537   Submodules and specials
538       Submodules and specials can be added by using the submodules  and  spe‐
539       cials attributes respectively. This can be done in two ways:
540
541       1. anonymously,  by  using the += operator on the special attribute di‐
542          rectly, e.g. self.submodules +=  some_other_module.  Like  with  the
543          comb and sync attributes, a single module/special or a tuple or list
544          can be specified.
545
546       2. by naming the submodule/special using a subattribute of the  submod‐
547          ules  or  specials attribute, e.g. self.submodules.foo = module_foo.
548          The submodule/special is then accessible as an attribute of the  ob‐
549          ject,  e.g. self.foo (and not self.submodules.foo). Only one submod‐
550          ule/special can be added at a time using this form.
551
552   Clock domains
553       Specifying the implementation of a  clock  domain  is  done  using  the
554       ClockDomain  object.  It contains the name of the clock domain, a clock
555       signal that can be driven like any other signal in the design (for  ex‐
556       ample,  using a PLL instance), and optionally a reset signal. Clock do‐
557       mains without a reset signal are reset using e.g. initial statements in
558       Verilog,  which  in  many  FPGA families initalize the registers during
559       configuration.
560
561       The name can be omitted if it can be extracted from the variable  name.
562       When  using this automatic naming feature, prefixes _, cd_ and _cd_ are
563       removed.
564
565       Clock domains are then added to a module using the  clock_domains  spe‐
566       cial attribute, which behaves exactly like submodules and specials.
567
568   Summary of special attributes
569              ┌───────────────────────────┬────────────────────────────┐
570              │Syntax                     │ Action                     │
571              ├───────────────────────────┼────────────────────────────┤
572              │self.comb += stmt          │ Add  combinatorial  state‐ │
573              │                           │ ment to current module.    │
574              ├───────────────────────────┼────────────────────────────┤
575              │self.comb += stmtA, stmtB  │ Add  combinatorial  state‐ │
576              │                           │ ments A and B  to  current │
577              │self.comb    +=    [stmtA, │ module.                    │
578              │stmtB]                     │                            │
579              ├───────────────────────────┼────────────────────────────┤
580              │self.sync += stmt          │ Add  synchronous statement │
581              │                           │ to current module, in  de‐ │
582              │                           │ fault clock domain sys.    │
583              ├───────────────────────────┼────────────────────────────┤
584              │self.sync.foo += stmt      │ Add  synchronous statement │
585              │                           │ to  current   module,   in │
586              │                           │ clock domain foo.          │
587              ├───────────────────────────┼────────────────────────────┤
588              │self.sync.foo   +=  stmtA, │ Add synchronous statements │
589              │stmtB                      │ A and B to current module, │
590              │                           │ in clock domain foo.       │
591              │self.sync.foo  +=  [stmtA, │                            │
592              │stmtB]                     │                            │
593              ├───────────────────────────┼────────────────────────────┤
594              │self.submodules += mod     │ Add anonymous submodule to │
595              │                           │ current module.            │
596              └───────────────────────────┴────────────────────────────┘
597
598
599
600
601
602              │self.submodules  +=  modA, │ Add anonymous submodules A │
603              │modB                       │ and B to current module.   │
604              │                           │                            │
605              │self.submodules  += [modA, │                            │
606              │modB]                      │                            │
607              ├───────────────────────────┼────────────────────────────┤
608              │self.submodules.bar = mod  │ Add submodule named bar to │
609              │                           │ current module.  The  sub‐ │
610              │                           │ module  can  then  be  ac‐ │
611              │                           │ cessed using self.bar.     │
612              ├───────────────────────────┼────────────────────────────┤
613              │self.specials += spe       │ Add anonymous  special  to │
614              │                           │ current module.            │
615              ├───────────────────────────┼────────────────────────────┤
616              │self.specials   +=   speA, │ Add  anonymous  specials A │
617              │speB                       │ and B to current module.   │
618              │                           │                            │
619              │self.specials  +=   [speA, │                            │
620              │speB]                      │                            │
621              ├───────────────────────────┼────────────────────────────┤
622              │self.specials.bar = spe    │ Add special named  bar  to │
623              │                           │ current  module.  The spe‐ │
624              │                           │ cial can then be  accessed │
625              │                           │ using self.bar.            │
626              ├───────────────────────────┼────────────────────────────┤
627              │self.clock_domains += cd   │ Add  clock  domain to cur‐ │
628              │                           │ rent module.               │
629              ├───────────────────────────┼────────────────────────────┤
630              │self.clock_domains += cdA, │ Add clock domains A and  B │
631              │cdB                        │ to current module.         │
632              │                           │                            │
633              │self.clock_domains      += │                            │
634              │[cdA, cdB]                 │                            │
635              ├───────────────────────────┼────────────────────────────┤
636              │self.clock_domains.pix   = │ Create  and  add clock do‐ │
637              │ClockDomain()              │ main pix to  current  mod‐ │
638              │                           │ ule. The clock domain name │
639              │self.clock_domains._pix  = │ is pix in  all  cases.  It │
640              │ClockDomain()              │ can   be   accessed  using │
641              │                           │ self.pix,       self._pix, │
642              │self.clock_domains.cd_pix  │ self.cd_pix            and │
643              │= ClockDomain()            │ self._cd_pix,      respec‐ │
644              │                           │ tively.                    │
645              │self.clock_domains._cd_pix │                            │
646              │= ClockDomain()            │                            │
647              └───────────────────────────┴────────────────────────────┘
648
649   Clock domain management
650       When a module has named submodules that define one or several clock do‐
651       mains with the same name, those clock domain names  are  prefixed  with
652       the name of each submodule plus an underscore.
653
654       An  example  use  case of this feature is a system with two independent
655       video outputs. Each video output module is made of  a  clock  generator
656       module  that  defines  a  clock domain pix and drives the clock signal,
657       plus a driver module that has synchronous statements and other elements
658       in clock domain pix. The designer of the video output module can simply
659       use the clock domain name pix in that module. In the  top-level  system
660       module,  the video output submodules are named video0 and video1. Migen
661       then automatically renames the pix  clock  domain  of  each  module  to
662       video0_pix and video1_pix. Note that happens only because the clock do‐
663       main is defined (using ClockDomain objects), not simply referenced (us‐
664       ing e.g. synchronous statements) in the video output modules.
665
666       Clock domain name overlap is an error condition when any of the submod‐
667       ules that defines the clock domains is anonymous.
668
669   Finalization mechanism
670       Sometimes, it is desirable that some of a module logic be created  only
671       after  the user has finished manipulating that module. For example, the
672       FSM module supports that states be defined dynamically, and  the  width
673       of the state signal can be known only after all states have been added.
674       One solution is to declare the final number of states in the  FSM  con‐
675       structor,  but this is not user-friendly. A better solution is to auto‐
676       matically create the state signal just before the FSM  module  is  con‐
677       verted  to  V*HDL. Migen supports this using the so-called finalization
678       mechanism.
679
680       Modules can overload a do_finalize method that can create logic and  is
681       called using the algorithm below:
682
683       1. Finalization of the current module begins.
684
685       2. If the module has already been finalized (e.g. manually), the proce‐
686          dure stops here.
687
688       3. Submodules of the current module are recursively finalized.
689
690       4. do_finalize is called for the current module.
691
692       5. Any new submodules created by the current module's  do_finalize  are
693          recursively finalized.
694
695       Finalization  is automatically invoked at V*HDL conversion and at simu‐
696       lation. It can be manually invoked for any module by calling its final‐
697       ize method.
698
699       The  clock  domain  management mechanism explained above happens during
700       finalization.
701
702   Conversion for synthesis
703       Any FHDL module can be converted into synthesizable Verilog  HDL.  This
704       is accomplished by using the convert function in the migen.fhdl.verilog
705       module:
706
707          # define FHDL module MyDesign here
708
709          if __name__ == "__main__":
710            from migen.fhdl.verilog import convert
711            convert(MyDesign()).write("my_design.v")
712
713       The migen.build component provides  scripts  to  interface  third-party
714       FPGA  tools  (from Xilinx, Altera and Lattice) to Migen, and a database
715       of boards for the easy deployment of designs.
716

SIMULATING A MIGEN DESIGN

718       Migen allows you to easily simulate your FHDL design and  interface  it
719       with arbitrary Python code. The simulator is written in pure Python and
720       interprets the FHDL structure directly without using an  external  Ver‐
721       ilog simulator.
722
723       Migen  lets  you  write testbenches using Python's generator functions.
724       Such testbenches execute concurrently with the FHDL simulator, and com‐
725       municate  with  it using the yield statement. There are four basic pat‐
726       terns:
727
728          1. Reads: the state of the signal at the current time can be queried
729             using (yield signal);
730
731          2. Writes: the state of the signal after the next clock cycle can be
732             set using (yield signal.eq(value));
733
734          3. Clocking: simulation can be advanced by  one  clock  cycle  using
735             yield;
736
737          4. Composition:  control  can  be  transferred  to another testbench
738             function using yield from run_other().
739
740       A testbench can be run  using  the  run_simulation  function  from  mi‐
741       gen.sim;  run_simulation(dut,  bench) runs the generator function bench
742       against the logic defined in an FHDL module dut.
743
744       Passing the vcd_name="file.vcd" argument to run_simulation  will  cause
745       it to write a VCD dump of the signals inside dut to file.vcd.
746
747   Examples
748       For example, consider this module:
749
750          class ORGate(Module):
751            def __init__(self):
752              self.a = Signal()
753              self.b = Signal()
754              self.x = Signal()
755
756              ###
757
758              self.comb += self.x.eq(self.a | self.b)
759
760       It could be simulated together with the following testbench:
761
762          dut = ORGate()
763
764          def testbench():
765            yield dut.a.eq(0)
766            yield dut.b.eq(0)
767            yield
768            assert (yield dut.x) == 0
769
770            yield dut.a.eq(0)
771            yield dut.b.eq(1)
772            yield
773            assert (yield dut.x) == 1
774
775          run_simulation(dut, testbench())
776
777       This is, of course, quite verbose, and individual steps can be factored
778       into a separate function:
779
780          dut = ORGate()
781
782          def check_case(a, b, x):
783            yield dut.a.eq(a)
784            yield dut.b.eq(b)
785            yield
786            assert (yield dut.x) == x
787
788          def testbench():
789            yield from check_case(0, 0, 0)
790            yield from check_case(0, 1, 1)
791            yield from check_case(1, 0, 1)
792            yield from check_case(1, 1, 1)
793
794          run_simulation(dut, testbench())
795
796   Pitfalls
797       There are, unfortunately, some basic mistakes  that  can  produce  very
798       puzzling results.
799
800       When calling other testbenches, it is important to not forget the yield
801       from. If it is omitted, the call would silently do nothing.
802
803       When writing to a signal, it is  important  that  nothing  else  should
804       drive the signal concurrently. If that is not the case, the write would
805       silently do nothing.
806

SYNTHESIZING A MIGEN DESIGN

808       [To be written]
809

API REFERENCE

811   fhdl.structure module
812       class migen.fhdl.structure.Array(iterable=(), /)
813              Bases: list
814
815              Addressable multiplexer
816
817              An array is created from an iterable of values and indexed using
818              the  usual  Python simple indexing notation (no negative indices
819              or slices). It can be indexed by numeric constants, _Value s, or
820              Signal s.
821
822              The result of indexing the array is a proxy for the entry at the
823              given index that can be used on either RHS  or  LHS  of  assign‐
824              ments.
825
826              An array can be indexed multiple times.
827
828              Multidimensional  arrays  are  supported by packing inner arrays
829              into outer arrays.
830
831              Parameters
832                     values (iterable of ints, _Values, Signals) -- Entries of
833                     the array. Each entry can be a numeric constant, a Signal
834                     or a Record.
835
836              Examples
837
838              >>> a = Array(range(10))
839              >>> b = Signal(max=10)
840              >>> c = Signal(max=10)
841              >>> b.eq(a[9 - c])
842
843       migen.fhdl.structure.C
844              alias of migen.fhdl.structure.Constant
845
846       class migen.fhdl.structure.Case(test, cases)
847              Bases: migen.fhdl.structure._Statement
848
849              Case/Switch statement
850
851              Parameters
852
853test (_Value, in) --  Selector  value  used  to  decide
854                       which block to execute
855
856cases  (dict)  -- Dictionary of cases. The keys are nu‐
857                       meric constants to compare with test.  The  values  are
858                       statements to be executed the corresponding key matches
859                       test. The dictionary may contain a string key "default"
860                       to  mark  a  fall-through  case  that is executed if no
861                       other key matches.
862
863              Examples
864
865              >>> a = Signal()
866              >>> b = Signal()
867              >>> Case(a, {
868              ...     0:         b.eq(1),
869              ...     1:         b.eq(0),
870              ...     "default": b.eq(0),
871              ... })
872
873              makedefault(key=None)
874                     Mark a key as the default case
875
876                     Deletes/substitutes any previously existing default case.
877
878                     Parameters
879                            key (int, Constant or None) -- Key to use  as  de‐
880                            fault  case  if no other key matches.  By default,
881                            the largest key is the default key.
882
883       class migen.fhdl.structure.Cat(*args)
884              Bases: migen.fhdl.structure._Value
885
886              Concatenate values
887
888              Form a compound _Value from several smaller ones  by  concatena‐
889              tion.  The first argument occupies the lower bits of the result.
890              The return value can be used on either side  of  an  assignment,
891              that  is,  the  concatenated value can be used as an argument on
892              the RHS or as a target on the LHS. If it is used on the LHS,  it
893              must  solely  consist of Signal s, slices of Signal s, and other
894              concatenations meeting these properties. The bit length  of  the
895              return value is the sum of the bit lengths of the arguments:
896
897                 len(Cat(args)) == sum(len(arg) for arg in args)
898
899              Parameters
900                     *args  (_Values or iterables of _Values, inout) -- _Value
901                     s to be concatenated.
902
903              Returns
904                     Resulting _Value obtained by concatentation.
905
906              Return type
907                     Cat, inout
908
909       class migen.fhdl.structure.ClockDomain(name=None, reset_less=False)
910              Bases: object
911
912              Synchronous domain
913
914              Parameters
915
916name (str or None) -- Domain name.  If  None  (the  de‐
917                       fault) the name is inferred from the variable name this
918                       ClockDomain is assigned to (stripping  any  "cd_"  pre‐
919                       fix).
920
921reset_less  (bool)  --  The domain does not use a reset
922                       signal. Registers within this domain are still all ini‐
923                       tialized  to their reset state once, e.g.  through Ver‐
924                       ilog "initial" statements.
925
926              clk    The clock for this domain. Can be driven or used to drive
927                     other signals (preferably in combinatorial context).
928
929                     Type   Signal, inout
930
931              rst    Reset  signal  for  this domain. Can be driven or used to
932                     drive.
933
934                     Type   Signal or None, inout
935
936              rename(new_name)
937                     Rename the clock domain
938
939                     Parameters
940                            new_name (str) -- New name
941
942       class migen.fhdl.structure.ClockSignal(cd='sys')
943              Bases: migen.fhdl.structure._Value
944
945              Clock signal for a given clock domain
946
947              ClockSignal s for a given clock domain can be retrieved multiple
948              times. They all ultimately refer to the same signal.
949
950              Parameters
951                     cd  (str)  --  Clock domain to obtain a clock signal for.
952                     Defaults to "sys".
953
954       class migen.fhdl.structure.Constant(value, bits_sign=None)
955              Bases: migen.fhdl.structure._Value
956
957              A constant, HDL-literal integer _Value
958
959              Parameters
960
961value (int) --
962
963bits_sign (int or tuple or None) -- Either  an  integer
964                       bits or a tuple (bits, signed) specifying the number of
965                       bits in this Constant and whether  it  is  signed  (can
966                       represent  negative  values). bits_sign defaults to the
967                       minimum width and signedness of value.
968
969       class migen.fhdl.structure.DUID
970              Bases: object
971
972              Deterministic Unique IDentifier
973
974       class migen.fhdl.structure.If(cond, *t)
975              Bases: migen.fhdl.structure._Statement
976
977              Conditional execution of statements
978
979              Parameters
980
981cond (_Value(1), in) -- Condition
982
983*t (Statements) -- Statements to execute if cond is as‐
984                       serted.
985
986              Examples
987
988              >>> a = Signal()
989              >>> b = Signal()
990              >>> c = Signal()
991              >>> d = Signal()
992              >>> If(a,
993              ...     b.eq(1)
994              ... ).Elif(c,
995              ...     b.eq(0)
996              ... ).Else(
997              ...     b.eq(d)
998              ... )
999
1000              Elif(cond, *t)
1001                     Add an else if conditional block
1002
1003                     Parameters
1004
1005cond (_Value(1), in) -- Condition
1006
1007*t (Statements) -- Statements to execute if pre‐
1008                              vious conditions fail and cond is asserted.
1009
1010              Else(*f)
1011                     Add an else conditional block
1012
1013                     Parameters
1014                            *f (Statements) -- Statements to  execute  if  all
1015                            previous conditions fail.
1016
1017       migen.fhdl.structure.Mux(sel, val1, val0)
1018              Multiplex between two values
1019
1020              Parameters
1021
1022sel (_Value(1), in) -- Selector.
1023
1024val1 (_Value(N), in) --
1025
1026val0 (_Value(N), in) -- Input values.
1027
1028              Returns
1029                     Output  _Value. If sel is asserted, the Mux returns val1,
1030                     else val0.
1031
1032              Return type
1033                     _Value(N), out
1034
1035       class migen.fhdl.structure.Replicate(v, n)
1036              Bases: migen.fhdl.structure._Value
1037
1038              Replicate a value
1039
1040              An input value is replicated (repeated) several times to be used
1041              on the RHS of assignments:
1042
1043                 len(Replicate(s, n)) == len(s)*n
1044
1045              Parameters
1046
1047v (_Value, in) -- Input value to be replicated.
1048
1049n (int) -- Number of replications.
1050
1051              Returns
1052                     Replicated value.
1053
1054              Return type
1055                     Replicate, out
1056
1057       class        migen.fhdl.structure.ResetSignal(cd='sys',       allow_re‐
1058       set_less=False)
1059              Bases: migen.fhdl.structure._Value
1060
1061              Reset signal for a given clock domain
1062
1063              ResetSignal s for a given clock domain can be retrieved multiple
1064              times. They all ultimately refer to the same signal.
1065
1066              Parameters
1067
1068cd  (str) -- Clock domain to obtain a reset signal for.
1069                       Defaults to "sys".
1070
1071allow_reset_less (bool) -- If the clock domain  is  re‐
1072                       setless, return 0 instead of reporting an error.
1073
1074       class   migen.fhdl.structure.Signal(bits_sign=None,   name=None,  vari‐
1075       able=False, reset=0,  reset_less=False,  name_override=None,  min=None,
1076       max=None, related=None, attr=None)
1077              Bases: migen.fhdl.structure._Value
1078
1079              A _Value that can change
1080
1081              The  Signal object represents a value that is expected to change
1082              in the circuit. It does exactly what Verilog's wire and reg  and
1083              VHDL's signal do.
1084
1085              A Signal can be indexed to access a subset of its bits. Negative
1086              indices (signal[-1]) and the extended  Python  slicing  notation
1087              (signal[start:stop:step])  are  supported.  The indices 0 and -1
1088              are the least and most significant bits respectively.
1089
1090              Parameters
1091
1092bits_sign (int or tuple) -- Either an integer bits or a
1093                       tuple  (bits,  signed) specifying the number of bits in
1094                       this Signal and whether it  is  signed  (can  represent
1095                       negative values). signed defaults to False.
1096
1097name  (str  or  None)  -- Name hint for this signal. If
1098                       None (default) the name is inferred from  the  variable
1099                       name  this  Signal is assigned to.  Name collisions are
1100                       automatically resolved by prepending names  of  objects
1101                       that  contain  this Signal and by appending integer se‐
1102                       quences.
1103
1104variable (bool) -- Deprecated.
1105
1106reset (int) -- Reset (synchronous) or default (combina‐
1107                       torial) value.  When this Signal is assigned to in syn‐
1108                       chronous context and the corresponding clock domain  is
1109                       reset,  the  Signal  assumes the given value. When this
1110                       Signal is unassigned in combinatorial context  (due  to
1111                       conditional  assignments  not  being taken), the Signal
1112                       assumes its reset value. Defaults to 0.
1113
1114reset_less (bool) -- If True,  do  not  generate  reset
1115                       logic  for  this  Signal in synchronous statements. The
1116                       reset value is only used as a combinatorial default  or
1117                       as the initial value. Defaults to False.
1118
1119name_override  (str or None) -- Do not use the inferred
1120                       name but the given one.
1121
1122min (int or None) --
1123
1124max (int or None) -- If bits_sign is None,  the  signal
1125                       bit  width and signedness are determined by the integer
1126                       range given by min (inclusive, defaults to 0)  and  max
1127                       (exclusive, defaults to 2).
1128
1129related (Signal or None) --
1130
1131attr (set of synthesis attributes) --
1132
1133              classmethod like(other, **kwargs)
1134                     Create Signal based on another.
1135
1136                     Parameters
1137
1138other (_Value) -- Object to base this Signal on.
1139
1140migen.fhdl.bitcontainer.value_bits_sign  for de‐
1141                              tails. (See) --
1142
1143       migen.fhdl.structure.wrap(value)
1144              Ensures that the passed object is a Migen  value.  Booleans  and
1145              integers are automatically wrapped into Constant.
1146
1147   fhdl.bitcontainer module
1148       migen.fhdl.bitcontainer.value_bits_sign(v)
1149              Bit length and signedness of a value.
1150
1151              Parameters
1152                     v (Value) --
1153
1154              Returns
1155                     Number  of  bits  required  to store v or available in v,
1156                     followed by whether v has a sign bit (included in the bit
1157                     count).
1158
1159              Return type
1160                     int, bool
1161
1162              Examples
1163
1164              >>> value_bits_sign(f.Signal(8))
1165              8, False
1166              >>> value_bits_sign(C(0xaa))
1167              8, False
1168
1169   genlib.fifo module
1170       class migen.genlib.fifo.AsyncFIFO(width, depth)
1171              Bases:  migen.fhdl.module.Module,  migen.genlib.fifo._FIFOInter‐
1172              face
1173
1174              Asynchronous FIFO (first in, first out)
1175
1176              Read and write interfaces are accessed from different clock  do‐
1177              mains,  named  read and write. Use ClockDomainsRenamer to rename
1178              to other names.
1179
1180              Data written to the  input  interface  (din,  we,  writable)  is
1181              buffered  and  can  be  read  at the output interface (dout, re,
1182              readable). The data entry written first to the  input  also  ap‐
1183              pears first on the output.
1184
1185              Parameters
1186
1187width (int) -- Bit width for the data.
1188
1189depth (int) -- Depth of the FIFO.
1190
1191              din    Input data
1192
1193                     Type   in, width
1194
1195              writable
1196                     There is space in the FIFO and we can be asserted to load
1197                     new data.
1198
1199                     Type   out
1200
1201              we     Write enable signal to latch  din  into  the  FIFO.  Does
1202                     nothing if writable is not asserted.
1203
1204                     Type   in
1205
1206              dout   Output data. Only valid if readable is asserted.
1207
1208                     Type   out, width
1209
1210              readable
1211                     Output data dout valid, FIFO not empty.
1212
1213                     Type   out
1214
1215              re     Acknowledge  dout.  If  asserted,  the next entry will be
1216                     available on the next cycle (if readable is high then).
1217
1218                     Type   in
1219
1220       class migen.genlib.fifo.AsyncFIFOBuffered(width, depth)
1221              Bases:  migen.fhdl.module.Module,  migen.genlib.fifo._FIFOInter‐
1222              face
1223
1224              Improves  timing  when it breaks due to sluggish clock-to-output
1225              delay in e.g. Xilinx block RAMs. Increases latency by one cycle.
1226
1227       class migen.genlib.fifo.SyncFIFO(width, depth, fwft=True)
1228              Bases:  migen.fhdl.module.Module,  migen.genlib.fifo._FIFOInter‐
1229              face
1230
1231              Synchronous FIFO (first in, first out)
1232
1233              Read  and  write interfaces are accessed from the same clock do‐
1234              main.  If different clock domains are needed, use AsyncFIFO.
1235
1236              Data written to the  input  interface  (din,  we,  writable)  is
1237              buffered  and  can  be  read  at the output interface (dout, re,
1238              readable). The data entry written first to the  input  also  ap‐
1239              pears first on the output.
1240
1241              Parameters
1242
1243width (int) -- Bit width for the data.
1244
1245depth (int) -- Depth of the FIFO.
1246
1247              din    Input data
1248
1249                     Type   in, width
1250
1251              writable
1252                     There is space in the FIFO and we can be asserted to load
1253                     new data.
1254
1255                     Type   out
1256
1257              we     Write enable signal to latch  din  into  the  FIFO.  Does
1258                     nothing if writable is not asserted.
1259
1260                     Type   in
1261
1262              dout   Output data. Only valid if readable is asserted.
1263
1264                     Type   out, width
1265
1266              readable
1267                     Output data dout valid, FIFO not empty.
1268
1269                     Type   out
1270
1271              re     Acknowledge  dout.  If  asserted,  the next entry will be
1272                     available on the next cycle (if readable is high then).
1273
1274                     Type   in
1275
1276              level  Number of unread entries.
1277
1278                     Type   out
1279
1280              replace
1281                     Replaces the last entry written into the FIFO  with  din.
1282                     Does  nothing  if  that entry has already been read (i.e.
1283                     the FIFO is empty).  Assert in conjunction with we.
1284
1285                     Type   in
1286
1287       class migen.genlib.fifo.SyncFIFOBuffered(width, depth)
1288              Bases:  migen.fhdl.module.Module,  migen.genlib.fifo._FIFOInter‐
1289              face
1290
1291              Has  an  interface  compatible with SyncFIFO with fwft=True, but
1292              does not use asynchronous RAM reads that are not compatible with
1293              block RAMs. Increases latency by one cycle.
1294
1295   genlib.coding module
1296       Encoders and decoders between binary and one-hot representation
1297
1298       class migen.genlib.coding.Decoder(width)
1299              Bases: migen.fhdl.module.Module
1300
1301              Decode binary to one-hot
1302
1303              If  n is low, the i th bit in o is asserted, the others are not,
1304              else o == 0.
1305
1306              Parameters
1307                     width (int) -- Bit width of the output
1308
1309              i      Input binary
1310
1311                     Type   Signal(max=width), in
1312
1313              o      Decoded one-hot
1314
1315                     Type   Signal(width), out
1316
1317              n      Invalid, no output bits are to be asserted
1318
1319                     Type   Signal(1), in
1320
1321       class migen.genlib.coding.Encoder(width)
1322              Bases: migen.fhdl.module.Module
1323
1324              Encode one-hot to binary
1325
1326              If n is low, the o th bit in i is asserted, else none or  multi‐
1327              ple bits are asserted.
1328
1329              Parameters
1330                     width (int) -- Bit width of the input
1331
1332              i      One-hot input
1333
1334                     Type   Signal(width), in
1335
1336              o      Encoded binary
1337
1338                     Type   Signal(max=width), out
1339
1340              n      Invalid, either none or multiple input bits are asserted
1341
1342                     Type   Signal(1), out
1343
1344       class migen.genlib.coding.PriorityDecoder(width)
1345              Bases: migen.genlib.coding.Decoder
1346
1347       class migen.genlib.coding.PriorityEncoder(width)
1348              Bases: migen.fhdl.module.Module
1349
1350              Priority encode requests to binary
1351
1352              If  n is low, the o th bit in i is asserted and the bits below o
1353              are unasserted, else o == 0. The LSB has priority.
1354
1355              Parameters
1356                     width (int) -- Bit width of the input
1357
1358              i      Input requests
1359
1360                     Type   Signal(width), in
1361
1362              o      Encoded binary
1363
1364                     Type   Signal(max=width), out
1365
1366              n      Invalid, no input bits are asserted
1367
1368                     Type   Signal(1), out
1369
1370   genlib.sort module
1371       class migen.genlib.sort.BitonicSort(n, m, ascending=True)
1372              Bases: migen.fhdl.module.Module
1373
1374              Combinatorial sorting network
1375
1376              The Bitonic sort is implemented as a  combinatorial  sort  using
1377              comparators  and  multiplexers.  Its  asymptotic  complexity (in
1378              terms of number of comparators/muxes) is  O(n  log(n)**2),  like
1379              mergesort or shellsort.
1380
1381              http://www.dps.uibk.ac.at/~cosenza/teaching/gpu/sort-batcher.pdf
1382
1383              http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm
1384
1385              http://www.myhdl.org/doku.php/cookbook:bitonic
1386
1387              Parameters
1388
1389n (int) -- Number of inputs and output signals.
1390
1391m (int) -- Bit width of inputs and outputs. Or a  tuple
1392                       of (m, signed).
1393
1394ascending (bool) -- Sort direction. True if input is to
1395                       be sorted ascending, False for descending. Defaults  to
1396                       ascending.
1397
1398              i      Input values, each m wide.
1399
1400                     Type   list of Signals, in
1401
1402              o      Output values, sorted, each m bits wide.
1403
1404                     Type   list of Signals, out
1405
1406   genlib.fsm module
1407       class migen.genlib.fsm.FSM(reset_state=None)
1408              Bases: migen.fhdl.module.Module
1409
1410              Finite state machine
1411
1412              Any Python objects can be used as states, e.g. strings.
1413
1414              Parameters
1415                     reset_state  --  Reset state. Defaults to the first added
1416                     state.
1417
1418              Examples
1419
1420              >>> self.active = Signal()
1421              >>> self.bitno = Signal(3)
1422              >>>
1423              >>> fsm = FSM(reset_state="START")
1424              >>> self.submodules += fsm
1425              >>>
1426              >>> fsm.act("START",
1427              ...     self.active.eq(1),
1428              ...     If(strobe,
1429              ...         NextState("DATA")
1430              ...     )
1431              ... )
1432              >>> fsm.act("DATA",
1433              ...     self.active.eq(1),
1434              ...     If(strobe,
1435              ...         NextValue(self.bitno, self.bitno + 1),
1436              ...         If(self.bitno == 7,
1437              ...             NextState("END")
1438              ...         )
1439              ...     )
1440              ... )
1441              >>> fsm.act("END",
1442              ...     self.active.eq(0),
1443              ...     NextState("STOP")
1444              ... )
1445
1446              act(state, *statements)
1447                     Schedules statements to be executed in state.  Statements
1448                     may include:
1449
1450                        • combinatorial statements of form a.eq(b), equivalent
1451                          to self.comb += a.eq(b) when the FSM is in the given
1452                          state;
1453
1454                        • synchronous  statements  of  form  NextValue(a,  b),
1455                          equivalent to self.sync += a.eq(b) when the  FSM  is
1456                          in the given state;
1457
1458                        • a  statement of form NextState(new_state), selecting
1459                          the next state;
1460
1461If, Case, etc.
1462
1463              ongoing(state)
1464                     Returns a signal that has the value 1 when the FSM is  in
1465                     the given state, and 0 otherwise.
1466

AUTHOR

1468       Sebastien Bourdeauducq
1469
1471       2011-2021, M-Labs Limited
1472
1473
1474
1475
14760.9                              Jul 23, 2021                         MIGEN(1)
Impressum