Icarus verilog как использовать

При сколь-нибудь сложном проектировании с использованием verilog возникает необходимость симуляции, для проверки корректности работы блока схемы. Для простых случаев, раньше можно было воспользоватся встроенным в Quartus симулятором. Но он уже давно выпилен из Quartus IDE. Взамен нам предлагают использовать ModelSim. Проблема в том, что он бесплатный только для простых проектов. И еще одна проблема — его интерфейс слишком перегружен. И еще одна — сложность установки в linux.

К счастью существует open source альтернатива, в виде Icarus-Verilog, которая лишена вышеперечисленных недостатков.

Для windows, перейти по ссылке http://bleyer.org/icarus/, скачать дистрибутив, установить.

Для linux. Программа включена в стандартный ubuntu репозиторий.

На этом установка завершена. Давайте попробуем построить временные диаграммы делителя частоты, verilog файл которого показан ниже.

Важное замечание. На данный момент, icarus-verilog умеет симулировать только схемы, у которых определены начальные значения всех регистров, обычно путем сигнала reset.

Теперь нам нужен модуль тестирования. Вот он:

Для получения временных диаграмм нужна следующая последовательность команд:

Собственно теперь мы можем увидеть вывод работы симулятора в консоль. Для более наглядного представления в графическом виде, можно использовать программу gtkwave. Набираем в командной строке:

Появится окно, в котором слева есть окошко со списком сигналов проекта. Нужно выбрать необходимые сигналы и добавить их в график с помощью кнопки "Append".

This version of the FAQ is obsolete, and is preserved for historical reasons. For the actual FAQ (and other documentation) go to the Iverilog Wikia.com wiki. The Icarus Verilog home page has moved to http://iverilog.icarus.com.

Simulation Issues

My program compiles, but it complains about "system.vpi". So how do I run my program?

In very old versions of Icarus Verilog, you needed to set the environment variable VPI_MODULE_PATH to point to the system.vpi file that was installed when you installed Icarus Verilog. Normally, this is installed in "/ usr/local/lib/ivl " so you need that directory in your VPI_MODULE_PATH .

The situation has improved since then. Released version 0.2 and later include the module path in the generated code, so that the environment variable is not needed. However, you can still get the error message if you move the root of the installation, or if you try to run the compiled program to a system that doesn’t have the VPI modules.

As of version 0.5 and later, the situation is even better, assuming you are running a program compiled with the -tvvp target. A compiled program (in vvp format) can be copied around freely, and the local vvp command will use the local path to find the vpi modules.

However, complaints about user compiled VPI modules not being found still persist. The Icarus Verilogvvp run-time needs to be told to look for vpi modules other then system.vpi, and if the module is not installed in the system default location, it needs to be told where to look for user compile modules. The «-m» and «-M» modules are both pertinent, and need to be looked up in the vvp and iverilog man pages.

My program compiles under Solaris, but when I run it I get a relocation error with "system.vpi". So how do I run my program?

In this case, you are finding system.vpi fine, but there is some confusion with linkers under Solaris.

It seems that everybody has g++ installed on their Solaris systems, but typically the native linker is used, as opposed to the GNU ld linker. This is fine. The configure script assumes this case and forms up the right set of linker parameters for linking programs that iverilog compiles. However, if the GNU linker is installed, those link parameters are not correct, and VPI modules will fail to load.

If you have a Solaris system with the GNU linker installed, and you have this problem, edit the generated Makefile in the Icarus Verilog source, and replace the " rdynamic= " line with this:

You then need to recompile and reinstall the iverilog command. (No need to recompile ivl or ivlpp .) I’d gladly entertain suggestions for how to fix iverilog to cope with this situation at runtime, since the precompiled Solaris binaries are configured to assume the native linker, instead of the GNU linker.

Even better would be to fix g++ on Solaris to do the right thing with the — rdynamic flag, like it does on many other systems. Ah, well.

