Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc const and optimization across function calls

Tags:

c

gcc

Consider this code, compiled with gcc and -Ofast:

int f1(const char *p) {
    if (!p[0])
        return 0;

    f2(); //not inlined

    if (p[0]) { //not optimized out
        //do something
        return 0;
    } else {
        //do something else
        //not optimized out
        return 1;
    }
}

how can I get behavior where the second test and lower branch are optimized out (since p[0] is const and has already been tested)?

like image 247
gcc-question Avatar asked Apr 13 '26 16:04

gcc-question


1 Answers

There is no reason for the compiler to assume that function f2 may not modify what p is pointing to. The fact that p is defined as const char *p only tells the compiler that p cannot be used to modify the data it points to, not that the data itself is constant.

If you know the array is indeed not modified by function f2(), you can modify the code to not read it again and see if gcc will optimize accordingly:

int f1(const char *p) {
    char c = *p;
    if (!c)
        return 0;

    f2(); //not inlined

    if (c) { //should be always true
        //do something
        return 0;
    } else {
        //should be optimized out
        //do something else
        return 1;
    }
}
like image 85
chqrlie Avatar answered Apr 16 '26 09:04

chqrlie