Skip to content

JIT: (bug) Strength reduction computes int.MinValue % -1 in Gcd, faulting the JIT with an integer-divide overflow #133756

Description

@EgorBo

Minimal repro

using System;
using System.Runtime.CompilerServices;

public class Program
{
    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    public static int Test(int n)
    {
        int sum = 0;
        int i = 0;
        for (int c = 0; c < n; c++)
        {
            sum += i * 1431655765; // derived IV step = 3 * 0x55555555 = -1
            sum += i << 31;        // derived IV step = 3 << 31 = int.MinValue
            i += 3;
        }
        return sum;
    }

    public static int Main()
    {
        Console.WriteLine(Test(5));
        return 100;
    }
}

Expected

-10 (printed with DOTNET_JitEnableStrengthReduction=0)

Actual

JIT faults while compiling Test; the hardware #DE surfaces as
Unhandled exception. System.OverflowException: Arithmetic operation resulted in an overflow. at the Test call site, exit code 0xE0434352.

Notes

Two derived IVs with steps -1 and int.MinValue reach ComputeRephrasableIVByScaling (inductionvariableopts.cpp:2156), whose Gcd evaluates b % a = int.MinValue % -1 at inductionvariableopts.cpp:2059 — an unrepresentable signed quotient, lowered to idiv by MSVC. The gcd == 1 || gcd == -1 rejection happens only after the remainder. The int64_t instantiation has the same hazard.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

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