Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the number of variables alive in a for loop?

Tags:

c++

c

llvm

Consider the following piece of code:

int main() {
    int a = 0;
    int b = 1;

    for (int i = 0; i < 3; i++) {
        a = 2;
        int c = 1;
        int d = 3;
        d = a + c;
    }

   a = b+2;
}

In the piece of code above three variables have a lifespan contained in the body of the loop (i, c and d). I would like to be able to count the variables whose lifespan exists in the body of any given loop using LLVM (i.e. for this loop, my code should return 3).

I found the Live Variables Analysis, but I'm having trouble using it to find what I described above.

like image 450
Farhad Avatar asked Dec 29 '17 07:12

Farhad


1 Answers

Maybe this should just be a comment, but I couldn't express the code inline:

Only two variables have duration within the loop body. i is declared before the loop starts, and lasts until after the last execution of the loop body. In other words, c and d are constructed/destructed 3 times; after the third time they are destructed, then i is.

Thus, the for loop you wrote is equivalent to:

{
    int i = 0;
    while (i < 3)
    {
        a = 2;
        int c = 1;
        int d = 3;
        d = a + c;

    }
    i++;
}

The extra set of braces invokes block scoping; i goes out of scope and is destroyed outside of the for loop body, but before any subsequent code.

like image 160
stands2reason Avatar answered Oct 27 '22 08:10

stands2reason