HDL for synthesis · Lesson 5 of 14

VHDL basics for FPGA design

Learn the VHDL you need for FPGA work: entity and architecture, numeric_std, std_logic, signals vs variables, processes, generics and type conversions.

beginner40 minUpdated Free

What you will learn

  • Write an entity and architecture for a clocked VHDL design using ieee.numeric_std
  • Explain the difference between signals and variables inside a process
  • Use process(all), rising_edge and the three kinds of concurrent signal assignment
  • Convert between std_logic_vector, unsigned, signed and integer without vendor packages
  • Translate a small design between VHDL and SystemVerilog

Before you start

  • Verilog and SystemVerilog for synthesis (lesson 4)

After this lesson you can read and write synthesizable VHDL, use the standard numeric packages correctly, and translate a small design between VHDL and SystemVerilog. The concepts are the same as in the Verilog lesson; the syntax and the type system are different. VHDL is strongly typed and verbose, and in exchange the compiler catches many mistakes that Verilog lets through.

Entity and architecture

A VHDL design unit has two parts. The entity declares the interface: generics and ports. The architecture describes the implementation. Here is the counter from lesson 4, written in VHDL:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity counter is
  generic (
    WIDTH : positive := 8
  );
  port (
    clk   : in  std_logic;
    rst   : in  std_logic;   -- synchronous, active high
    en    : in  std_logic;   -- count enable
    count : out std_logic_vector(WIDTH - 1 downto 0)
  );
end entity counter;

architecture rtl of counter is
  signal count_r : unsigned(WIDTH - 1 downto 0);
begin

  process (clk)
  begin
    if rising_edge(clk) then
      if rst = '1' then
        count_r <= (others => '0');
      elsif en = '1' then
        count_r <= count_r + 1;
      end if;
    end if;
  end process;

  count <= std_logic_vector(count_r);

end architecture rtl;

Points to notice:

  • Comments start with --. VHDL is not case sensitive, so COUNT and count are the same name.
  • (others => '0') is an aggregate that sets every element to '0', whatever the width. It is the VHDL equivalent of '0 in SystemVerilog.
  • The arithmetic happens on count_r, which is unsigned. The port stays std_logic_vector and the last line converts. This is a common convention: std_logic_vector on ports, numeric types inside.
  • Before VHDL-2008 an out port could not be read inside its own architecture, so code used an internal signal like count_r. VHDL-2008 allows reading out ports, but the internal-signal style is still common and works with every tool.

An entity can have several architectures. In practice you write one per entity, often named rtl for synthesizable code or sim for testbenches.

Libraries and packages

Every synthesizable file starts with the same three lines:

library ieee;
use ieee.std_logic_1164.all;   -- std_logic, std_logic_vector, rising_edge
use ieee.numeric_std.all;      -- unsigned, signed, arithmetic, conversions

std_logic_1164 defines the logic types. numeric_std defines unsigned and signed, which are arrays of std_logic with a numeric meaning, plus arithmetic, comparison, resize and conversion functions.

Older code and some vendor templates use ieee.std_logic_arith, ieee.std_logic_unsigned or ieee.std_logic_signed. Avoid them in new code:

  • They were written by Synopsys and placed in the ieee library by tool vendors. They are not part of the IEEE 1076 standard.
  • std_logic_arith declares its own signed and unsigned types. Using it together with numeric_std gives conflicting declarations.
  • std_logic_unsigned makes every std_logic_vector in the file behave as an unsigned number. The type no longer tells you how a vector is interpreted.

If you want arithmetic directly on std_logic_vector, VHDL-2008 provides the standard package ieee.numeric_std_unsigned. Most designers prefer explicit unsigned and signed types.

std_logic and its nine values

std_logic is not a two-valued bit. It has nine values:

ValueMeaningWhere you see it
'U'UninitialisedSimulation: a signal never assigned, often a missing reset
'X'Forcing unknownSimulation: two drivers in conflict, or unknown input
'0'Forcing 0Logic low
'1'Forcing 1Logic high
'Z'High impedanceTri-state outputs at I/O pins
'W'Weak unknownRare in FPGA design
'L'Weak 0Pull-down modelling
'H'Weak 1Pull-up modelling
'-'Don’t careLets synthesis choose the value

Hardware only has '0' and '1' (plus 'Z' at bidirectional pins). The other values help simulation show problems. A waveform full of 'U' after reset tells you a register was never initialised.

