Search code examples
for-loopverilogvivado

For Loop In Verilog Does Not Converge


I'm attempting to using a for loop to count the repeated leading bit in a 32-bit number. For this, I am doing:

input[31:0] A;
output reg result;
Integer i;
for (i = 31; i > -1; i = i - 1) begin
    if (A[i] == 0) begin
        result = result + 1;
    end
    else if (A[i] == 1) begin
        i = -1;
    end
end

However, when I synthesize the program, I receive a warning saying that the program does not converge. Am I using the for loop wrong? Before this I used i >= 0 and even used a while instead but it doesn't change the outcome. I would appreciate any help. Should I set result to 0 before running the loop?


Solution

  • A[i] == 1 makes number of iterations non-deterministic and causes synthesis to fail. The way around it is letting the loop to unroll till the end and use a conditional variable to handle your calculations. Something like the following:

    input[31:0] A;
    output reg result;
    Integer i;
    reg flag;
    
    flag = 0;
    for (i = 31; i > -1; i = i - 1) begin
        if (flag == 0 && A[i] == 0) begin
            result = result + 1;
        end
        else if (A[i] == 1) begin
            flag = 1;
        end
    end
    

    I assume that it was some type of a flop logic, since in any case this would produce state elements. So, you need to use correct nbas for result and flag.