ECMA CLI spec: initobj instruction description for value types

206 Views Asked by At

The ECMA CLI spec has the following statement in the description for the initobj CLI instruction:

"If typeTok is a value type, then after this instruction is executed, the instance is ready for a constructor method to be called."

However, the following C# code (where S is a struct):

S s = default;
S s2 = new S();
S s3 = new S(5);

compiles to IL that looks something like this:

IL_0001: ldloca.s     s
IL_0003: initobj      S

IL_0009: ldloca.s     s2
IL_000b: initobj      S

IL_0011: ldloca.s     s3
IL_0013: ldc.i4.5
IL_0014: call         instance void S::.ctor(int32)

My question is, when would a compiler ever use initobj followed by calling the value type's constructor?

1

There are 1 best solutions below

0
Svirin On

If typeTok is a value type, then after this instruction is executed, the instance is ready for a constructor method to be called.

It means that a constructor can call a constructor after this instruction.

But, as you mentioned in the comments above there is no need to initialize the locals again before the constructor because of the localsinit flag on a method sig.

My question is, when would a compiler ever use initobj followed by calling the value type's constructor?

I can only find one case where I will require the compiler to use initobj, tell it not to use the localsinit flag. As of this moment, SkipLocalsInitAttribute should help you reproduce the case, but the implementation of this compiler feature has not started.