Search code examples
loopsfor-loopverilogquartus

For loop goes into infinite loop when I use a variable as ending condition


I have a for loop that runs fine in Verilog. It looks like this:

for(j=0; j<=5; j=j+1)begin
    ...
end

but as soon as I change the 5 into a variable:

for(j=0; j<=m; j=j+1)begin
    ...
end

I get this error:

Error (10119): Verilog HDL Loop Statement error at alu.v(95): loop with non-constant loop condition must terminate within 250 iterations

I have m as a reg initialized as such:

reg [3:0] m = 5;

The reason I need to use a variable is I have an another variable that I want this loop to count to. I was getting the same error so I used this test value 'm' that should always equal 5. I'm not sure why this is happening. I would think the loop would end after 5, but for some reason it doesn't. Please help!


Solution

  • Verilog HDL is not programming language, like e.g. C or Python, but a Hardware Description Language (HDL). So the synthesis tool will unroll the for loop to a fixed hardware circuit, and for this it needs to know the (maximum) number of iterations in the loop.

    In your case it appears that the synthesis tool (Altera Quartus II/Prime), can't figure this out when the end condition is based on m as a register, so you have to rewrite this to each loop has a constant end condition, allowing the synthesis tool to unroll this to a fixed hardware circuit.