std_logic is a resolved type: if two drivers assign the same signal, a resolution function combines them, and a conflict shows up as 'X'. The unresolved type std_ulogic makes multiple drivers an error at elaboration instead. Some teams use std_ulogic for that reason; most code uses std_logic.

Concurrent statements

Statements in the architecture body, outside any process, are concurrent. Like Verilog assign statements, they all describe hardware that runs in parallel, and their order does not matter. There are three forms of concurrent signal assignment. The second and third examples below describe the same 4-to-1 multiplexer:

-- Simple assignment
z <= a and b;

-- Conditional assignment (when/else): a priority chain
y3 <= a when sel = "00" else
      b when sel = "01" else
      c when sel = "10" else
      d;

-- Selected assignment (with/select): a parallel mux
with sel select
  y2 <= a when "00",
        b when "01",
        c when "10",
        d when others;

The when ... else form checks conditions in order, like an if chain. The with ... select form must cover every possible value of sel exactly once, which is why it ends with when others. sel is std_logic_vector, so values such as "0X" exist and must be covered. The combinational logic lesson explains what each form becomes in hardware.

Processes

A process contains sequential statements (if, case, loops) that execute in order each time the process wakes up. The process as a whole is one concurrent statement.

Clocked processes and rising_edge

A clocked process has only the clock in its sensitivity list (plus an asynchronous reset if you use one) and tests for the edge:

process (clk)
begin
  if rising_edge(clk) then
    q <= d;
  end if;
end process;

rising_edge(clk) returns true only on a transition from '0' (or 'L') to '1' (or 'H'). The older idiom clk'event and clk = '1' is also true on a change from 'U' or 'X' to '1', so a clock that starts at 'U' produces a false edge when it is first driven high. Use rising_edge.

Combinational processes and process(all)

A combinational process must be sensitive to every signal it reads. If one is missing, simulation only re-evaluates when the listed signals change, while synthesis tools typically ignore the list and build the full logic. Simulation and hardware then disagree. VHDL-2008 fixes this with process (all):

process (all)
begin
  case sel is
    when "00"   => y <= a;
    when "01"   => y <= b;
    when "10"   => y <= c;
    when others => y <= d;
  end case;
end process;

Use process (all) for every combinational process, and compile with VHDL-2008 enabled (--std=08 in GHDL; Vivado, Quartus and other tools have a per-file or per-project language setting). As in SystemVerilog, every output must be assigned on every path through a combinational process, or synthesis infers a latch.

Signals and variables

VHDL has two kinds of object that hold values, and they behave differently inside a process.

  • A signal assignment (<=) is scheduled. The signal keeps its old value until the process suspends. This matches Verilog non-blocking assignment.
  • A variable assignment (:=) is immediate. The next statement sees the new value. This matches Verilog blocking assignment. Variables are declared inside the process and are only visible there.
process (clk)
  variable v : unsigned(7 downto 0) := (others => '0');
begin
  if rising_edge(clk) then
    s <= s + 1;   -- scheduled: s changes after the process suspends
    t <= s;       -- t gets the OLD value of s
    v := v + 1;   -- immediate: v changes now
    u <= v;       -- u gets the NEW value of v
  end if;
end process;

If s and v both start at 0, then after the first clock edge s is 1, t is 0, v is 1 and u is 1. t always lags s by one cycle; u always equals v.

What hardware does v become? It is read (v + 1) before it is written, so its value must survive from one clock edge to the next. Synthesis therefore builds a register for it. A variable that is always written before it is read becomes plain wiring. That rule is easy to get wrong, so a safe starting point is: use signals for everything that crosses a clock edge, and use variables only for intermediate values inside a calculation.

A signal assigned more than once in one process takes the last value assigned. This makes the default-value pattern safe:

process (all)
begin
  y <= (others => '0');           -- default
  if en = '1' then
    y(to_integer(unsigned(sel))) <= '1';
  end if;
end process;

Generics and instantiation

Generics are VHDL’s parameters. The counter entity has WIDTH : positive := 8. positive is an integer subtype that must be at least 1, so the tool rejects WIDTH => 0 at elaboration.

There are two ways to instantiate an entity. The older one needs a component declaration that repeats the entity’s interface:

