Why compiler can not recognize what variables are volatile?

Hi,

If I compile the following program without -O*, it will print this.

$ ./main.exe
2
20

If I compile it with -O1 or any other number > 1, it will print this.

$ ./main.exe
2
10

The optimization clearly changes the semantics of the program. Why the
compiler can not figure out local_var2 is volatile on its own to
reduce the burdens of the programmers in having to figure out what
variables should be specified as volatile?

Thanks.

#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

int main() {
    volatile int local_var = 1;
    int local_var2 = 10;
    if(!setjmp(buf)) {
        local_var = 2;
        local_var2 = 20;
        longjmp(buf, 1);
    } else {
        printf("%d\n", local_var);
        printf("%d\n", local_var2);
    }

    return 0;
}

The question of explicitly modeling setjmp control flow has come up before; see http://lists.llvm.org/pipermail/llvm-dev/2017-November/118820.html . It's probably feasible, but I don't think anyone has actually attempted to implement it.

-Eli