Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hint the C compiler (GCC or Clang) of possible variable value/range [duplicate]

Tags:

c

gcc

llvm

clang

In the following code, only one comparison will be done, because the compiler knows the conditions are exclusive and we will always enter the second condition as bar will be necessary > 32:

int foo(int bar) {
    if (bar <= 64)
        return 1;
    if (bar > 32) {
        printf("Too many elements");
    }
    return 0;
}

Now, imagine I know bar is always higher than 64. Because of the input of the system, configuration, or else. How can I hint the compiler to do no comparison at all, like if the if (bar <= 64) return was compiled, except it actually isn't kept in the final ASM.

Something like:

int foo(int bar) {
    @precond(bar > 64);
    if (bar > 32) {
        printf("Too many elements");
    }
    return 0;
}

Is my only solution to write eg a LLVM pass?

like image 364
MappaM Avatar asked Mar 01 '20 12:03

MappaM


1 Answers

You can use __builtin_unreachable in GCC:

if (bar > 32) {
  __builtin_unreachable();
}

__builtin_assume in Clang:

__builtin_assume(bar <= 32);

and __assume in MSVC:

__assume(bar <= 32);
like image 115
yugr Avatar answered Nov 19 '22 04:11

yugr