Designing Flip-Flops With Python and Migen

migen

Flip-flops are extremely simple electronic circuits, forming the basis of clock circuits, memory circuits, buffers, and shift registers. Through his dilly-dallying with digital logic, [Jeffrey] decided he would build his own. Not with Verilog or VHDL, though, but Migen: the Python-based way to build digital circuits with software.

Migen is an interesting tool that makes traditional FPGA programming a lot easier; instead of Verilog or VHDL, Migen allows an FPGA to be programmed in Python. Yes, it’s the tool you’ve been waiting for, and the tutorials make it look pretty easy. After installing Migen, [Jeff] wrote a class for a D flip-flop in only three lines of code. That’s three readable lines of code, and he was able to simulate the flip-flop with gtkwave in another two lines. Compared to learning the complexities of VHDL or Verilog, Migen makes digital logic and FPGA programming a breeze.

[Jeff] has a great tutorial for building a D flip-flop with Migen, but we’d love to see some more complex examples of what can be done with this very cool tool. If you’re building (or have built) something with Migen, be sure to send it in and relate your experiences.

39 thoughts on “Designing Flip-Flops With Python and Migen

    1. So HDL’s do not need to be parallel in and of themselves, they just need to be able to describe circuits/connections and things which are parallel in nature. Migen code never gets run on the FPGA, it runs through a bunch of synthesis steps, first to FHDL, then to a standard HDL then through the specific toolchain out to the FPGA (I believe).

      So in other words, it doesn’t matter if Python is parallel or not… At all…

    1. Remember, it’s winter there and it seems most Americans think the apocalypse is coming based on the collective reactions on winter/snow I see online. I doubt their minds can even fathom putting something like flip flops (thongs if you live there, Oz?) on their feet.

      1. You have a point. It’s the opposite over here at the moment (yep, oz) stupidly hot. Seriously though, who’s up for the challenge of making an stl of a pair of flip flops/thongs with Python? :p

  1. I’d like to see the synth results of this. I personally am fine with VHDL syntax in all it’s absurdity, but new tools are always neat.

    The only issue I see arising is the difference in philosophy. With any FPGA work you’re not really writing code, you’re writing circuits. You can’t think of things in terms of sequence or read lines from top to bottom expecting things to function like code does sequentially. FPGAs are concurrent, something different even than parallel. Writing standard python for anything too complex will start getting into these differences. Depending on how good Migen is about warning users ahead of time it’ll start causing issues that are not very easy to troubleshoot.

  2. Firstly: Migen, Welcome to the world of FPGA development! And now on with my rant….

    There are lot of these tools – PSHDL, MyHDL and the whole HLS scene (usually C to FPGA logic). They mostly work by mapping your more compact high-level code to more generic HDL (VHDL/Verilog) code, that then goes through the usual EDA tools to get mapped to the FPGA.

    They restrict what you express in the HDL into a ‘safe’ set of constructs, which if you actually understood the underlying language you would most probably be using anyway (once you have built up the experience/understanding).

    It doesn’t change the fact that you are mapping your code to hardware, and some software constructs can not be transformed nicely – all loops must be bounded, all data sizes are fixed,

    But they do restrict what you can do with FPGAs. What do you do when your design fails to run at the clock speed you want? Or you need special I/O attributes on your signals? Maybe you need to drive tri-state logic? Can you manage clock routing, or ensure that clock domains are crossed safely? Can you infer dual-port memories and other goodies?

    This is much like poeple who say “I don’t need to use SQL, I have a GUI query builder”, or “Why do people still use C when they could be using Python?”. My own feeling was If there were dramatically better tools than VHDL and Verilog they would have been written and adopted all ready.

    Or maybe I am missing the point. Should HDLs become like assembler? Everybody knows that the layer exists, but most ignore it completely. If the level of abstraction was more complete I would in boots and all.

    1. I’m with your rant fellow HDL-guy. FPGAs are used where performance or parallelism is needed, otherwise most likely a microcontroller would do cheaper and easier. Everything else is a waste of ressources. Ok when hacking, but not acceptable in the professional sector.
      I’d dissagree on one point HDL will someday become what assembler is today in the software world. I just don’t beleve it will be tools like migen to replace it: you’d still need a specialized language just more high-level. In most cases modeling on register transfer level (RTL) is sufficient and greatly improves productivity. From there you could simply generate _readable_ HDL code and only look at it to improve performance and/or problems arise. One potential candidate for that is systemC. As I’ve heard many use it for early simmulation and some already use it to generate stubs for their designs.

    2. Actually, you are missing the point. Migen should be thought of as ‘generate’ on steroids, with a DSL of the synthesizable subset of Verilog.

      Migen really doesn’t restrict you in terms of synthesizable code. Sure, you can’t emit delays, but you can’t synthesize those either. You can directly instantiate FPGA primitives (LUTs) if you really want. For clocking – you’d just directly instantiate a DCM + whatever BUFGs/CLK muxes/etc that you need.

      With regard to optimization – I’ve done plenty of manual floorplanning before, and even written Verilog to the level of directly instantiating + LOCing LUTs for the critical path (ISE wouldn’t come up with the fastest design on its own). I can do a lot of the same with Migen; except I have the whole of python to automate things for me (I want a bunch of SLICEs LOCed in a column so I can do something weird with the carry chains? no problem).

      The place Migen really shines is automating the irritating parts of HDLs – the tedious things like doing address decoding and implementing registers for configuration busses. For example – with Migen I can simply use handy classes that are ‘CSR’ types, and use python to walk + collect all the CSRs in my design; create address decoding based on an existing header or in order found, and then generate all of the address decoding and read and write buses.

      Speaking as someone who has done medium-sized (8-10kLOC) HDL designs, some of which were highly optimized both with Verilog, and now Migen – I really recommend you give it a proper shot.

      In summary: Migen is not translating python into HDL – its using python to generate HDL.

      1. +1 to you Sir.
        Yes VHDL, Verilog and assembler share certain characteristics. There really is nothing wrong with a high level language – it certainly doesn’t stop you from creating assembler/Verilog where you need it.
        One day…. one day… (personally I’m a myHDL fan but I’m now looking at Migen).
        I’d love to see this integrated with the work Jack’s doing on Papilio and his libraries and the new SOCs like FreeSOC with CPLD layers on chip for local configuration.

        IMHO – Plenty of room in the middle ground…

      2. Thanks for the clarification! Now I think I confused it with something else. Some time ago there was a report about a python to HDL tool which would generate a CPU and compile python-code into machine code to run it on. That’s a silly approach IMO.

        From what you say, it sounds like migen is actually a usefull tool. Personally I thought systemC would win that race, since it’s a IEEE standard.

    3. First, MyHDL is very different from Migen or PSHDL. Like VHDL/Verilog, it embraces the event-driven paradigm and the idea that an HDL should support both sequential and concurrent semantics.

      In contrast, HDLs such as Migen and PSHDL are based on “everything is parallel” semantics and an artificial split between clocked and combinatorial logic. This is a step backward from Verilog/VHDL. This flawed concept has been tried by many failed HDLs before. The notable exceptions are the ones you know: VHDL, Verilog, SystemC, and MyHDL.

      Second, the restrictions you mention are RTL restrictions that have to be learned in any case, irrespective of the language. If you think about VHDL/Verilog as an RTL language, it is only because you have learned the tiny fraction that corresponds to RTL semantics, and you ignore all the rest.

      If one restricts HDL design to “describing hardware”, as you and the Migen guys seem to do, I agree that there is no compelling reason for a new HDL. For small and hobby projects, where errors are cheap, that may be fine. But for industrial projects it is not. Nothing is easy, but in industrial projects “describing hardware” is relatively spoken the easy part, and verification the hard part.

      It is no coincidence that most HDL advances in the past decade went to verification: constrained random, SystemVerilog, SystemC. What Python brings to the table is tremendous modeling power and agile techniques. There are signs that this may be the next wave in HDL verification techniques.

      MyHDL is unique in the sense that it gives you a unified environment that combines Verilog/VHDL-style RTL expressiveness with Python power for high-level modeling and verification.

    4. First, MyHDL is very different from Migen or PSHDL. Like VHDL/Verilog, it is based on the event-driven paradigm and the idea that HDLs should support both sequential and concurrent semantics.

      In contrast, HDLs such as Migen and PSHDL are based on “everything is parallel” semantics and the artificial separation of clocked and combinatorial logic. This is a step backward from VHDL/Verilog. This flawed concept has been tried by many failed HDLs before. The notable exceptions are the ones you know: VHDL, Verilog, SystemC, and MyHDL.

      Second, the restrictions you mention are RTL restrictions that have to be learned irrespective of the language. If you think about VHDL/Verilog as an RTL language, that is because you have learned the tiny fraction that corresponds to RTL semantics and you ignore all the rest.

      If one restricts HDL design to “describing hardware”, as you and the Migen guys seem to do, I agree that there is no compelling reason for a new HDL. For small and hobby projects, where errors are cheap, that may be fine, but in an industrial setting it is not. Nothing is easy, but in industrial projects “describing hardware” is relatively spoken the easy part. Verification is the hard part.

      It is no coincidence that most HDL advances in the past decade went to verification: constrained random, SystemVerilog, SystemC. What Python brings to the table is tremendous modeling power and agile techniques. There are signs that this may be the next wave in HDL verification.

      MyHDL is unique in the sense that provides a unified environment that combines VHDL/Verilog style RTL expressiveness with Python power for high level modeling and verification.

  3. This is disgusting.
    If you want to play with FPGAs learn an HDL. There is a reason that you use an HDL rather than something like C to do this.
    Learn and expand your horizons a bit instead of thinking you should just use the same way to solve every problem.

    Or if you must, load a soft core onto the FPGA and use it as a damn microcontroller.
    But please don’t do… this.

    I guess I’m just a crotchity old man at 30.

    1. Yep Matt, you are a crotchity old man… but recommendeding FPGA embedded microcontrollers?

      I didn’t realise that you were that old that you needed a mobility scooter to get out the door to yell “get off my lawn!” -)

      1. Well, I figure if some is masochistic enough to want to use Python with an FPGA they might as well use it on an interpreter running on an embedded microcontroller softcore on an FPGA. ;)

    2. There are actually lots of good reasons to embed a soft core into an FPGA… CPU’s are just better suited for certain tasks, they don’t need to be fast, but a soft core CPU can actually be more condense than the direct to circuit equivalent. A good example would be a TCP/IP stack or even a UART. Depending on the complexity of the stack, the easiest way to reuse the FPGA’s resources (and most efficient) is essentially to create a simple CPU (or use someone else’s).

  4. For those who are saying “this is disgusting” etc.
    1°) Have you tried it?
    and more importantly
    2°) Don’t you think that MAYBE the person who developed Migen was well aware of Verilog and VHDL and has really done very impressive projects with them and has therefore a good experience of traditional HDL languages.
    And don’t you think that MAYBE this guy having this good understanding and experience of traditional HDL languages, he then could have designed something BETTER and actually FIXED the issues he encountered while using traditional HDL stuff?

    Please, stop assuming that everybody else is stupid and has stupid ideas.
    Migen did not come down from the sky, it solves problems and it does it very well. Python gives you very pleasant syntactic sugar. Have a look at MiSoC which is kind of the equivalent of the verilog written SoC called “milkymist-ng”.

  5. A question to the author of the writeup, it appears that you consider Verilog or VHDL unreadable? Why is that, can you elaborate? Did you actually try to implement something in either of the main HDLs to get yourself accustomed to the syntax and general principles of hardware description?

  6. from a digital designer for a major ASIC IP company.

    DFF in 3 lines in synthesizable verilog.. written for reuse.. how is this hard?

    module 3_line_dff(input clk, input d, output reg q);
    always @ (posedge clk) q <= d;
    endmodule

    Want an asynchronous, active low reset? 3 lines.

    module 3_line_dff_async_rst(input rst_n, input clk, input d, output reg q);
    always @ (posedge clk or negedge rst_n) q <= d;
    endmodule

    etc.

    Verilog is easy.

    1. Writing a DFF in Verilog as you showed is pretty straight forward, the goal of Migen is not to write a DFF as the goal of C is not to write a printf(“hello, world\n”);

      Migen is very useful when you want to write a SoC or more complex digital designs (buses, dataflow programming, cores config registers etc).

  7. I’m a VHDL-2008 programmer who works on software defined radio. What I really like about VHDL is that it is so strongly typed. Sure, it’s more verbose, but it helps me catch a lot of errors that something like Migen would allow. I feel a lot more confident coding when I know exactly what type of signal vector I’m working with and how it is represented internally. I don’t see an easy way to get that in Migen without recreating a lot of existing VHDL libraries.

    Also, for anyone who hasn’t used VHDL’s 2008 extensions, I highly recommend trying them out, as they fix a lot of complaints people have about the language. There is much more support for generics and procedural generation. The fixed point and floating point libraries are excellent for signal processing as well.

  8. It already exists, it’s called SystemVerilog. Altera and Lattice support it directly, xilinx vivado does as well.

    Yes this migen thing is better for doing bus arbitration and what not, which is common in anything that’s not a blinking led. But with SV support now quite common, less reason to write code depending on somebody’s experiment.

Leave a Reply to pcf11Cancel reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.