As of Icarus Verilog 0.5, these issues no longer apply as it no longer uses gcc in the backend. The easiest way to deal with Solaris, therefore, is to use Icarus Verilog 0.5 or later.

Why is it that "if (2’b01 & 2’b10). " doesn’t run the true case? Is Icarus Verilog Broken?

This is a popular coding error. You used the bit wise AND operator (&) where you meant to use the logical AND operator (&&). I no longer make this particular error in my own Verilog code because I received so many spurious bug reports about this that it’s burned into my brain:-) Icarus Verilog has its share of bugs, but this is not one of them.

My "always" statement doesn’t trigger at time 0. Is Icarus Verilog broken?

In this case, the bug is most likely in your program, and is probably the most common and unnoticed error in the entire history of Verilog use. Your program probably looks something like this:

reg [7:0] a, b, c;
always @(a or b) c = a + b;
initial begin a = 1; b = 2; end

This is in fact a race condition at time zero. James Lee has this to say:

[T]he bug is the race between the always at time zero getting to the @ and the initial setting the values. A #1 in the initial block before changing a or b should do the trick.

I think that most verilog simulators have some sort of trick to catch the changes at time zero.

The IEEE 1364-1995 standard is also clear on this issue: the given example leaves c with an unpredictable value at time 0. This is a frightfully common mistake, we’ve all done it. It often goes unnoticed because compilers often start threads from first (in the source file) to last. It just so happens that Icarus Verilog, by a detail of implementation, starts threads from last to first.

Читайте также:  Klixon ys11a45b 005 t принцип работы

What people don’t typically realize is that «#0 » has a well defined meaning. I suggest that you preceed statements in your initial processes with a «#0» to eliminate the race, like so:

reg [7:0] a, b, c;
always @(a or b) c = a + b;
initial #0 begin a = 1; b = 2; end

This improved version doesn’t have a time-0 race—if the initial block is scheduled ahead of the always block, the «#0» will tell the scheduler to first yield to all other threads, then continue.

I want pretty pictures (wave forms) of my simulation run.

Well, you are in luck. As of version 0.2, Icarus Verilog supports VCD output. You need to learn about the $dumpfile and $dumpvars system tasks from any good Verilog reference, and use them. The output VCD dumps can be viewed by commercial wave form viewers, and my personal favorite, GTKWave. Note that gtkwave development has changed hands.

I also keep a version of GTKWave that is known to work with the most recent version of Icarus Verilog here: . This directory includes source and a variety of precompiled binaries. The release mirrored on Icarus.com is a 1.X release, whereas the current development version is 2.X.

VPI Issues

How do I compile my VPI module?

The easiest way to do that is use the iverilog-vpi command. This handles your platform details, so all you need to do is give it the source C files, a it gives back a vpi module. See the iverilog-vpi manual page for details.

How do I install my VPI module?

You don’t need to (You can use the -M flag to vvp to locate it) but if you wish, you can copy it to the /usr/lib/ivl directory, or /usr/local/lib/ivl directory, depending on where Icarus Verilog was installed on your system.


NOTE: Most of the synthesis capabilities of Icarus Verilog appear after the v0.1 stable release. Although the 0.1 release can produce XNF files, its ability to synthesize logic from behavioral code is not in general powerful enough to use. The development snapshots leading up to v0.2 have improved the situation, so the following answers will be describing development and 0.2 or later versions. Starting with v0.7, synthesis is greatly improved again, this time to a professional level. There are still significant limitations in synthesis, but the greatest remaining issue is code generator for various target types.

You mean XNF synthesis works?!

Sure does. It’s still under development, so version 0.1 doesn’t officially support XNF synthesis, but version 0.2 and later do. See the x nf.txt file distributed with Icarus Verilog.

As of 0.6, Icarus Verilog also supports more general synthesis with the -tfpga code generator, described in the fpga.txt file. This also starts the move towards EDIF as the netlist format. Most (all?) FPGA vendors and ASIC P&R tools support EDIF as an input netlist format, so the change is inevitable. However, the real problem is not the netlist format, but the detailed code generator that supports the technology family in question.

