Home > Uncategorized > IL Code

IL Code

.Net languages compile to IL code which stands for Intermediate Language which corresponds to java byte code in the java world. An informative introduction to IL can be found here. An IL file can be compiled to an executable using ILAsm.exe; i.e.

ILAsm.exe test.il [/debug]

All programs that passes ILAsm are not runnable though and may cause an InvalidProgramException to be thrown. If this is the case running

PEVerify test.exe

might return useful information about the actual problem. More information about PEVerify can be found here. When your program is up and running you can attach to the process and debug it using visual studio just like any other program, assuming you passed /debug to ILAsm.exe.

Ok, now that we got the foundations the natural question to ask (doh) is how the previous entry might look like when hand coded in IL. Here it is:

.method static int32 solve(int32, int32) cil managed
{
    .maxstack 10   
    .locals init (int32, int32, int32, int32)  // maxLen, n, n’, c
   
    // maxLen = 0
    ldc.i4 0
    stloc.0
    // n = i
    ldarg.0
    stloc.1   
    // while (n <= j)
repeat_outer:   
    ldloc.1
    ldarg.1
    bgt done   
    // n’ = n
    ldloc.1
    stloc.2   
    // c = 1
    ldc.i4 1
    stloc.3    
    // while (n’ <> 1)
repeat_inner:   
    ldc.i4 1
    ldloc.2
    beq end_inner
    // c++
    ldc.i4 1
    ldloc.3
    add
    stloc.3
    // if n’%2 = 0
    ldloc.2
    ldc.i4 2
    rem
    ldc.i4 0
    beq case_even   
    // n’ = 3*n+1
    ldloc.2
    ldc.i4 3
    mul
    ldc.i4 1
    add
    stloc.2
    br repeat_inner
case_even:   
    // n’ = n’/2
    ldloc.2
    ldc.i4 2
    div
    stloc.2   
    br repeat_inner
end_inner:
    // n++
    ldloc.1
    ldc.i4 1
    add
    stloc.1
    // if c > maxlen
    ldloc.3
    ldloc.0
    ble repeat_outer
    ldloc.3
    stloc.0
    br repeat_outer
done:
    ldloc.0
    ret
}

Here is the entire program on skydrive:

https://skydrive.live.com/embedicon.aspx/.Public/test.il?cid=b46559fe42938868&sc=documents

Enjoy.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: