Christopher Diggins wrote:
> Hi All,
>
> Quick question about optimizing JVM bytecode. Suppose I have the
> following Java code:
>
> public static void main(String[] args) {
> int a[] = new int[42];
> for (int i=0; i < a.length; ++i)
> a[i] = 1;
> int sum = 0;
> for (int i=0; i < a.length; ++i)
> sum = sum + a[i] ;
> System.out.println(sum);
> }
>
> Would it be okay if I wrote an optimizer that pre-evaluated the code
> and just generated byte-code that output the value 42? In other words,
> did not even bother allocating the array, if it could avoid it? Would
> it violate the Java virtual machine spec, or the language spec? If it
> is okay, does anyone know of optimizers that do such a pre-
> evaluation?
Optimization appears to be legal according to the JLS with a few caveats:
1. All constant-expression code is strictfp
2. Application of the commutative and associative properties is strictly
forbidden.
3. There's more restrictions, see §15 for the full scoop.
The Java VM does not, to my knowledge, prohibit any optimization; the
JVM actually does hefty optimization.
I believe that there is a flag in javac that causes it to optimize, but
Sun doesn't recommend it because (I think) they found that the JIT
optimizer worked better with the unoptimized code. I do not know if that
optimizer did constant propagation though.
Many optimizers (gcc included) do use constant propagation and constant
folding--it is very trivial optimization.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth


|