Currently, FPGA synthesis is weighted heavily towards Xilinx devices, partly because of the support that I have received from Xilinx. Other device families can be supported as well if I were to receive similar support from the vendor, or other motivated entity with the proper resources.

What else do I need to make working Xilinx Designs?

Besides Icarus Verilog, you will need Alliance or Foundation software packages from Xilinx to place-and-route and to generate configuration bit streams. Unfortunately, Xilinx does not yet directly support Linux so you will have to copy the XNF and NCF files that Icarus Verilog generates onto a supported (in other words, «Windows») platform.

Rumor has it that Xilinx Alliance tools for Windows can be run under Linux using WINE. Only the command line tools are reported to work this way, but this should be enough to get you a bit file. If you feel daring, try this: .

As of RedHat 7.2 and Xilinx ISE 4.2i, Xilinx claims to support the back-end tools via the WINE application layer. There are Xilinx APP Notes on the subject (search the Xilinx web site for details) but in the real world this support draws mixed reviews. I personally have not been able to get it to work, but others claim success. However, It seems clear that the best path is to continue reminding Xilinx that we really want native Linux support.

How do I make XNF macros?

Icarus Verilog will automatically generate the EXT records needed for XNF linkers to include XNF code generated by Icarus Verilog. All you do is synthesize a module that has ports, an the generated XNF will include the PIN= attributes to make the ports visible outs >xnf.txt file for details.

How do I make EDIF macros?

As of 0.6, Icarus Verilog is moving towards the more sophisticated -tfpga code generator. As with the older XNF code generator, the ports of a root module are made into interface ports of an EDIF macro. As ov v0.7, the sqrt-virtex.v example is bundled as an example of how to make parts and macros using the -tfpga code generator.

I figured out how to make flip-flops, but how do I initialize them?

CLB flip-flops can be initialized to 0 or 1. You can force them to take on a specific value by assigning the desired value in an initial statement, like so:

Note that this example uses the 1364-2000 reg initial assignment syntax, but you can get the same effect like so:

Either way, the compiler will detect the initial assignment to the flip-flop output and will generate the correct INIT= parameter to the XNF device.

How do I make a RAM in a CLB?

As of released version 0.2, Icarus Verilog can recognize memories as RAMS and generate XNF synchronous RAM devices, if:

The memory assignment is a clocked behavioral assignment,

Reads from the memory are asynchronous,

And all the address lines are shared by the read and write statements.

Icarus Verilog will try to generate the smallest ram needed to support the memory. If the memory has width, then enough rams will be generated to accomodate the data width.

I want to work entirely within Linux? How do I do PAR?

News FLASH! As of Foundation 4.2i, Xilinx officially claims Linux support, although only for the X86 architecture. Foundation 4.2i is supposedly supported on RedHat 7.2 using the Wine appications layer, with future plans for a native port of the newer ISE tools. For the word from Xilinx, go here: .

Читайте также:  Функция smart tv в телевизорах что это

Why XNF and not EDIF?

NOTE: This answer (and indeed the question itself) is obsolete. Icarus Verilog synthesis now favors using EDIF.

Xilinx has found a way to be difficult. While the XNF specification is available for free download, the Xilinx libraries for EDIF are not. However, although XNF is supposed to be obsolete, there are some big name design entry tool vendors that haven’t made the change over to EDIF so XNF will be around for a while.

As of 0.6, EDIF is supported with the -tfpga target. In fact, that target now supports more of the Virtex features then the XNF target, and newer part types will only be added to the fpga target, not the xnf target.

During the course of 0.7 development, Xilinx has become considerably more helpful, so as long as this support keeps up, the only limitation remaining is the time needed to do the work of supporting the various part types. Keep following the geda-dev mailing lists for the latest progress.

Another advantage of the -tfpga target is that other vendor’s PAR tools can also be supported similarly, and that is in the works. It is low priority, however, because other FPGA vendors lack UNIX/Linux support.

