What happens when an integer goes out of range in VHDL?

Russell picture Russell · Dec 18, 2013 · Viewed 7.4k times · Source

Let's say you have a signal defined as follows:

signal test_count : integer range 0 to 11;

Now if test_count ever goes below 0 or above 11 in simulation it will cause the simulation to crash immediately. What I'm wondering is what happens when this is synthesized? What happens if test_count is incremented past 11 or decremented below 0? Will the synthesis tools force the signal to wrap around? Notice that I chose an example that does not wrap back to 0000 easily.

Answer

Morten Zilmer picture Morten Zilmer · Dec 18, 2013

The tool assumes that the signal stays within range by design, so the case where this is not true, circuit can give any output on the internal bus used to implement the integer value. In this case for 0 to 11 it will be a 4 bit bus, and if the design does not keep the value in range 0 to 11, then even "illegal" values in range 12 to 15 may be presented in the circuit made by synthesis.

Also, in the case where the value is incremented beyond 11, should the counter then be saturating, or wrap? It is simply not defined.

The result from Altera QII of the counter with clear below:

architecture syn of mdl is  -- Counter with clear
  signal test_count : integer range 0 to 11;
begin

  process (clk_i) is
  begin
    if rising_edge(clk_i) then
      if clr_i = '1' then  -- Clear
        test_count <= 0;
      else  -- Increment
        test_count <= test_count + 1;
      end if;
    end if;
  end process;

  z_o <= std_logic_vector(to_unsigned(test_count, 4));

end architecture;

is shown as RTL result in this figure:

enter image description here

So in this case the synthesis result is a 4-bit counter with increment and clear value from mux as selected with signal clr_i, and without any range check. So if the design controlling the clr_i signal does not keep the value in range 0 to 11, it may output values outside the declared range of 0 to 11, thus even values in 12 to 15.