0
0
Verilogprogramming~5 mins

Latch inference and how to avoid it in Verilog - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Latch inference and how to avoid it
O(n)
Understanding Time Complexity

When writing Verilog, sometimes unintended latches are created. This affects how the hardware behaves and how long it takes to run.

We want to understand how the design's execution steps grow when latches appear or are avoided.

Scenario Under Consideration

Analyze the time complexity of this Verilog code that may cause latch inference.


always @(*) begin
  if (enable) begin
    out = in1;
  end else begin
    out = out; // Explicitly hold value to avoid latch
  end
end
    

This code assigns out only when enable is true, otherwise it keeps previous value, causing a latch.

Identify Repeating Operations

Look for repeated actions that affect timing.

  • Primary operation: The conditional check inside the always block runs every time inputs change.
  • How many times: This check happens continuously as signals change, but the latch holds state without extra operations.
How Execution Grows With Input

Consider how the hardware reacts as input signals increase.

Input Size (n)Approx. Operations
1010 conditional checks, latch holds state
100100 conditional checks, latch holds state
10001000 conditional checks, latch holds state

Pattern observation: The number of checks grows linearly with input changes, but the latch itself does not add extra operations.

Final Time Complexity

Time Complexity: O(n)

This means the number of operations grows linearly with the number of input changes, but the latch holds state without extra repeated work.

Common Mistake

[X] Wrong: "Leaving out an else branch won't affect timing or hardware behavior."

[OK] Correct: Missing else causes latch inference, which changes hardware behavior and can cause unexpected delays or bugs.

Interview Connect

Understanding latch inference shows you know how hardware timing and behavior relate to code. This skill helps you write clear, predictable designs.

Self-Check

"What if we add an else branch that assigns a default value? How would the time complexity change?"