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.

Comments

  1. rasz says:

    programming inherently parallel hardware using one of the last languages that has no support for parallelism, nice ….

  2. Matt says:

    I read the title and expected to see the flip flops you put on your feet (thongs if you live over here). That would be a challenge with Python.

  3. mistahdoom says:

    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.

  4. Hamster says:

    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.

    • zondor says:

      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.

    • David Carne says:

      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.

      • MarkS says:

        +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…

      • zondor says:

        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.

    • Jan Decaluwe says:

      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.

    • jandecaluwe says:

      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.

  5. rj says:

    Having looked at the example, I really don’t see how this syntax is particularly more concise or easy to follow over either other popular HDL…

  6. Matt says:

    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.

  7. Yann Sionneau says:

    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”.

  8. svofski says:

    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?

  9. jpa says:

    OpenVizsla uses migen: https://github.com/openvizsla/ov_ftdi/tree/master/software/fpga

    But I am not sure if that is an argument in favor or against migen..

  10. fratbrofrat says:

    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.

    • Yann Sionneau says:

      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).

  11. commfreaks says:

    Flip flops should be made out of transistors. ANy other way it is a waste of silicon or power. Non-paralleled, non-crazy logic designs should not be made on VHDL if an arduino can do the same job

  12. Scott says:

    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.

  13. poop says:

    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.

  14. Jeffrey’s tutorial can also be done completely on EDA Playground — try Migen before installing it. As another example, here is a Migen synthesizable Divider design and testbench: http://www.edaplayground.com/s/example/485

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 96,401 other followers