About Icarus Verilog In General

Are there any precompiled binaries?

Yes, for Linux (i386 and alpha), Solaris/SPARC, NetBSD/everything and Windows. Look in . In some cases, there are actually pointers to other sites that store and maintain the actual binaries. I personally only maintain the Linux and Windows binaries. The others are available thanks to the generous efforts of volunteers who take the time to compile and test on their favorite platform. These are generally only of the stable release. The development snapshots are distributed in source form only.

The symbol «lexor_keyword_code» is undefined when I compile ivl.

The source file l exor_keyword.cc is actually generated from lexor_keyword.gperf . The program that does this conversion is called gperf and you need version 2.6 or later. (I use version 2.7.) Linux distributions generally include gperf , although it is not necessarily installed. It is also available for NetBSD and FreeBSD and all the other UNIX variants. Check the version of an installed gperf with the command « gperf —version ».

If you discover that you are missing gperf, or that your installed version is out of date, you must install the correct version, then remove the lexor_keyword.cc file so that it is regenerated. Then just remake and the compile and link should complete properly.

All this is to a degree moot, however, because even snapshots should come with a premade version of lexor_keyword.cc . You will only need to create this file for yourself if you are accessing the source via CVS, or if you are editing the lexor_keyword.lex source file.

I have RedHat 7.0 and Icarus Verilog won’t compile. What’s wrong?

There have been many problems with the gcc 2.96 compiler that RedHat included with the 7.0 release. Some of those problems impacted Icarus Verilog. The end result is that you need snapshot 20001104 or later to compile on RedHat 7.0. The stable versions 0.4 and later also work. There are other issues regarding 2.96 on the gcc home page. In particular, look here; but be aware that the problem is even worse then this page clearly states. In any case, if you must upgrade to RedHat 7.0, be prepared to live with recent snapshots of Icarus Verilog.

RedHat has been informed of problems that are tickled by Icarus Verilog. If you care, check out buzilla , and look for bug number 20267 . As of Icarus Verilog 0.6, compile problems have been dealt with.

What about gcc 3.X?

The 0.5 release (and later) compiles with gcc 3.0. The source before 0.5 does not compile with gcc 3.0, but there’s no real reason to use anything older then the 0.5 release anyhow. The latest C++ from gcc still (as of v0.7) leads to a warning about support for , but it still works, and the post-0.7 development cycle should deal with it.

What about bison 1.30?

Somewhere between version 1.28 and 1.30 of bison, the powers that maintain bison made several incompatible changes: they changed the name of output files that are generated, and they changed the structure of the default yylloc type, and they changed a few other things. Many of these changes cause build problems with Icarus Verilog.

The typical bug report related to this is here: This bug report includes the fix needed, in the form of a patch to the 20011230 snapshot. Snapshots after 20011230 are fixed to account for the new bison, and the 0.6 release also includes the needed changes.

And then they changed it yet again, and the v0.7 release includes even more changes to account for different versions of bison. As of the 0.7 Release, most versions of bison compile Icarus Verilog, so I think I’ve got it licked. At least for now.

Parse.cc won’t compile. The compiler crashes. What’s up with that?

If you are compiling Icarus Verilog, you are probably aware that it is written in C++. Unfortunately, the parse.cc file (which is generated from parse.y by bison) tickles some performance problems in the GNU C++ compiler. So, you need either a lot of memory (a lot of memory) or plenty of swap and lots of patience to compile parse.cc. It does work, though. If your compiler crashes, it is probably from lack of virtual memory.

If umpteen gazillion megabytes is somewhat out of your reach, and prayers to the gcc gods/godesses come to naught, try convincing the compiler to not optimize when compiling this file. You can get the desired effect by compiling just this file with the command:

Note that once you get past compiling ivl, its run time demands are not so great.

After version 0.5, this problem seems to have largely vanished.

I get "virtual memory exhausted" when compiling the compiler.

