Sunday, September 08, 2002

C# Compiler Bug

Jason Hagar writes about an ugly C# compiler optimization bug:

1. When compiling the following code with CSC using the optimize switch, /o+ the compiler optimizes away certain IL instructions that permit the correct flow of the program.

2. Compile the code below with the optimize switch turned on. Then run the program.

3. The program prints out

Test
Shouldn't get here.

4. Instead the compiler should emit correct IL that bypasses the else statement.

5. I found this bug at (watch for wrapping): http://groups.google.com/groups?hl=en&lr=&ie=UTF8&threadm=eySvl16JCHA.2240%40tkmsftngp13&rnum=1&prev=/groups%3Fq%3DC%2523%2Bcompiler%2Boptimize%2Bbug%2Bgroup:microsoft.public.dotnet.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3DeySvl16JCHA.2240%2540tkmsftngp13%26rnum%3D1

The code is as follows:

using System;

class Test
{
 public static void Main()
 {
  object o = "test";
  if (o is string)
  {
   try
   {
    Console.WriteLine("Test");
   }
   finally
   {
    //Console.WriteLine("Finally.");
   }
  }
  else
  {
   Console.WriteLine("Shouldn't get here.");
  }
 
 }
}

Ouch! After doing some testing and looking at the produced IL code, it seems that the C# compiler always screws up when a try-finally block is the last thing inside an if-else statement. At the end of the finally block, instead of jumping over the else block, it jumps right into it.

I've updated the .NET Bug Registry with this info.

   11:26 PM

Content of this site is © Dejan Jelovic. All rights reserved.