Skip to content

InvalidProgramException: Common Language Runtime detected an invalid program (Debug-only) #124425

@Cheatoid

Description

@Cheatoid

Description

As the title says.

Reproduction Steps

#nullable enable
Console.WriteLine("Begin.");
Console.WriteLine(Foo(v: null));
Console.WriteLine("Finished.");

static string? Foo(System.Numerics.Vector2? v = null)
{
  return Bar(nameof(v), v);
}

static string? Bar<T>(string name, T? value)
{
  if (value == null) { return "(null)"; }
  string? valueStr;
  if (typeof(T) == typeof(System.Numerics.Vector2?))
  {
    var v = (System.Numerics.Vector2?)(object?)value;
    valueStr = v.HasValue ? $"[{v}]" : "(null)";
  }
  else if (typeof(T) == typeof(System.Numerics.Vector2))
  {
    var v = (System.Numerics.Vector2)(object)value!;
    valueStr = $"[{v}]";
  }
  else
  {
    valueStr = value?.ToString() ?? "(null)";
  }
  return valueStr;
}

dotnet run Program.cs -c Debug

Begin.
Unhandled exception. System.InvalidProgramException: Common Language Runtime detected an invalid program.
   at Program.<<Main>$>g__Bar|0_1[T](String name, T value)
   at Program.<<Main>$>g__Foo|0_0(Nullable`1 v) in Program.cs:line 8
   at Program.<Main>$(String[] args) in Program.cs:line 3

dotnet run Program.cs -c Release

Begin.
(null)
Finished.

🤔 😕 💻 💥

Expected behavior

I expected a valid CIL and no CLR crash. The program should produce the same output regardless of configuration, whether the program is compiled with <Optimize>false</Optimize> (which is the case for Debug configuration). In other words, it should work and print out:

Begin.
(null)
Finished.

Actual behavior

As the title says.
Common Language Runtime detected an invalid program. But this only happens when program is compiled in Debug configuration (<Optimize>false</Optimize> a.k.a. /p:Optimize=false).

Regression?

No response

Known Workarounds

My current workaround is to use pattern matching:

#nullable enable
Console.WriteLine("Begin.");
Console.WriteLine(Foo(v: null));
Console.WriteLine("Finished.");

static string? Foo(System.Numerics.Vector2? v = null)
{
  return Bar(nameof(v), v);
}

static string? Bar<T>(string name, T? value)
{
  if (value == null) { return "(null)"; }
  string? valueStr;
  if (value is System.Numerics.Vector2 vector2)
  {
    valueStr = $"[{vector2}]";
  }
  else
  {
    valueStr = value?.ToString() ?? "(null)";
  }
  return valueStr;
}

Configuration

dotnet --info

.NET SDK:
 Version:           10.0.103
 Commit:            c2435c3e0f
 Workload version:  10.0.103
 MSBuild version:   18.0.11+c2435c3e0

(On Windows 10 x64, but I think that's irrelevant.)

Other information

No response

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions