javacompiler-constructionjavacdead-codecode-elimination

javac code elimination capabilities


I'm having a hard time finding information about javac's code elimination capabilities:

I read that if you have something like the following, the if-statement will be eliminated:

static final boolean DEBUG = false;

if (DEBUG) System.out.println("Hello World!"); // will be removed

But how about this, for example:

static final int VALUE = 3;

if (VALUE > 9) System.out.println("VALUE > 9 ???"); // will this be removed?

Or this:

static final SomeEnum VALUE = SomeEnum.FOO;

if (VALUE==SomeEnum.BAR) System.out.println("Bar???"); // will this be removed?

Since it's very difficult/impossible to analyze a program to find all dead code (probably similar to the halting problem), I would imagine that there are only a few well-defined constructs (like the first example above), which javac will recognize and remove reliably. Is there a comprehensive list of these constructs?


Solution

  • assylias seems to have found the answer (let me just put it all together):

    Chapter "14.21. Unreachable Statements" of the JLS specifies, that, in general, any unreachable statement in the code is considered a compile-time-error, with the only exception being a special treatment of if-statements to specifically allow for conditional compiles.

    Therefore, the only construct that may result in code elimination (if the compiler chooses to do so!) is:

    if (compileTimeConstantExpression) {
        doThis(); // may be removed if compileTimeConstantExpression == false;
    } else {
        doThat(); // may be removed if compileTimeConstantExpression == true;
    }
    

    (the else-part is optional, of course)

    All other constructs that would allow for code elimination, like for example while (false) ..., are disallowed and cause a compile-time-error instead rather than resulting in conditional compilation.

    The definition for what constitutes an acceptable compileTimeConstantExpression can be found in chapter "15.28. Constant Expressions" of the JLS. Another great page with further examples can be found here: Compile Time Constants in Java

    Note: There is no requirement for a compiler to remove the "unreachable" sections of an if-stament. javac seems to do this reliably, but other compilers may not. The only way to know for sure is to check the output via decompilation, for example using javap -c as suggested by Jon Skeet.