In a stack-based intermediate language such as CIL or Java byte code, why do local variables exist? You can just use only the stack. It may not be that easy for artificial IL, but the compiler can certainly do it. But my C # compiler does not.
Both the stack and local variables are private to the method and disappear from the scope when the method returns. Thus, it could have nothing to do with side effects visible from outside the method (from another thread).
The JIT compiler would eliminate load and storage for both the stack slots and local variables when generating machine code, if I am right, so the JIT compiler also does not see the need for local variables.
On the other hand, the C # compiler generates loads and stores for local variables, even if compilation with optimizations enabled. Why?
Take, for example, the following contrived code example:
static int X() { int a = 3; int b = 5; int c = a + b; int d; if (c > 5) d = 13; else d = 14; c += d; return c; }
When compiling in C # with optimization, it produces:
ldc.i4.3
Pay attention to loads and storages on four local variables. I could write the same operations (without taking into account the obvious optimization of constant propagation) without using any local variables.
ldc.i4.3
It seems right to me, and much shorter and more efficient. So why do stack-based intermediate languages โโhave local variables? And why does the optimizing compiler use them so widely?
java c # bytecode local-variables
Virtlink
source share