1MIGEN(1) Migen MIGEN(1)
2
3
4
6 migen - Migen manual
7
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
13 object-oriented programming and metaprogramming to design hardware.
14 This results in more elegant and easily maintained designs and reduces
15 the 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
90 example 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
151 The Fragmented Hardware Description Language (FHDL) is the basis of
152 Migen. It consists of a formal system to describe signals, and combina‐
153 torial 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
175 below. 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
180 behaves 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
218 exclusive 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].
267 Implicit indices using the forms [x], [x:] and [:y] are supported.
268 Beware! Slices work like Python slices, not like VHDL or Verilog
269 slices. The first bound is the index of the LSB and is inclusive. The
270 second 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
295 directly would result in a cluttered syntax, the preferred technique
296 for assignments is to use the eq() method provided by objects that can
297 have a value assigned to them. They are signals, and their combinations
298 with the slice and concatenation operators. As an example, the state‐
299 ment:
300
301 a[0].eq(b)
302
303 is equivalent to:
304
305 _Assign(_Slice(a, 0, 1), b)
306
307 If
308 The If object takes a first parameter which must be an expression (com‐
309 bination of the Constant, Signal, _Operator, _Slice, etc. objects) rep‐
310 resenting the condition, then a variable number of parameters repre‐
311 senting the statements (_Assign, If, Case, etc. objects) to be executed
312 when the condition is verified.
313
314 The If object defines a Else() method, which when called defines the
315 statements to be executed when the condition is not true. Those state‐
316 ments are passed as parameters to the variadic method.
317
318 For convenience, there is also a Elif() method.
319
320 Example:
321
322 If(tx_count16 == 0,
323 tx_bitcount.eq(tx_bitcount + 1),
324 If(tx_bitcount == 8,
325 self.tx.eq(1)
326 ).Elif(tx_bitcount == 9,
327 self.tx.eq(1),
328 tx_busy.eq(0)
329 ).Else(
330 self.tx.eq(tx_reg[0]),
331 tx_reg.eq(Cat(tx_reg[1:], 0))
332 )
333 )
334
335 Case
336 The Case object constructor takes as first parameter the expression to
337 be tested, and a dictionary whose keys are the values to be matched,
338 and values the statements to be executed in the case of a match. The
339 special value "default" can be used as match value, which means the
340 statements should be executed whenever there is no other match.
341
342 Arrays
343 The Array object represents lists of other objects that can be indexed
344 by FHDL expressions. It is explicitly possible to:
345
346 · nest Array objects to create multidimensional tables.
347
348 · list any Python object in a Array as long as every expression appear‐
349 ing in a module ultimately evaluates to a Signal for all possible
350 values of the indices. This allows the creation of lists of struc‐
351 tured data.
352
353 · use expressions involving Array objects in both directions (assign‐
354 ment and reading).
355
356 For example, this creates a 4x4 matrix of 1-bit signals:
357
358 my_2d_array = Array(Array(Signal() for a in range(4)) for b in range(4))
359
360 You can then read the matrix with (x and y being 2-bit signals):
361
362 out.eq(my_2d_array[x][y])
363
364 and write it with:
365
366 my_2d_array[x][y].eq(inp)
367
368 Since they have no direct equivalent in Verilog, Array objects are low‐
369 ered into multiplexers and conditional statements before the actual
370 conversion takes place. Such lowering happens automatically without any
371 user intervention.
372
373 Any out-of-bounds access performed on an Array object will refer to the
374 last element.
375
376 Specials
377 Tri-state I/O
378 A triplet (O, OE, I) of one-way signals defining a tri-state I/O port
379 is represented by the TSTriple object. Such objects are only containers
380 for signals that are intended to be later connected to a tri-state I/O
381 buffer, and cannot be used as module specials. Such objects, however,
382 should be kept in the design as long as possible as they allow the
383 individual one-way signals to be manipulated in a non-ambiguous way.
384
385 The object that can be used in as a module special is Tristate, and it
386 behaves exactly like an instance of a tri-state I/O buffer that would
387 be defined as follows:
388
389 Instance("Tristate",
390 io_target=target,
391 i_o=o,
392 i_oe=oe,
393 o_i=i
394 )
395
396 Signals target, o and i can have any width, while oe is 1-bit wide. The
397 target signal should go to a port and not be used elsewhere in the
398 design. Like modern FPGA architectures, Migen does not support internal
399 tri-states.
400
401 A Tristate object can be created from a TSTriple object by calling the
402 get_tristate method.
403
404 By default, Migen emits technology-independent behavioral code for a
405 tri-state buffer. If a specific code is needed, the tristate handler
406 can be overriden using the appropriate parameter of the V*HDL conver‐
407 sion function.
408
409 Instances
410 Instance objects represent the parametrized instantiation of a V*HDL
411 module, and the connection of its ports to FHDL signals. They are use‐
412 ful in a number of cases:
413
414 · Reusing legacy or third-party V*HDL code.
415
416 · Using special FPGA features (DCM, ICAP, ...).
417
418 · Implementing logic that cannot be expressed with FHDL (e.g. latches).
419
420 · Breaking down a Migen system into multiple sub-systems.
421
422 The instance object constructor takes the type (i.e. name of the
423 instantiated module) of the instance, then multiple parameters describ‐
424 ing how to connect and parametrize the instance.
425
426 These parameters can be:
427
428 · Instance.Input, Instance.Output or Instance.InOut to describe signal
429 connections with the instance. The parameters are the name of the
430 port at the instance, and the FHDL expression it should be connected
431 to.
432
433 · Instance.Parameter sets a parameter (with a name and value) of the
434 instance.
435
436 · Instance.ClockPort and Instance.ResetPort are used to connect clock
437 and reset signals to the instance. The only mandatory parameter is
438 the name of the port at the instance. Optionally, a clock domain name
439 can be specified, and the invert option can be used to interface to
440 those modules that require a 180-degree clock or a active-low reset.
441
442 Memories
443 Memories (on-chip SRAM) are supported using a mechanism similar to
444 instances.
445
446 A memory object has the following parameters:
447
448 · The width, which is the number of bits in each word.
449
450 · The depth, which represents the number of words in the memory.
451
452 · An optional list of integers used to initialize the memory.
453
454 To access the memory in hardware, ports can be obtained by calling the
455 get_port method. A port always has an address signal a and a data read
456 signal dat_r. Other signals may be available depending on the port's
457 configuration.
458
459 Options to get_port are:
460
461 · write_capable (default: False): if the port can be used to write to
462 the memory. This creates an additional we signal.
463
464 · async_read (default: False): whether reads are asychronous (combina‐
465 torial) or synchronous (registered).
466
467 · has_re (default: False): adds a read clock-enable signal re (ignored
468 for asychronous ports).
469
470 · we_granularity (default: 0): if non-zero, writes of less than a mem‐
471 ory word can occur. The width of the we signal is increased to act as
472 a selection signal for the sub-words.
473
474 · mode (default: WRITE_FIRST, ignored for aynchronous ports). It can
475 be:
476
477 · READ_FIRST: during a write, the previous value is read.
478
479 · WRITE_FIRST: the written value is returned.
480
481 · NO_CHANGE: the data read signal keeps its previous value on a
482 write.
483
484 · clock_domain (default: "sys"): the clock domain used for reading and
485 writing from this port.
486
487 Migen generates behavioural V*HDL code that should be compatible with
488 all simulators and, if the number of ports is <= 2, most FPGA synthe‐
489 sizers. If a specific code is needed, the memory handler can be overri‐
490 den using the appropriate parameter of the V*HDL conversion function.
491
492 Modules
493 Modules play the same role as Verilog modules and VHDL entities. Simi‐
494 larly, they are organized in a tree structure. A FHDL module is a
495 Python object that derives from the Module class. This class defines
496 special attributes to be used by derived classes to describe their
497 logic. They are explained below.
498
499 Combinatorial statements
500 A combinatorial statement is a statement that is executed whenever one
501 of its inputs changes.
502
503 Combinatorial statements are added to a module by using the comb spe‐
504 cial attribute. Like most module special attributes, it must be
505 accessed using the += incrementation operator, and either a single
506 statement, a tuple of statements or a list of statements can appear on
507 the right hand side.
508
509 For example, the module below implements a OR gate:
510
511 class ORGate(Module):
512 def __init__(self):
513 self.a = Signal()
514 self.b = Signal()
515 self.x = Signal()
516
517 ###
518
519 self.comb += self.x.eq(self.a | self.b)
520
521 To improve code readability, it is recommended to place the interface
522 of the module at the beginning of the __init__ function, and separate
523 it from the implementation using three hash signs.
524
525 Synchronous statements
526 A synchronous statements is a statement that is executed at each edge
527 of some clock signal.
528
529 They are added to a module by using the sync special attribute, which
530 has the same properties as the comb attribute.
531
532 The sync special attribute also has sub-attributes that correspond to
533 abstract clock domains. For example, to add a statement to the clock
534 domain named foo, one would write self.sync.foo += statement. The
535 default clock domain is sys and writing self.sync += statement is
536 equivalent to writing self.sync.sys += statement.
537
538 Submodules and specials
539 Submodules and specials can be added by using the submodules and spe‐
540 cials attributes respectively. This can be done in two ways:
541
542 1. anonymously, by using the += operator on the special attribute
543 directly, e.g. self.submodules += some_other_module. Like with the
544 comb and sync attributes, a single module/special or a tuple or list
545 can be specified.
546
547 2. by naming the submodule/special using a subattribute of the submod‐
548 ules or specials attribute, e.g. self.submodules.foo = module_foo.
549 The submodule/special is then accessible as an attribute of the
550 object, e.g. self.foo (and not self.submodules.foo). Only one sub‐
551 module/special can be added at a time using this form.
552
553 Clock domains
554 Specifying the implementation of a clock domain is done using the
555 ClockDomain object. It contains the name of the clock domain, a clock
556 signal that can be driven like any other signal in the design (for
557 example, using a PLL instance), and optionally a reset signal. Clock
558 domains without a reset signal are reset using e.g. initial statements
559 in Verilog, which in many FPGA families initalize the registers during
560 configuration.
561
562 The name can be omitted if it can be extracted from the variable name.
563 When using this automatic naming feature, prefixes _, cd_ and _cd_ are
564 removed.
565
566 Clock domains are then added to a module using the clock_domains spe‐
567 cial attribute, which behaves exactly like submodules and specials.
568
569 Summary of special attributes
570 ┌───────────────────────────┬────────────────────────────┐
571 │Syntax │ Action │
572 ├───────────────────────────┼────────────────────────────┤
573 │self.comb += stmt │ Add combinatorial state‐ │
574 │ │ ment to current module. │
575 ├───────────────────────────┼────────────────────────────┤
576 │self.comb += stmtA, stmtB │ Add combinatorial state‐ │
577 │ │ ments A and B to current │
578 │self.comb += [stmtA, │ module. │
579 │stmtB] │ │
580 ├───────────────────────────┼────────────────────────────┤
581 │self.sync += stmt │ Add synchronous statement │
582 │ │ to current module, in │
583 │ │ default clock domain sys. │
584 ├───────────────────────────┼────────────────────────────┤
585 │self.sync.foo += stmt │ Add synchronous statement │
586 │ │ to current module, in │
587 │ │ clock domain foo. │
588 ├───────────────────────────┼────────────────────────────┤
589 │self.sync.foo += stmtA, │ Add synchronous statements │
590 │stmtB │ A and B to current module, │
591 │ │ in clock domain foo. │
592 │self.sync.foo += [stmtA, │ │
593 │stmtB] │ │
594 ├───────────────────────────┼────────────────────────────┤
595 │self.submodules += mod │ Add anonymous submodule to │
596 │ │ current module. │
597 ├───────────────────────────┼────────────────────────────┤
598 │self.submodules += modA, │ Add anonymous submodules A │
599 │modB │ and B to current module. │
600 │ │ │
601 │self.submodules += [modA, │ │
602 │modB] │ │
603 └───────────────────────────┴────────────────────────────┘
604
605 │self.submodules.bar = mod │ Add submodule named bar to │
606 │ │ current module. The sub‐ │
607 │ │ module can then be │
608 │ │ accessed using self.bar. │
609 ├───────────────────────────┼────────────────────────────┤
610 │self.specials += spe │ Add anonymous special to │
611 │ │ current module. │
612 ├───────────────────────────┼────────────────────────────┤
613 │self.specials += speA, │ Add anonymous specials A │
614 │speB │ and B to current module. │
615 │ │ │
616 │self.specials += [speA, │ │
617 │speB] │ │
618 ├───────────────────────────┼────────────────────────────┤
619 │self.specials.bar = spe │ Add special named bar to │
620 │ │ current module. The spe‐ │
621 │ │ cial can then be accessed │
622 │ │ using self.bar. │
623 ├───────────────────────────┼────────────────────────────┤
624 │self.clock_domains += cd │ Add clock domain to cur‐ │
625 │ │ rent module. │
626 ├───────────────────────────┼────────────────────────────┤
627 │self.clock_domains += cdA, │ Add clock domains A and B │
628 │cdB │ to current module. │
629 │ │ │
630 │self.clock_domains += │ │
631 │[cdA, cdB] │ │
632 ├───────────────────────────┼────────────────────────────┤
633 │self.clock_domains.pix = │ Create and add clock │
634 │ClockDomain() │ domain pix to current mod‐ │
635 │ │ ule. The clock domain name │
636 │self.clock_domains._pix = │ is pix in all cases. It │
637 │ClockDomain() │ can be accessed using │
638 │ │ self.pix, self._pix, │
639 │self.clock_domains.cd_pix │ self.cd_pix and │
640 │= ClockDomain() │ self._cd_pix, respec‐ │
641 │ │ tively. │
642 │self.clock_domains._cd_pix │ │
643 │= ClockDomain() │ │
644 └───────────────────────────┴────────────────────────────┘
645
646 Clock domain management
647 When a module has named submodules that define one or several clock
648 domains with the same name, those clock domain names are prefixed with
649 the name of each submodule plus an underscore.
650
651 An example use case of this feature is a system with two independent
652 video outputs. Each video output module is made of a clock generator
653 module that defines a clock domain pix and drives the clock signal,
654 plus a driver module that has synchronous statements and other elements
655 in clock domain pix. The designer of the video output module can simply
656 use the clock domain name pix in that module. In the top-level system
657 module, the video output submodules are named video0 and video1. Migen
658 then automatically renames the pix clock domain of each module to
659 video0_pix and video1_pix. Note that happens only because the clock
660 domain is defined (using ClockDomain objects), not simply referenced
661 (using e.g. synchronous statements) in the video output modules.
662
663 Clock domain name overlap is an error condition when any of the submod‐
664 ules that defines the clock domains is anonymous.
665
666 Finalization mechanism
667 Sometimes, it is desirable that some of a module logic be created only
668 after the user has finished manipulating that module. For example, the
669 FSM module supports that states be defined dynamically, and the width
670 of the state signal can be known only after all states have been added.
671 One solution is to declare the final number of states in the FSM con‐
672 structor, but this is not user-friendly. A better solution is to auto‐
673 matically create the state signal just before the FSM module is con‐
674 verted to V*HDL. Migen supports this using the so-called finalization
675 mechanism.
676
677 Modules can overload a do_finalize method that can create logic and is
678 called using the algorithm below:
679
680 1. Finalization of the current module begins.
681
682 2. If the module has already been finalized (e.g. manually), the proce‐
683 dure stops here.
684
685 3. Submodules of the current module are recursively finalized.
686
687 4. do_finalize is called for the current module.
688
689 5. Any new submodules created by the current module's do_finalize are
690 recursively finalized.
691
692 Finalization is automatically invoked at V*HDL conversion and at simu‐
693 lation. It can be manually invoked for any module by calling its final‐
694 ize method.
695
696 The clock domain management mechanism explained above happens during
697 finalization.
698
699 Conversion for synthesis
700 Any FHDL module can be converted into synthesizable Verilog HDL. This
701 is accomplished by using the convert function in the migen.fhdl.verilog
702 module:
703
704 # define FHDL module MyDesign here
705
706 if __name__ == "__main__":
707 from migen.fhdl.verilog import convert
708 convert(MyDesign()).write("my_design.v")
709
710 The migen.build component provides scripts to interface third-party
711 FPGA tools (from Xilinx, Altera and Lattice) to Migen, and a database
712 of boards for the easy deployment of designs.
713
715 Migen allows you to easily simulate your FHDL design and interface it
716 with arbitrary Python code. The simulator is written in pure Python and
717 interprets the FHDL structure directly without using an external Ver‐
718 ilog simulator.
719
720 Migen lets you write testbenches using Python's generator functions.
721 Such testbenches execute concurrently with the FHDL simulator, and com‐
722 municate with it using the yield statement. There are four basic pat‐
723 terns:
724
725 1. Reads: the state of the signal at the current time can be queried
726 using (yield signal);
727
728 2. Writes: the state of the signal after the next clock cycle can be
729 set using (yield signal.eq(value));
730
731 3. Clocking: simulation can be advanced by one clock cycle using
732 yield;
733
734 4. Composition: control can be transferred to another testbench
735 function using yield from run_other().
736
737 A testbench can be run using the run_simulation function from
738 migen.sim; run_simulation(dut, bench) runs the generator function bench
739 against the logic defined in an FHDL module dut.
740
741 Passing the vcd_name="file.vcd" argument to run_simulation will cause
742 it to write a VCD dump of the signals inside dut to file.vcd.
743
744 Examples
745 For example, consider this module:
746
747 class ORGate(Module):
748 def __init__(self):
749 self.a = Signal()
750 self.b = Signal()
751 self.x = Signal()
752
753 ###
754
755 self.comb += self.x.eq(self.a | self.b)
756
757 It could be simulated together with the following testbench:
758
759 dut = ORGate()
760
761 def testbench():
762 yield dut.a.eq(0)
763 yield dut.b.eq(0)
764 yield
765 assert (yield dut.x) == 0
766
767 yield dut.a.eq(0)
768 yield dut.b.eq(1)
769 yield
770 assert (yield dut.x) == 1
771
772 run_simulation(dut, testbench())
773
774 This is, of course, quite verbose, and individual steps can be factored
775 into a separate function:
776
777 dut = ORGate()
778
779 def check_case(a, b, x):
780 yield dut.a.eq(a)
781 yield dut.b.eq(b)
782 yield
783 assert (yield dut.x) == x
784
785 def testbench():
786 yield from check_case(0, 0, 0)
787 yield from check_case(0, 1, 1)
788 yield from check_case(1, 0, 1)
789 yield from check_case(1, 1, 1)
790
791 run_simulation(dut, testbench())
792
793 Pitfalls
794 There are, unfortunately, some basic mistakes that can produce very
795 puzzling results.
796
797 When calling other testbenches, it is important to not forget the yield
798 from. If it is omitted, the call would silently do nothing.
799
800 When writing to a signal, it is important that nothing else should
801 drive the signal concurrently. If that is not the case, the write would
802 silently do nothing.
803
805 [To be written]
806
808 fhdl.structure module
809 class migen.fhdl.structure.Array
810 Bases: list
811
812 Addressable multiplexer
813
814 An array is created from an iterable of values and indexed using
815 the usual Python simple indexing notation (no negative indices
816 or slices). It can be indexed by numeric constants, _Value s, or
817 Signal s.
818
819 The result of indexing the array is a proxy for the entry at the
820 given index that can be used on either RHS or LHS of assign‐
821 ments.
822
823 An array can be indexed multiple times.
824
825 Multidimensional arrays are supported by packing inner arrays
826 into outer arrays.
827
828 Parameters
829 values (iterable of ints, _Values, Signals) -- Entries of
830 the array. Each entry can be a numeric constant, a Signal
831 or a Record.
832 Examples.sp
833 >>> a = Array(range(10))
834 >>> b = Signal(max=10)
835 >>> c = Signal(max=10)
836 >>> b.eq(a[9 - c])
837
838 migen.fhdl.structure.C
839 alias of migen.fhdl.structure.Constant
840
841 class migen.fhdl.structure.Case(test, cases)
842 Bases: migen.fhdl.structure._Statement
843
844 Case/Switch statement
845
846 Parameters
847
848 · test (_Value, in) -- Selector value used to decide
849 which block to execute
850
851 · cases (dict) -- Dictionary of cases. The keys are
852 numeric constants to compare with test. The values are
853 statements to be executed the corresponding key matches
854 test. The dictionary may contain a string key "default"
855 to mark a fall-through case that is executed if no
856 other key matches.
857 Examples.sp
858 >>> a = Signal()
859 >>> b = Signal()
860 >>> Case(a, {
861 ... 0: b.eq(1),
862 ... 1: b.eq(0),
863 ... "default": b.eq(0),
864 ... })
865
866 makedefault(key=None)
867 Mark a key as the default case
868
869 Deletes/substitutes any previously existing default case.
870
871 Parameters
872 key (int, Constant or None) -- Key to use as
873 default case if no other key matches. By default,
874 the largest key is the default key.
875
876 class migen.fhdl.structure.Cat(*args)
877 Bases: migen.fhdl.structure._Value
878
879 Concatenate values
880
881 Form a compound _Value from several smaller ones by concatena‐
882 tion. The first argument occupies the lower bits of the result.
883 The return value can be used on either side of an assignment,
884 that is, the concatenated value can be used as an argument on
885 the RHS or as a target on the LHS. If it is used on the LHS, it
886 must solely consist of Signal s, slices of Signal s, and other
887 concatenations meeting these properties. The bit length of the
888 return value is the sum of the bit lengths of the arguments:
889
890 len(Cat(args)) == sum(len(arg) for arg in args)
891
892 Parameters
893 *args (_Values or iterables of _Values, inout) -- _Value
894 s to be concatenated.
895
896 Returns
897 Resulting _Value obtained by concatentation.
898
899 Return type
900 Cat, inout
901
902 class migen.fhdl.structure.ClockDomain(name=None, reset_less=False)
903 Bases: object
904
905 Synchronous domain
906
907 Parameters
908
909 · name (str or None) -- Domain name. If None (the
910 default) the name is inferred from the variable name
911 this ClockDomain is assigned to (stripping any "cd_"
912 prefix).
913
914 · reset_less (bool) -- The domain does not use a reset
915 signal. Registers within this domain are still all ini‐
916 tialized to their reset state once, e.g. through Ver‐
917 ilog "initial" statements.
918
919 clk The clock for this domain. Can be driven or used to drive
920 other signals (preferably in combinatorial context).
921
922 Type Signal, inout
923
924 rst Reset signal for this domain. Can be driven or used to
925 drive.
926
927 Type Signal or None, inout
928
929 rename(new_name)
930 Rename the clock domain
931
932 Parameters
933 new_name (str) -- New name
934
935 class migen.fhdl.structure.ClockSignal(cd='sys')
936 Bases: migen.fhdl.structure._Value
937
938 Clock signal for a given clock domain
939
940 ClockSignal s for a given clock domain can be retrieved multiple
941 times. They all ultimately refer to the same signal.
942
943 Parameters
944 cd (str) -- Clock domain to obtain a clock signal for.
945 Defaults to "sys".
946
947 class migen.fhdl.structure.Constant(value, bits_sign=None)
948 Bases: migen.fhdl.structure._Value
949
950 A constant, HDL-literal integer _Value
951
952 Parameters
953
954 · value (int) --
955
956 · bits_sign (int or tuple or None) -- Either an integer
957 bits or a tuple (bits, signed) specifying the number of
958 bits in this Constant and whether it is signed (can
959 represent negative values). bits_sign defaults to the
960 minimum width and signedness of value.
961
962 class migen.fhdl.structure.DUID
963 Bases: object
964
965 Deterministic Unique IDentifier
966
967 class migen.fhdl.structure.If(cond, *t)
968 Bases: migen.fhdl.structure._Statement
969
970 Conditional execution of statements
971
972 Parameters
973
974 · cond (_Value(1), in) -- Condition
975
976 · *t (Statements) -- Statements to execute if cond is
977 asserted.
978 Examples.sp
979 >>> a = Signal()
980 >>> b = Signal()
981 >>> c = Signal()
982 >>> d = Signal()
983 >>> If(a,
984 ... b.eq(1)
985 ... ).Elif(c,
986 ... b.eq(0)
987 ... ).Else(
988 ... b.eq(d)
989 ... )
990
991 Elif(cond, *t)
992 Add an else if conditional block
993
994 Parameters
995
996 · cond (_Value(1), in) -- Condition
997
998 · *t (Statements) -- Statements to execute if pre‐
999 vious conditions fail and cond is asserted.
1000
1001 Else(*f)
1002 Add an else conditional block
1003
1004 Parameters
1005 *f (Statements) -- Statements to execute if all
1006 previous conditions fail.
1007
1008 migen.fhdl.structure.Mux(sel, val1, val0)
1009 Multiplex between two values
1010
1011 Parameters
1012
1013 · sel (_Value(1), in) -- Selector.
1014
1015 · val1 (_Value(N), in) --
1016
1017 · val0 (_Value(N), in) -- Input values.
1018
1019 Returns
1020 Output _Value. If sel is asserted, the Mux returns val1,
1021 else val0.
1022
1023 Return type
1024 _Value(N), out
1025
1026 class migen.fhdl.structure.Replicate(v, n)
1027 Bases: migen.fhdl.structure._Value
1028
1029 Replicate a value
1030
1031 An input value is replicated (repeated) several times to be used
1032 on the RHS of assignments:
1033
1034 len(Replicate(s, n)) == len(s)*n
1035
1036 Parameters
1037
1038 · v (_Value, in) -- Input value to be replicated.
1039
1040 · n (int) -- Number of replications.
1041
1042 Returns
1043 Replicated value.
1044
1045 Return type
1046 Replicate, out
1047
1048 class migen.fhdl.structure.ResetSignal(cd='sys',
1049 allow_reset_less=False)
1050 Bases: migen.fhdl.structure._Value
1051
1052 Reset signal for a given clock domain
1053
1054 ResetSignal s for a given clock domain can be retrieved multiple
1055 times. They all ultimately refer to the same signal.
1056
1057 Parameters
1058
1059 · cd (str) -- Clock domain to obtain a reset signal for.
1060 Defaults to "sys".
1061
1062 · allow_reset_less (bool) -- If the clock domain is
1063 resetless, return 0 instead of reporting an error.
1064
1065 class migen.fhdl.structure.Signal(bits_sign=None, name=None, vari‐
1066 able=False, reset=0, reset_less=False, name_override=None, min=None,
1067 max=None, related=None, attr=None)
1068 Bases: migen.fhdl.structure._Value
1069
1070 A _Value that can change
1071
1072 The Signal object represents a value that is expected to change
1073 in the circuit. It does exactly what Verilog's wire and reg and
1074 VHDL's signal do.
1075
1076 A Signal can be indexed to access a subset of its bits. Negative
1077 indices (signal[-1]) and the extended Python slicing notation
1078 (signal[start:stop:step]) are supported. The indices 0 and -1
1079 are the least and most significant bits respectively.
1080
1081 Parameters
1082
1083 · bits_sign (int or tuple) -- Either an integer bits or a
1084 tuple (bits, signed) specifying the number of bits in
1085 this Signal and whether it is signed (can represent
1086 negative values). signed defaults to False.
1087
1088 · name (str or None) -- Name hint for this signal. If
1089 None (default) the name is inferred from the variable
1090 name this Signal is assigned to. Name collisions are
1091 automatically resolved by prepending names of objects
1092 that contain this Signal and by appending integer
1093 sequences.
1094
1095 · variable (bool) -- Deprecated.
1096
1097 · reset (int) -- Reset (synchronous) or default (combina‐
1098 torial) value. When this Signal is assigned to in syn‐
1099 chronous context and the corresponding clock domain is
1100 reset, the Signal assumes the given value. When this
1101 Signal is unassigned in combinatorial context (due to
1102 conditional assignments not being taken), the Signal
1103 assumes its reset value. Defaults to 0.
1104
1105 · reset_less (bool) -- If True, do not generate reset
1106 logic for this Signal in synchronous statements. The
1107 reset value is only used as a combinatorial default or
1108 as the initial value. Defaults to False.
1109
1110 · name_override (str or None) -- Do not use the inferred
1111 name but the given one.
1112
1113 · min (int or None) --
1114
1115 · max (int or None) -- If bits_sign is None, the signal
1116 bit width and signedness are determined by the integer
1117 range given by min (inclusive, defaults to 0) and max
1118 (exclusive, defaults to 2).
1119
1120 · related (Signal or None) --
1121
1122 · attr (set of synthesis attributes) --
1123
1124 classmethod like(other, **kwargs)
1125 Create Signal based on another.
1126
1127 Parameters
1128
1129 · other (_Value) -- Object to base this Signal on.
1130
1131 · migen.fhdl.bitcontainer.value_bits_sign for
1132 details. (See) --
1133
1134 migen.fhdl.structure.wrap(value)
1135 Ensures that the passed object is a Migen value. Booleans and
1136 integers are automatically wrapped into Constant.
1137
1138 fhdl.bitcontainer module
1139 migen.fhdl.bitcontainer.value_bits_sign(v)
1140 Bit length and signedness of a value.
1141
1142 Parameters
1143 v (Value) --
1144
1145 Returns
1146 Number of bits required to store v or available in v,
1147 followed by whether v has a sign bit (included in the bit
1148 count).
1149
1150 Return type
1151 int, bool
1152 Examples.sp
1153 >>> value_bits_sign(f.Signal(8))
1154 8, False
1155 >>> value_bits_sign(C(0xaa))
1156 8, False
1157
1158 genlib.fifo module
1159 class migen.genlib.fifo.SyncFIFO(width, depth, fwft=True)
1160 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1161 face
1162
1163 Synchronous FIFO (first in, first out)
1164
1165 Read and write interfaces are accessed from the same clock
1166 domain. If different clock domains are needed, use AsyncFIFO.
1167
1168 Data written to the input interface (din, we, writable) is
1169 buffered and can be read at the output interface (dout, re,
1170 readable). The data entry written first to the input also
1171 appears first on the output.
1172
1173 Parameters
1174
1175 · width (int) -- Bit width for the data.
1176
1177 · depth (int) -- Depth of the FIFO.
1178
1179 din Input data
1180
1181 Type in, width
1182
1183 writable
1184 There is space in the FIFO and we can be asserted to load
1185 new data.
1186
1187 Type out
1188
1189 we Write enable signal to latch din into the FIFO. Does
1190 nothing if writable is not asserted.
1191
1192 Type in
1193
1194 dout Output data. Only valid if readable is asserted.
1195
1196 Type out, width
1197
1198 readable
1199 Output data dout valid, FIFO not empty.
1200
1201 Type out
1202
1203 re Acknowledge dout. If asserted, the next entry will be
1204 available on the next cycle (if readable is high then).
1205
1206 Type in
1207
1208 level Number of unread entries.
1209
1210 Type out
1211
1212 replace
1213 Replaces the last entry written into the FIFO with din.
1214 Does nothing if that entry has already been read (i.e.
1215 the FIFO is empty). Assert in conjunction with we.
1216
1217 Type in
1218
1219 class migen.genlib.fifo.SyncFIFOBuffered(width, depth)
1220 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1221 face
1222
1223 Has an interface compatible with SyncFIFO with fwft=True, but
1224 does not use asynchronous RAM reads that are not compatible with
1225 block RAMs. Increases latency by one cycle.
1226
1227 class migen.genlib.fifo.AsyncFIFO(width, depth)
1228 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1229 face
1230
1231 Asynchronous FIFO (first in, first out)
1232
1233 Read and write interfaces are accessed from different clock
1234 domains, named read and write. Use ClockDomainsRenamer to rename
1235 to other names.
1236
1237 Data written to the input interface (din, we, writable) is
1238 buffered and can be read at the output interface (dout, re,
1239 readable). The data entry written first to the input also
1240 appears first on the output.
1241
1242 Parameters
1243
1244 · width (int) -- Bit width for the data.
1245
1246 · depth (int) -- Depth of the FIFO.
1247
1248 din Input data
1249
1250 Type in, width
1251
1252 writable
1253 There is space in the FIFO and we can be asserted to load
1254 new data.
1255
1256 Type out
1257
1258 we Write enable signal to latch din into the FIFO. Does
1259 nothing if writable is not asserted.
1260
1261 Type in
1262
1263 dout Output data. Only valid if readable is asserted.
1264
1265 Type out, width
1266
1267 readable
1268 Output data dout valid, FIFO not empty.
1269
1270 Type out
1271
1272 re Acknowledge dout. If asserted, the next entry will be
1273 available on the next cycle (if readable is high then).
1274
1275 Type in
1276
1277 class migen.genlib.fifo.AsyncFIFOBuffered(width, depth)
1278 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1279 face
1280
1281 Improves timing when it breaks due to sluggish clock-to-output
1282 delay in e.g. Xilinx block RAMs. Increases latency by one cycle.
1283
1284 genlib.coding module
1285 Encoders and decoders between binary and one-hot representation
1286
1287 class migen.genlib.coding.Decoder(width)
1288 Bases: migen.fhdl.module.Module
1289
1290 Decode binary to one-hot
1291
1292 If n is low, the i th bit in o is asserted, the others are not,
1293 else o == 0.
1294
1295 Parameters
1296 width (int) -- Bit width of the output
1297
1298 i Input binary
1299
1300 Type Signal(max=width), in
1301
1302 o Decoded one-hot
1303
1304 Type Signal(width), out
1305
1306 n Invalid, no output bits are to be asserted
1307
1308 Type [22mSignal(1), in
1309
1310 class migen.genlib.coding.Encoder(width)
1311 Bases: migen.fhdl.module.Module
1312
1313 Encode one-hot to binary
1314
1315 If n is low, the o th bit in i is asserted, else none or multi‐
1316 ple bits are asserted.
1317
1318 Parameters
1319 width (int) -- Bit width of the input
1320
1321 i One-hot input
1322
1323 Type Signal(width), in
1324
1325 o Encoded binary
1326
1327 Type Signal(max=width), out
1328
1329 n Invalid, either none or multiple input bits are asserted
1330
1331 Type [22mSignal(1), out
1332
1333 class migen.genlib.coding.PriorityDecoder(width)
1334 Bases: migen.genlib.coding.Decoder
1335
1336 class migen.genlib.coding.PriorityEncoder(width)
1337 Bases: migen.fhdl.module.Module
1338
1339 Priority encode requests to binary
1340
1341 If n is low, the o th bit in i is asserted and the bits below o
1342 are unasserted, else o == 0. The LSB has priority.
1343
1344 Parameters
1345 width (int) -- Bit width of the input
1346
1347 i Input requests
1348
1349 Type Signal(width), in
1350
1351 o Encoded binary
1352
1353 Type Signal(max=width), out
1354
1355 n Invalid, no input bits are asserted
1356
1357 Type [22mSignal(1), out
1358
1359 genlib.sort module
1360 class migen.genlib.sort.BitonicSort(n, m, ascending=True)
1361 Bases: migen.fhdl.module.Module
1362
1363 Combinatorial sorting network
1364
1365 The Bitonic sort is implemented as a combinatorial sort using
1366 comparators and multiplexers. Its asymptotic complexity (in
1367 terms of number of comparators/muxes) is O(n log(n)**2), like
1368 mergesort or shellsort.
1369
1370 http://www.dps.uibk.ac.at/~cosenza/teaching/gpu/sort-batcher.pdf
1371
1372 http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm
1373
1374 http://www.myhdl.org/doku.php/cookbook:bitonic
1375
1376 Parameters
1377
1378 · n (int) -- Number of inputs and output signals.
1379
1380 · m (int) -- Bit width of inputs and outputs. Or a tuple
1381 of (m, signed).
1382
1383 · ascending (bool) -- Sort direction. True if input is to
1384 be sorted ascending, False for descending. Defaults to
1385 ascending.
1386
1387 i Input values, each m wide.
1388
1389 Type list of Signals, in
1390
1391 o Output values, sorted, each m bits wide.
1392
1393 Type list of Signals, out
1394
1395 genlib.fsm module
1396 class migen.genlib.fsm.FSM(reset_state=None)
1397 Bases: migen.fhdl.module.Module
1398
1399 Finite state machine
1400
1401 Any Python objects can be used as states, e.g. strings.
1402
1403 Parameters
1404 reset_state -- Reset state. Defaults to the first added
1405 state.
1406 Examples.sp
1407 >>> self.active = Signal()
1408 >>> self.bitno = Signal(3)
1409 >>>
1410 >>> fsm = FSM(reset_state="START")
1411 >>> self.submodules += fsm
1412 >>>
1413 >>> fsm.act("START",
1414 ... self.active.eq(1),
1415 ... If(strobe,
1416 ... NextState("DATA")
1417 ... )
1418 ... )
1419 >>> fsm.act("DATA",
1420 ... self.active.eq(1),
1421 ... If(strobe,
1422 ... NextValue(self.bitno, self.bitno + 1),
1423 ... If(self.bitno == 7,
1424 ... NextState("END")
1425 ... )
1426 ... )
1427 ... )
1428 >>> fsm.act("END",
1429 ... self.active.eq(0),
1430 ... NextState("STOP")
1431 ... )
1432
1433 act(state, *statements)
1434 Schedules statements to be executed in state. Statements
1435 may include:
1436
1437 · combinatorial statements of form a.eq(b), equivalent
1438 to self.comb += a.eq(b) when the FSM is in the given
1439 state;
1440
1441 · synchronous statements of form NextValue(a, b),
1442 equivalent to self.sync += a.eq(b) when the FSM is
1443 in the given state;
1444
1445 · a statement of form NextState(new_state), selecting
1446 the next state;
1447
1448 · If, Case, etc.
1449
1450 ongoing(state)
1451 Returns a signal that has the value 1 when the FSM is in
1452 the given state, and 0 otherwise.
1453
1455 Sebastien Bourdeauducq
1456
1458 2011-2015, M-Labs Limited
1459
1460
1461
1462
14630.9 Jun 06, 2019 MIGEN(1)