Repository navigation
Description
Description
Vector128.Min and Vector128.Max are documented to propagate NaN. When both operands are compile-time constants, the JIT emits a bare vminpd/vmaxpd with none of the NaN/signed-zero compensation it emits for non-constant operands. Because vminpd returns its second source when either input is NaN, the result disagrees with the same expression written with opaque operands.
This is a regression in .NET 10. On .NET 9 the same expression is fully constant-folded to the correct value.
Reproduction Steps
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
class Repro
{
[MethodImpl(MethodImplOptions.NoInlining)]
static Vector128<double> Opaque(Vector128<double> v) => v;
static string Bits(Vector128<double> v) =>
$"[0x{BitConverter.DoubleToUInt64Bits(v[0]):X16}, 0x{BitConverter.DoubleToUInt64Bits(v[1]):X16}]";
// both operands constant
static Vector128<double> FoldedMin()
{
var x = Vector128.Create(double.NaN, 3.0);
var y = Vector128.Create(3.0, double.NaN);
return Vector128.Min(x, y);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static Vector128<double> RuntimeMin(Vector128<double> a, Vector128<double> b) => Vector128.Min(a, b);
static void Main()
{
var x = Opaque(Vector128.Create(double.NaN, 3.0));
var y = Opaque(Vector128.Create(3.0, double.NaN));
Console.WriteLine($"Min folded = {Bits(FoldedMin())}");
Console.WriteLine($"Min runtime = {Bits(RuntimeMin(x, y))}");
}
}dotnet run -c Release on x64.
Expected behavior
Both lines print [0xFFF8000000000000, 0xFFF8000000000000].
Lane 0 is Min(NaN, 3.0), which must propagate NaN. The scalar equivalents in the same process agree:
Math.Min(double.NaN, 3.0) = 0xFFF8000000000000
Math.Max(double.NaN, 3.0) = 0xFFF8000000000000
Actual behavior
On .NET 10 and .NET 11 preview:
Vector128.Min folded = [0x4008000000000000, 0xFFF8000000000000] <-- lane 0 = 3.0
Vector128.Min runtime = [0xFFF8000000000000, 0xFFF8000000000000]
Vector128.Max folded = [0x4008000000000000, 0xFFF8000000000000] <-- lane 0 = 3.0
Vector128.Max runtime = [0xFFF8000000000000, 0xFFF8000000000000]
Lane 0 of the constant path is 3.0 where NaN is required. Max is affected identically.
Regression
Same machine and SDK, changing only <TargetFramework>:
| TFM | runtime | constant path | opaque path | |
|---|---|---|---|---|
| net8.0 | 8.0.30 | 3.0 |
3.0 |
self-consistent, pre-IEEE semantics |
| net9.0 | 9.0.19 | NaN |
NaN |
correct |
| net10.0 | 10.0.11 | 3.0 |
NaN |
diverges |
| net11.0 | 11.0.0-preview.7.26381.103 | 3.0 |
NaN |
diverges |
The codegen shows what changed. On .NET 9, FoldedMin is genuinely constant-folded to the right answer:
; net9.0 - Repro:FoldedMin()
vmovups xmm0, xmmword ptr [reloc @RWD00]
RWD00 dq FFF8000000000000h, FFF8000000000000h ; [NaN, NaN] - correctOn .NET 10, the fold no longer happens; a bare vminpd is emitted over the two constants and evaluated at run time:
; net10.0 - Repro:FoldedMin()
vmovups xmm0, xmmword ptr [reloc @RWD00]
vminpd xmm0, xmm0, xmmword ptr [reloc @RWD16]
vmovups xmmword ptr [rcx], xmm0
RWD00 dq FFF8000000000000h, 4008000000000000h
RWD16 dq 4008000000000000h, FFF8000000000000hFor contrast, the opaque-operand version on .NET 10 emits the full compensation sequence and is correct:
; net10.0 - Repro:RuntimeMin(Vector128<double>, Vector128<double>)
vcmpeqpd xmm2, xmm1, xmm0
vxorps xmm3, xmm3, xmm3
vpcmpgtq xmm3, xmm3, xmm0
vandpd xmm2, xmm3, xmm2
vcmpneqpd xmm3, xmm0, xmm0 ; NaN test
vorpd xmm2, xmm3, xmm2
vcmpltpd xmm3, xmm0, xmm1
vorpd xmm2, xmm3, xmm2
vblendvpd xmm0, xmm1, xmm0, xmm2So the defect is path selection: with two constant operands the JIT takes neither the fold nor the compensation sequence.
Suspected cause
I have not built the JIT to confirm this, so please treat it as a reading of the source rather than a verified diagnosis.
In gtNewSimdMinMaxNode (src/coreclr/jit/gentree.cpp, ~line 26486) the NaN and signed-zero compensation is gated on:
else if ((cnsNode != nullptr) && !otherNode->OperIsConst())The block contains the correct NaN guard (if (isNaN) { return isNumber ? otherNode : cnsNode; }), but the !otherNode->OperIsConst() clause requires exactly one constant operand. With both constant the block is skipped and an uncompensated NI_X86Base_Min/Max is emitted, which matches the codegen above.
Also possibly relevant: GenTreeVecCon::IsNaN (~line 20949) is all-lanes, so a partially-NaN constant such as the one here is not recognized as NaN. I tested that case against the single-constant path and it currently produces correct results, so it appears latent rather than separately exploitable.
Related
#130831 is the same function but a distinct defect: one constant operand, signed zero, and a wrongly-computed needsFixup inside the block. Here the block is never entered. That issue's description notes that "NaN cases are handled separately (operand swap for isNumber, natural propagation otherwise)", which holds only while one operand is non-constant.
Configuration
- Windows x64, Release, AVX-512-capable host
- SDK
11.0.100-preview.7.26381.103 - Reproduces under
DOTNET_EnableAVX2=0and at tier0 - Correct under
DOTNET_EnableHWIntrinsic=0
Other information
Found by differential testing of constant-operand versus opaque-operand spellings of the same expression. Vector128.Add/Sub/Mul/Div were checked in the same sweep and do not diverge; only Min and Max do.
Note
This issue was authored with the help of GitHub Copilot.
Activity
dotnet-policy-service commentedon Sep 1, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
AndyAyersMS commentedon Sep 1, 2026
Additional data on this issue, including a second and more clearly live failing shape in the same function.
A second failing cell: a partially-NaN constant with one non-constant operand
The report above covers two constant operands. The same function also mishandles a constant that is NaN in some lanes but not all, with the other operand non-constant. On
10.0.11, x64 Release:Lane 0 is
Min(NaN, +inf)and must be NaN. Codegen is a barevminpdwith the constant assrc1:Since
minpdreturnssrc2when either operand is NaN, the constant's NaN lanes are discarded.This one goes through the
else if ((cnsNode != nullptr) && !otherNode->OperIsConst())branch rather than skipping it. The early-out usesGenTreeVecCon::IsNaN, which is documented as true only when all elements are NaN, so[NaN, +inf]falls past it into code whose comment reasons only about the other operand ("if other was NaN, we want to return other") while the subsequentneedsFixupanalysis considers only zeros. A constant that is NaN in some lanes and not others is handled by neither path.Unlike the two-constant case, this branch is unchanged on current
main(d2ea726dd3d), so this shape appears live there as well.Note on the two-constant case
That shape is sensitive to how the operands are spelled, which is worth knowing before attempting to reproduce. On the same
10.0.11binary, with identical values:A version written with
static readonlyfields also does not trigger, because the fields are not constants at that point and the compensating sequence is emitted instead.I have a report that the two-constant shape returns the correct value on
main, which I have not been able to confirm myself and which may be explained by the spelling sensitivity above rather than by a fix. I could not locate a corresponding change: the gate is unchanged onmain, andEvaluateBinarySimdinsimd.hstill has noGT_MIN/GT_MAXcase. Treating the partially-NaN shape as the primary live repro is probably safest.Related
#130831(closed) is the third member of this family in the same block: one constant, signed zero,needsFixupcomputed incorrectly inside the branch.Note
This comment was authored with the help of GitHub Copilot.
AndyAyersMS commentedon Sep 1, 2026
Correcting two things in my comment above, both of which affect what a fix has to cover. A checked build of
mainatd2ea726dd3dwas used for the reproductions I could not do myself; I have independently confirmed the control results below on shipped10.0.11.1. The two-constant case reproduces on
main— my "may be fixed" note was wrongI wrote that I had a report of the two-constant shape returning the correct value on
mainand could not confirm it. That report has since been retracted by its author: it was the spelling sensitivity I described, not a fix. The verbatimFoldedMin/FoldedMaxfrom the original post reproduce onmainatd2ea726dd3d, and identically attier0_min, so this is not tied to an optimizer phase.Please disregard the suggestion that only the partially-NaN shape should be treated as live. Both shapes are live on
main.2. Widening the
!otherNode->OperIsConst()gate would not fix the partially-NaN caseThis is the more important correction. My original post pointed at the gate as the cause, which is right for the two-constant shape but misleading as a general diagnosis: the partially-NaN case already passes that gate and enters the compensation block, then produces the wrong answer anyway.
Three controls isolate it. All three have exactly one constant operand, so all three enter the block:
[1.0, 2.0]— no NaN lane[NaN, NaN]— every lane NaNisNaNearly-out fires)[NaN, 3.0]— some lanes NaNMeasured on
10.0.11, one constant operand against an opaque[3.0, NaN]:The mechanism is that
GenTreeVecCon::IsNaNis all-lanes, so[NaN, 3.0]skips the early-out; theneedsFixupanalysis below it considers only zeros (IsVectorZero/IsVectorNegativeZero), so!needsFixupholds and the code emitsmin cns, otherwith the constant assrc1. Sinceminpdreturnssrc2when either operand is NaN, the constant's NaN lanes are dropped.So there appear to be two distinct defects in this block:
needsFixuppath.A fix that only relaxes the gate would leave the second one live.
Note
This comment was authored with the help of GitHub Copilot.
AndyAyersMS commentedon Sep 1, 2026
The same defect also loses the sign of zero, with no NaN involved
Measured on
main@d2ea726dd3d, windows.x64.Checked, AVX-512-capable host.This is the same function and the same code path, but it needs one constant
operand rather than two, and no NaN anywhere — so it is reachable in a shape the
current repro does not cover, and a fix aimed only at the two-constant gate
would not address it.
Repro
Lane 1 is
Min(-0.0, +0.0), which must be-0.0.Identical under
tier0_min. The expected answer is established in the sameprocess rather than quoted from the spec:
Generated code
The constant-operand form emits a bare
vminpdwith the constant assrc1, 65bytes in total:
The all-opaque form emits the compensation, including the sign-of-zero handling:
minpd src1, src2returnssrc2when both inputs are zero of either sign, sowith the constant as
src1the-0.0lane is discarded.The boundary, with controls
All three use exactly one constant operand, so all three enter the same block:
[-1.0, -2.0]— no zero lane-2.0[-0.0, -0.0]—-0.0in every lane-0.0[-1.0, -0.0]—-0.0in some lanes+0.0Refinement (later comment): the safe case is not “the constant is all zeros”.
[-0.0, +0.0]is all zeros but counts as some, and is wrong — so it must not be used as an “all zeros, should be fine” control. A further correction narrows it again: forMinNumbereven a constant with no-0.0lane is unsafe when the other operand can contain-0.0— so safety is a property of the operand pair, not of the constant alone.Cause
gtNewSimdMinMaxNode, the!isNumbervector branch:The block's own comment states the requirement precisely:
That is right. But
GenTreeVecCon::IsNegativeZeroreturnsfalseat the firstelement that is not
-0.0, so it recognises the situation only when everylane is
-0.0. A constant that is-0.0in one lane and something else inanother therefore reports
needsFixup == false, and the bare instruction isemitted with the very case the comment describes still present in that lane.
This is the same shape as the
IsVectorNaNobservation already in the issue —IsNaN,IsVectorZeroandIsNegativeZeroare all whole-vector predicates,while the property they gate is per lane.
Scope
16 operation/pattern combinations disagree between operand spellings,
identically at
fulloptsandtier0_min:Min,Max,MinNumberandMaxNumber, over four signed-zero lane patterns, in both operand positions.MinMagnitude,MaxMagnitudeand theirNumbervariants are unaffected — theytake the
isMagnitudebranch, which does not perform the zero fixup.Suggestion for the fix
The emission requires the absence of the special value in every lane, while
the predicates establish only its universal presence. Complementary
predicates — no lane
-0.0, no lane zero, no lane NaN — would gate the bareinstruction correctly and fall back to the compensation sequence for a mixed
constant.
For test coverage: for each of
Min,Max,MinNumber,MaxNumber, sweepconstants containing the special value in no, some and all lanes, in
both operand positions. Only the some column is currently wrong, in both the
NaN and the signed-zero families, and nothing existing reaches it.
Add a width axis alongside that:
Vector256<double>reproduces both families too (comment), so a fix scoped toVector128would be incomplete.Note on verification
Results are sensitive to how the expression is spelled — the same expression can
be wrong written one way and correct written another. The one-constant forms
above were wrong in every spelling and configuration tried, so they are the more
reliable regression tests.
Found by differential testing across operand spellings (ReifyCs).
AndyAyersMS commentedon Sep 2, 2026
One data point for scoping a fix: this is not
Vector128-only.Vector256<double>reproduces both forms, on stock .NET 10.0.11 (release runtime, no checked JIT or stress,DOTNET_TieredCompilation=0):with the all-opaque spelling of the same values correct in both cases, as before.
MaxmatchesMin.That is expected from the mechanism already described here — the branch is chosen by operand constant-ness, not simd size — but it means a fix and its test both want a width axis, not just the no/some/all-lanes axis.
Vector64andVector512did not reproduce for me, but neither is hardware-accelerated on this host, so both took software fallbacks and that result says nothing about the intrinsic path. They are unknown, not clean —Vector512would need an AVX-512 machine andVector64an arm64 one.Standalone repro: https://github.com/AndyAyersMS/ReifyCs/blob/main/findings/2026-09-01_minmax_partial_nan_const/v256_shipping/Program.cs
AndyAyersMS commentedon Sep 2, 2026
Warning
Partially corrected below. The “no lane
-0.0→ correct” clause in thiscomment is wrong for
MinNumber: an all-+0.0constant has no-0.0lanebut still differs when the other operand can contain
-0.0. See the correction.Min,MaxandMaxNumberare unaffected, and the rest of this comment stands.One refinement to the "all lanes" column above, because it can be read the wrong way round and would cost someone a regression test.
The safe case is not "the constant is all zeros".
IsVectorNegativeZerorequires every lane to be-0.0specifically, so an all-zero constant of mixed sign fails exactly like a partially-zero one. On stock .NET 10.0.11 (release,DOTNET_TieredCompilation=0), constant operand on the left, all-opaque spelling as the reference:So the boundary for a constant operand is: no lane
-0.0→ correct; every lane-0.0→ correct; some lanes-0.0→ wrong, and[-0.0, +0.0]counts as some despite being all zeros.Correction (later comment): the first clause holds only for
Min,MaxandMaxNumber. ForMinNumbera constant with no-0.0lane is not safe —MinNumber(const[+0,+0], opaque containing -0.0)differs. Safety is a property of the operand pair, not of the constant alone. The[1,2]row below is the only case I ran for that clause, and ordinary numbers do not probe the boundary.Worth stating because a test using
[-0.0, +0.0]as its "all zeros, should be fine" control would pass while the bug was still present.Repro: https://github.com/AndyAyersMS/ReifyCs/blob/main/findings/2026-09-01_minmax_partial_nan_const/mixedzero/Program.cs
AndyAyersMS commentedon Sep 2, 2026
Correction to my comment above (
5512943404): row 1 of that table is wrong forMinNumber.I wrote that a constant with no
-0.0lane is correct. An all-+0.0constant has no-0.0lane, so the table calls it safe — and forMinNumberit is not. Stock .NET 10.0.11,DOTNET_TieredCompilation=0, constant operand on the left, all-opaque spelling as the reference:Only
MinNumberis affected on that row;Min,MaxandMaxNumberare genuinely fine there.The reason I missed it: the only case I ran for that row was
const[1.0, 2.0]— ordinary numbers with no zero in them at all. That tests the row's label, not its boundary.So the safety condition is not a property of the constant. It depends on the operand pair:
MinNumberwith a+0.0constant is unsafe whenever the other operand can contain-0.0. Corrected:-0.0, op isMin/Max/MaxNumber-0.0, op isMinNumber, other operand may contain-0.0-0.0-0.0, including all-zero mixed sign like[-0.0, +0.0]Worth flagging for whoever fixes this, because it is the same shape as the defect itself: my table characterised safety per-vector when the property is per-pair — which is the mistake
IsVectorNegativeZeromakes by gating a per-lane property on a whole-vector predicate. A regression test derived from the original row 1 would pass whileMinNumberwas still wrong.Repro: https://github.com/AndyAyersMS/ReifyCs/blob/main/findings/2026-09-01_minmax_partial_nan_const/row1_minnumber/Program.cs
AndyAyersMS commentedon Sep 3, 2026
Data point on hardware coverage: this defect's reach appears to be wider on AVX512 hardware, and everything reported on this issue so far — including my comments — was measured on hosts without it.
The gate
gtNewSimdMinMaxNode(src/coreclr/jit/gentree.cpp, line 26554 ond2ea726dd3d) only takes the constant-operand path when the needed fixup is available:with
needsFixupset fromIsVectorZero()/IsVectorNegativeZero()just above, and the block comment stating the intent directly:So on a host without AVX512, a zero constant that sets
needsFixupmakescanHandlefalse and the JIT declines the constant path entirely. With AVX512 the second disjunct fires, the baremin/maxis emitted, and correctness depends on the fixup. A non-AVX512 host therefore cannot exercise the path at all.Measurement
Differential fuzzing of constant-vs-opaque spellings of the same min/max expressions, identical generator commit so identical programs, identical four-config matrix (
fullopts,fullopts_no_avx512,fullopts_no_avx2,tier0_min), identical seed range:Avx512F.IsSupportedMinNumber/MaxNumber,fulloptsonlyAt a 41% rate, 300 trials on the second host would be expected to produce ~120 disagreements. It produced none.
I want to be precise about what is and is not mine: the AVX512 row is a report from another machine that I have not reproduced myself — I have no AVX512 hardware. What I verified directly is the non-AVX512 row, that the two runs use byte-identical generated programs, and the source gate quoted above.
Why it matters for the fix
So it would be worth running any candidate fix, and any new regression test, on an AVX512 machine specifically — and worth an
Avx512F.IsSupportedline in the repro output so a clean result cannot be mistaken for a correct one.One correction to my own earlier comments
The five-case table I used to characterise this family is not a probe of the gate above, and I do not want it read as one. An all-NaN constant returns early at line 26499 (
return otherNodeforMinNumber/MaxNumber,return cnsNodeotherwise) and never reaches theneedsFixuplogic at all. AndIsVectorZero()is all-bits-zero, so only a+0.0constant setsneedsFixupforMinNumber— a-0.0constant does not. Cases built from all-NaN or-0.0constants exercise neither branch of the gate.AndyAyersMS commentedon Sep 3, 2026
Upshot of above, make sure we test fixes on both AVX-512 and non-AVX-512 HW.
Fix SIMD MinMax constant special cases (#133173)