Electronic – How to avoid latches during synthesis

vhdl

I want to design a block of combinational logic using VHDL, but occasionally the synthesized result contains an unintentional latch.

What coding guidelines do I need to follow in order to avoid the synthesizer from inferring latches?

Example : in small segment of code, should I use if-else statements?

Best Answer

To avoid latches, you need to make sure all of your outputs are assigned at all possible branches of the code.

for example,

if a = '1' then
   b(0) <= '1';
else
   b(1 downto 0) <= "00";
end if;

would generate a latch, because in the first condition, the value of b(1) is not specified, so the compiler decided you wanted to keep the previous value of b(1) there. One way to write this that would not generate a latch is:

if a = '1' then
   b <= prev_b;
   b(0) <= '1';
else
   b(1 downto 0) <= "00";
end if;

...

if rising_edge (clk)
    prev_b <= b;
end if;

Here you explicitly state that b should retain it's old value, and then overwrite b(0) with the new value.

Another way is to give b a default value, as in @TomiJ's answer.

If you post the code you are getting a latch on, we could help you find the specific reason.