Latch inference and how to avoid it in Verilog - Time & Space 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.
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.
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.
Consider how the hardware reacts as input signals increase.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 conditional checks, latch holds state |
| 100 | 100 conditional checks, latch holds state |
| 1000 | 1000 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.
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.
[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.
Understanding latch inference shows you know how hardware timing and behavior relate to code. This skill helps you write clear, predictable designs.
"What if we add an else branch that assigns a default value? How would the time complexity change?"