See above. You’re probably having trouble with parse.cc, which is generated from parse.y. What can I say, you need more ( lots more) memory. Try adding 256MB of temporary swap or use the technique in the previous FAQ entry. Or try precompiled binaries for your platform. If you are compiling under cygwin32, see the cygwin.txt text file.

The Makefile is broken, and I’m on *BSD. What’s up with that?

Icarus Verilog makefiles make use of GNU make extensions. BSD based systems such as NetBSD and FreeBSD tend to have a BSD style make program. In standard FreeBSD systems, the GNU make program is available as gmake . That may be true with NetBSD as well. Use that and you will be fine.

Читайте также:  Что значит адрес регистрации карты

For systems like Solaris, you may need to download GNU make from the usual GNU sites.

Does it run under Windows?

Yes, as of the 0.5 release. Each release directory includes a Windows subdirectory which includes the installer that you use to install a precompiled binary of the 0.5 release. The snapshots can also be compiled yourself. The instructions for the compile are in the mingw.txt file.

Note that compiling with the MSVC++ compiler is not supported, and never will be. There is no point. Also, the Cygwin support is being deprecated for the mingw port, although as explained in the mingw.txt file, you will need Cygwin if you plan to compile Icarus Verilog .

There is also an alternative source for Icarus Verilog for Windows, at . This package is managed by Pablo Bleyer Kocik.

I get Linker errors linking system.vpi under Cygwin. How do I fix it?

When compiling under recent binutils installed, you will see complaints about _bss_end__ and _bss_start__ and some similar symbols when trying to link system.vpi. This appears to be a problem with the binutils package. binutils-20001029 does not play nice with Icarus Verilog . Downgrade to the 20000625 version and you should be OK for now.

The ivl-bugs PR#58 is available to track this particular issue.

Does it run under Mac/OS?

The MacOS (before macosX) port is obsolete. There are ancient precompiled binaries available for download from the Icarus Verilog FTP site, as tarballs and hqx files. There is also a README.txt file that describes how to install and run the Macintosh port. Note that this is done by a volunteer, and I have no idea how he accomplished this little miracle.

Mac O/S X, however, is in good shape and compiles Icarus Verilog out of the box. There are some minor bits of preparation needed to compile on MacOSX, so see the " macosx.txt " file in the source distribution.

This page is Copyright 2001-2004 Stephen Williams

После некоторых раздумий я решил написать статью о симуляции Verilog проектов с помощью пакета программ icarus-verilog . Мне кажется, что это лучший способ «быстро попробовать» возможности симуляции. Конечно, среда симуляции ModelSim компании Mentor Graphics (или ModelSim-Altera Edition) — это мощное средство, но освоить ее несколько труднее.

Сейчас мы быстренько скачаем из интернета icarus-verilog , установим его и попробуем что нибудь просимулировать.

Первое, что нужно сделать – это посетить сайт http://www.icarus.com/eda/verilog/ — отправная точка для изучения Icarus Verilog . Это свободный проект, то есть при желании можно даже посмотреть исходные тексты всех программ, и компилятора и симулятора Verilog . Здесь есть ссылки на документацию и откуда скачивать файлы для установки. Конечно, есть пакеты программ и для Linux и для Windows.

Оттуда я перехожу по ссылке Pablo Bleyer Kocik’s Icarus Verilog Windows packages (off-site), которая ведет меня на станицу скачивания программы для операционной системы Windows. Вы будете приятно удивлены – размер файла для скачивания составляет около 6 мегабайт! Для ModelSim , например, размер будет более 500Мб!

Выкачиваем и устанавливаем!
По умолчанию программа устанавливается в папку c:iverilog и установщик сам прописывает пути к исполняемым файлам.

В этой же папке есть несколько коротких но понятных инструкций, как пользоваться компилятором и симулятором (правда на английском языке).

Теперь напишем 2 модуля на языке Verilog :

  1. Модуль 8-ми битный счетчик с возможностью загрузки.
  2. Тестбенч – модуль для тестирования первого модуля счетчика.

