Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hint to GCC that a line should be unreachable at compile time?

It's common for compilers to provide a switch to warn when code is unreachable. I've also seen macros for some libraries, that provide assertions for unreachable code.

Is there a hint, such as through a pragma, or builtin that I can pass to GCC (or any other compilers for that matter), that will warn or error during compilation if it's determined that a line expected to be unreachable can actually be reached?

Here's an example:

    if (!conf->devpath) {
        conf->devpath = arg;
        return 0;
    } // pass other opts into fuse
    else {
        return 1;
    }
    UNREACHABLE_LINE();

The value of this is in detecting, after changes in conditions above the expected unreachable line, that the line is in fact reachable.

like image 982
Matt Joiner Avatar asked Aug 01 '10 09:08

Matt Joiner


People also ask

What is werror in GCC?

-Werror= Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors.

Which option can be used to display compiler warnings?

You can use a #pragma warning directive to control the level of warning that's reported at compile time in specific source files. Warning pragma directives in source code are unaffected by the /w option.

Which GCC flag is used to enable all compiler warning?

gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.


2 Answers

gcc 4.5 supports the __builtin_unreachable() compiler inline, combining this with -Wunreachable-code might do what you want, but will probably cause spurious warnings

like image 51
Hasturkun Avatar answered Sep 23 '22 17:09

Hasturkun


With gcc 4.4.0 Windows cross compiler to PowerPC compiling with -O2 or -O3 the following works for me:

#define unreachable asm("unreachable\n")

The assembler fails with unknown operation if the compiler doesn't optimise it away because it has concluded that it is unreachable.

Yes, it is quite probably `highly unpredictable under different optimization options', and likely to break when I finally update the compiler, but for the moment it's better then nothing.

like image 33
Moritz Rathgeber Avatar answered Sep 25 '22 17:09

Moritz Rathgeber