.netvirtual-machineclrstack-based

.NET MSIL: How commands detect size of operands?


There is a single add command in MSIL to add two arguments (pop from stack, add, push into stack). How does it know whether it has to pop 2 bytes or 4 or 8 bytes?

In java different bytecodes (fadd, dadd, iadd, ...) but how do they handle this in .NET?


Solution

  • Java bytecode was optimized to be executed by an interpreter, early JVMs did not have Hotspot yet. .NET msil was designed from day one to always be jitted, no special opcodes for different operand types were necessary.

    The jitter knows the operand type from the stack state. Whatever opcode pushed a value onto the stack indicates the type as well. Say an Opcodes.Ldarg_0, the jitter knows the type from the method signature. Keeping track of the stack state is something you never want to have to do in an interpreter, it slows down code execution significantly, a jitter only has to do it once.