Search code examples
ccompiler-optimizationc99dead-code

Dead code elimination in switch statement


Imagine that the following function exists in a static library (*.a, *.lib):

int func_foo(int i) {
    switch (i) {
    case 1:
        return foo_bar();
    case 2:
        return foo_baz();
    case 3:
        return foo_bat();
    default:
        return -1;
    }
}

If the user of this library calls this function and only passes in 1, will (or can) the compiler remove the calls to 2 and 3?

Will the compiler also remove the foo_baz() and foo_bat() functions if they're not referenced in any other functions (aka. dead code elimination)?


Solution

  • If Whole Program Optimization is enabled and func_foo is not marked to be exported from the output shared object library or DLL, a decent compiler like MSVC can and will remove such dead code. Therefore, the code will look like this (ignoring function inlining of course):

    int func_foo(int i) {
        return foo_bar();
    }
    

    Otherwise, if WPO is not enabled and func_foo has external linkage (the default), the compiler cannot remove the dead code. Finally, if WPO is not enabled and func_foo has static linkage, the compiler can remove the dead. In the last case, MSVC didn't perform the optimization. Other compilers may perform it though.

    Will the compiler also remove the foo_baz() and foo_bat() functions if they're not referenced in any other functions?

    Again it depends on whether WPO is on or off and if it's off, it depends on the linkage of the function. In all cases, the functions must not be exported. In addition, you have to tell the compiler explicitly to remove unreferenced functions by using compiler switches. For example, in MSVC, you have to use the /Gy compiler switch and the /OPT:NOREF linker switch.