architecture rtl of counter_top is

  component counter is
    generic (WIDTH : positive := 8);
    port (
      clk, rst, en : in  std_logic;
      count        : out std_logic_vector(WIDTH - 1 downto 0)
    );
  end component counter;

  signal low      : std_logic_vector(3 downto 0);
  signal high     : std_logic_vector(7 downto 0);
  signal low_wrap : std_logic;

begin

  low_wrap <= '1' when en = '1' and low = "1111" else '0';

  -- Component instantiation: needs the component declaration above.
  u_low : counter
    generic map (WIDTH => 4)
    port map (clk => clk, rst => rst, en => en, count => low);

  -- Direct entity instantiation: no component declaration needed.
  u_high : entity work.counter
    generic map (WIDTH => 8)
    port map (clk => clk, rst => rst, en => low_wrap, count => high);

  count <= high & low;

end architecture rtl;

Direct entity instantiation (entity work.counter) was added in VHDL-93. It needs no component declaration, so the interface is written once and cannot drift out of step. Use it for your own entities. Component declarations are still useful for blocks that have no VHDL entity in the library, such as a Verilog module in a mixed-language design or a vendor primitive. Check your tool’s documentation for the rules in mixed-language flows.

As in Verilog, always use named association (clk => clk) rather than positional association.

Type conversions

VHDL never converts types implicitly. std_logic_vector is just a bundle of bits; to do arithmetic you must say whether it is unsigned or signed. unsigned, signed and std_logic_vector have the same element type, so you convert between them with a type cast. Conversions to and from integer use functions from numeric_std.

FromToExpression
std_logic_vectorunsignedunsigned(v)
std_logic_vectorsignedsigned(v)
unsigned or signedstd_logic_vectorstd_logic_vector(u)
unsignedintegerto_integer(u)
signedintegerto_integer(s)
integerunsignedto_unsigned(i, N)
integersignedto_signed(i, N)
std_logic_vectorintegerto_integer(unsigned(v))
integerstd_logic_vectorstd_logic_vector(to_unsigned(i, N))
unsigned (width change)unsignedresize(u, N) (zero-extends)
signed (width change)signedresize(s, N) (sign-extends)

N is the result width. to_unsigned needs it because an integer has no width of its own.

Widths must match exactly in an assignment. Adding two 8-bit unsigned values gives an 8-bit result, and assigning that to a 9-bit signal is an error, not a silent extension. To keep the carry, resize first:

sum9 <= resize(a, 9) + resize(b, 9);   -- a, b : unsigned(7 downto 0)

Compare this with the Verilog averaging bug in the previous lesson: VHDL forces you to decide the width.

Integer signals are synthesizable if you constrain their range. signal n : integer range 0 to 99; becomes a 7-bit register. An unconstrained integer becomes 32 bits, which wastes logic if you only need a few.

Records and enumerated types

An enumerated type lists named values. It is the normal way to write state machine states:

type state_t is (IDLE, RUN, DONE);
signal state : state_t := IDLE;

The synthesis tool chooses the encoding (binary, one-hot or another) unless you constrain it. State machines themselves are covered in the state machines lesson.

A record groups related fields, like a C struct or a SystemVerilog packed struct:

type pixel_t is record
  r : unsigned(7 downto 0);
  g : unsigned(7 downto 0);
  b : unsigned(7 downto 0);
end record pixel_t;

signal px : pixel_t;
-- ...
px.r <= unsigned(din);
px.g <= x"80";

Types declared inside an architecture are only visible there. To use a type on a port, declare it in a package and use work.types_pkg.all; in every file that needs it.

Side by side: VHDL and SystemVerilog

The counter in both languages, line for line. The SystemVerilog version is the tested file from lesson 4.

module counter #(
    parameter int WIDTH = 8
) (
    input  logic             clk,
    input  logic             rst,
    input  logic             en,
    output logic [WIDTH-1:0] count
);
    always_ff @(posedge clk) begin
        if (rst)
            count <= '0;
        else if (en)
            count <= count + WIDTH'(1);
    end
endmodule
Download counter.sv
ConceptVHDLSystemVerilog
Interface and bodyentity + architecturemodule
Compile-time constantgeneric (WIDTH : positive := 8)parameter int WIDTH = 8
Internal wire or registersignal x : std_logic;logic x;
Clocked blockprocess (clk) + if rising_edge(clk)always_ff @(posedge clk)
Combinational blockprocess (all)always_comb
Register assignmentsignal <=non-blocking <=
Immediate assignmentvariable :=blocking =
All zeros(others => '0')'0
Hex literalx"A5"8'hA5
Concatenationa & b{a, b}
Case defaultwhen others =>default:
Unsigned numberunsigned(7 downto 0)logic [7:0]
Instanceu0 : entity work.counter port map (...)counter u0 (...)

