Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# compiler emit additional OpCodes in IL?

Tags:

c#

cil

opcode

il

If I've a method Multiply defined as:

public static class Experiment
{
    public static int Multiply(int a, int b)
    {
        return a * b;
    }
}

Then why does the compiler emit this IL:

.method public hidebysig static int32 Multiply(int32 a, int32 b) cil managed
{
    .maxstack 2              //why is it not 16?
    .locals init (
        [0] int32 CS$1$0000) //what is this?
    L_0000: nop              //why this?
    L_0001: ldarg.0 
    L_0002: ldarg.1 
    L_0003: mul 
    L_0004: stloc.0          //why this?
    L_0005: br.s L_0007      //why this?
    L_0007: ldloc.0          //why this?
    L_0008: ret 
}

As you can see, it also contains some additional OpCodes which don't make sense to me, when in fact I expect the following IL:

.method public hidebysig static int32 MyMethod(int32 a, int32 b) cil managed
{
    .maxstack 16
    L_0000: ldarg.0 
    L_0001: ldarg.1 
    L_0002: mul 
    L_0003: ret 
}

which does the very same thing.

So the question is, why does the compiler emit additional OpCodes in IL?

I'm using Debug mode.

like image 428
Nawaz Avatar asked Oct 06 '11 09:10

Nawaz


People also ask

Why do we use symbol in C?

The most common use of symbols by programmers is for performing language reflection (particularly for callbacks), and most common indirectly is their use to create object linkages. In the most trivial implementation, they are essentially named integers (e.g. the enumerated type in C).

What does -> mean in C language?

An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below.

Is C still used in 2022?

C is one of the earliest and most widely used programming languages. C is the fourth most popular programming language in the world as of January 2022. Modern languages such as Go, Swift, Scala, and Python are not as popular as C. Where is C used today?

Why C is so fast?

Another reason is closeness of C to the Assembly language, in most of the cases its instructions directly map to assembly language, C is only one or level two levels of abstraction away from assembly language while Java is at minimum 3 levels abstraction away from assembler.


1 Answers

Mostly for debugging & breakpoint support; See an answer here: Why are these nop instructions in my debug build?

like image 106
Simon Mourier Avatar answered Sep 24 '22 03:09

Simon Mourier