Для чего применяется такая методика из раздельных модулей – тестируемого и тестирующего? Первый модуль – это тот, который мы в будущем хотим компилировать для чипа. Для него важно быть простым и компактным. А второй модуль, тестирующий (их называют testbench ) моделирует внешние сигналы, которые подаются на тестируемый модуль и проверяет выходные сигналы из него.

Тут надо заметить, что написание тестбенчей – это в каком-то смысле искуство. Получается мы пишем программу, модуль. Для тестирования этой программы мы пишем вторую программу – модуль тестбенч. Мы можем ошибиться как в первой программе, так и во второй или в обеих сразу! Ведь в любой программе возможны баги. Разработчик может думать, что он все сделал правильно и просимулировал и увидел результат какой хотел, но на самом деле проект может остаться неработоспособным Но не нужно пугаться. Будем двигаться дальше.

Итак, вот мой счетчик, тестируемый модуль:

module counter (
input wire reset,
input wire clk,
input wire [7:0]wdata,
input wire wr,
output reg [7:0]data
always @ ( posedge clk or posedge reset)
if (reset)
data else
if (wr)
data end
data endmodule

А вот тестбенч, тестирующий модуль. Чтобы он был более понятным пожалуйста прочитайте предыдущую статью про System Tasks.

reg reset, clk, wr;
reg [7:0]wdata;
wire [7:0] data_cnt;

//устанавливаем экземпляр тестируемого модуля
counter counter_inst(reset, clk, wdata, wr, data_cnt);

//моделируем сигнал тактовой частоты
#10 clk =

//от начала времени.

clk = 0;
reset = 0;
wdata = 8’h00;
wr = 1’b0;

//через временной интервал "50" подаем сигнал сброса
#50 reset = 1;

//еще через время "4" снимаем сигнал сброса

//пауза длительностью "50"

//ждем фронта тактовой частоты и сразу после нее подаем сигнал записи
@( posedge clk)
wdata = 8’h55;
wr = 1’b1;

//по следующему фронту снимаем сигнал записи
@( posedge clk)
wdata = 8’h00;
wr = 1’b0;

//заканчиваем симуляцию в момент времени "400"
#400 $finish;

//создаем файл VCD для последующего анализа сигналов

//наблюдаем на некоторыми сигналами системы
$monitor($stime,, reset,, clk. wdata,, wr,, data_cnt);

Icarus-verilog может скомпилировать их в свой «исполняемый» формат. Для этого в командной строке набираем команду:

>iverilog -o qqq counter.v tcounter.v

Iverilog – это компилятор, который транслирует исходный код Verilog в файл специального формата для симуляции проекта, или в файлы других форматов netlist для последующей обработки другими программами.

После выполнения этой команды у нас появился новый файл «qqq». Мы будем использовать его для симуляции. Запускаем в командной строке симулятор из комплекта icarus-verilog :

>vvp qqq

Вот мы и видим весь вывод симулятора на консоль:

Здесь видно, как значение счетчика увеличивается с каждым фронтом сигнала clk .
Видно, что до возникновения сигнала reset значение счетчика неопределено.
Видно, что в момент времени "110" устанавливается сигнал wr , а в момент времени "130" происходить запись нового значения в счетчик.

Если вы теперь захотите увидеть сигналы в графическом виде, то это тоже возможно. В результате симуляции у нас появился новый файл "out.vcd" — это Value Change Dump File . Для его просмотра есть инструмент gtkwave . Он есть здесь же в комплекте установленного нами icarus-verilog .

Набираем в командной строке:

>gtkwave out.vcd

И появляется вот такое окно (кликните на картинку, чтобы увеличить ее):

Слева есть окошко со списком сигналов проекта. Нужно выбрать необходимые сигналы и добавить их к просмотру кнопкой " Append ".
Справа – окно графического представления сигналов. Можно менять масштаб просмотра и скролировать вдоль шкалы времени.

Вот так можно проводить функциональную симуляцию проектов написаных на языке Verilog .