The concepts map one to one. The main difference in daily use is typing: VHDL rejects a width or type mismatch, where SystemVerilog extends or truncates and leaves it to a linter.

Checking VHDL with GHDL

GHDL is a free, open-source VHDL simulator. Install it from your package manager or from the releases listed in the GHDL documentation. To analyse (compile) files with VHDL-2008 rules:

ghdl -a --std=08 counter.vhd counter_top.vhd

Analyse files in dependency order: packages first, then the entities that use them. ghdl -e --std=08 <entity> elaborates a top-level entity and ghdl -r --std=08 <entity> runs it, which is how you run a testbench. The testbenches lesson covers writing one.

Exercise

Translate a modulo-10 counter to VHDL

Write a VHDL entity counter_mod10 with inputs clk, rst (synchronous, active high) and en, an output count of type std_logic_vector(3 downto 0), and an output wrap. The counter counts 0 to 9 and back to 0 when en is high. wrap is high, combinationally, when en is high and the count is 9. Use numeric_std, rising_edge, and an internal unsigned signal.

Show solution
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity counter_mod10 is
  port (
    clk   : in  std_logic;
    rst   : in  std_logic;
    en    : in  std_logic;
    count : out std_logic_vector(3 downto 0);
    wrap  : out std_logic
  );
end entity counter_mod10;

architecture rtl of counter_mod10 is
  signal count_r : unsigned(3 downto 0);
  signal wrap_i  : std_logic;
begin

  wrap_i <= '1' when en = '1' and count_r = 9 else '0';

  process (clk)
  begin
    if rising_edge(clk) then
      if rst = '1' then
        count_r <= (others => '0');
      elsif wrap_i = '1' then
        count_r <= (others => '0');
      elsif en = '1' then
        count_r <= count_r + 1;
      end if;
    end if;
  end process;

  count <= std_logic_vector(count_r);
  wrap  <= wrap_i;

end architecture rtl;

count_r = 9 compares an unsigned with an integer, which numeric_std supports. The internal signal wrap_i lets the process read the wrap condition without reading an out port, so the code also works with pre-2008 tools.

Exercise

Write the conversions

Given signal a : std_logic_vector(7 downto 0);, signal n : integer range 0 to 255; and signal s : signed(15 downto 0);, write one assignment for each: (1) n gets the unsigned value of a; (2) a gets n + 1, wrapping at 256; (3) s gets a interpreted as a signed 8-bit number, sign-extended to 16 bits.

Show solution
n <= to_integer(unsigned(a));
a <= std_logic_vector(to_unsigned((n + 1) mod 256, 8));
s <= resize(signed(a), 16);

In (2), mod 256 keeps the value in range. Without it, to_unsigned(256, 8) truncates the result and a simulator reports a warning. In (3), resize on a signed value copies the sign bit into the new upper bits.

Summary

  • An entity declares the interface and an architecture describes the hardware. Concurrent statements and processes inside an architecture all run in parallel.
  • Use ieee.std_logic_1164 and ieee.numeric_std. Avoid std_logic_arith and std_logic_unsigned, which are not IEEE standard packages.
  • Signals update when the process suspends, like Verilog <=. Variables update immediately, like Verilog =.
  • Use rising_edge(clk) in clocked processes and process (all) in combinational ones, with VHDL-2008 enabled.
  • VHDL never converts types or widths for you. Keep the conversion table at hand and use resize to control widths.
  • Prefer direct entity instantiation with named association. Use enumerated types for states and records to group related signals.

Check your understanding

Pick an answer for each question, then check. Answers stay hidden until you submit.

1. Why should new VHDL code use ieee.numeric_std rather than ieee.std_logic_arith?
2. Inside a clocked process, s is a signal and v is a variable. The process executes s <= s + 1; t <= s; v := v + 1; u <= v;. Which statement is true?
3. Which expression converts an 8-bit std_logic_vector called a into an integer?
4. What does process(all) mean in VHDL-2008?

Further reading

Found a mistake or something unclear?Report a correction.