Skip to content

JIT: (bug) Loop stepped by checked(i - (-1)) is unrolled to one iteration, dropping an OverflowException #133583

Closed

Description

@EgorBo

Repro

using System;
using System.Runtime.CompilerServices;

internal static class Program
{
    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    private static int Test()
    {
        int count = 0;
        int i = 2147483646;
        while (i != 2147483645)
        {
            count++;
            i = checked(i - (-1));
        }
        return count;
    }

    private static void Main()
    {
        try
        {
            Console.WriteLine($"returned {Test()}");
        }
        catch (OverflowException)
        {
            Console.WriteLine("OverflowException");
        }
    }
}

Run with DOTNET_TieredCompilation=0.

Expected

OverflowException

i starts at 2147483646. The first iteration leaves i == int.MaxValue; the second evaluates
checked(int.MaxValue - (-1)), which overflows and throws. DOTNET_JITMinOpts=1 prints exactly
this.

Actual

returned 1

The optimizer decides the loop runs exactly once, so the second (throwing) update is deleted
entirely and Test returns normally. The unrolled iteration count is wrong for a != loop whose
step is a checked subtraction of a negative constant.

Platform

Windows x64, .NET 11 (dotnet/runtime main @ a0b86b1, Checked build). Requires
DOTNET_TieredCompilation=0; no special CPU features.

Activity

  1. added this to the 12.0.0 milestone on Sep 10, 2026
  2. added
    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
    on Sep 10, 2026
  3. dotnet-policy-service commented on Sep 10, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  4. self-assigned this
    on Sep 10, 2026
  5. AndyAyersMS commented on Sep 10, 2026

    @AndyAyersMS
    Member

    Not a new bug, fails the same way in .NET 7 through now.

  6. added a commit that references this issue on Sep 12, 2026
    47db904
  7. EgorBo commented on Sep 18, 2026

    @EgorBo
    MemberAuthor

    Affected SDK versions:

    • 8.0.425
    • 9.0.318
    • 10.0.401
    • 11.0.100-rc.2.26467.112
  8. added a commit that references this issue on Sep 18, 2026
    7231e97
  9. locked and limited conversation to collaborators on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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