Skip to content

JIT: Montgomery rows, CMOV mask selects and carry chains through composite field kernels - #2

Merged
benaadams merged 2 commits into
benaadams:adcfrom
flcl42:carry-rows
Oct 15, 2026
Merged

benaadams merged 2 commits into
benaadams:adcfrom
flcl42:carry-rows

Conversation

@flcl42

@flcl42 flcl42 commented Oct 13, 2026 •

Copy link
Copy Markdown

This builds on dotnet#134039. It targets that PR's adc branch, so the diff shows only the additions.

It came out of Nethermind.Crypto.BlsNet, a pure C# BLS12-381 library (fields, G1/G2, MSM, map-to-curve, pairing) ported from blst and used to implement Nethermind's EIP-2537 precompiles without native code. Its field arithmetic is written in the carry idioms dotnet#134039 recognizes. With dotnet#134039 alone, those kernels still ran 1.5–1.7x slower than blst's hand-written MULX/ADCX/ADOX assembly. With this change, the same C# beats blst in every EIP-2537 precompile.

Results

All numbers are from a Ryzen 9 9950X3D VM running Windows x64. "dotnet#134039" is the PR at 331fa2b3; "dotnet#134039 + this PR" adds this branch. Both runtimes report as .NET 12.0.0-dev. The managed binaries are identical across the runtime columns: only the JIT changes.

Fr/Fp Montgomery mul+add

Times are in ns per acc = acc * a + b, over 1,000,000 dependent iterations. Each run takes the best of 7 rounds, and the table shows the best of 5 interleaved runs (benchmark):

.NET 11 RC1 dotnet#134039 dotnet#134039 + this PR blst (ADX), P/Invoke
Fr mul+add 26.7 17.9 11.0 12.3
Fp mul+add 57.3 35.9 19.9 20.7

EIP-2537 precompiles in Nethermind

These come from Nethermind's own BenchmarkDotNet precompile benchmarks (in-process toolchain, Short job), with the benchmark inputs from bench_precompiles. The MSM inputs use 1–4096 distinct points; the pairing inputs use distinct points.

  • blst: Nethermind's current precompiles, over Nethermind.Crypto.Bls 0.3.17.15 (blst with ADX).
  • managed: the same Nethermind precompile code (input validation, parallel decoding with subgroup checks, encoding), with the calls into blst replaced by the C# library, compiled for net10.0 as Nethermind is.
  • "This PR vs JIT: recognition of ADC/SBB, MULX/ADCX/ADOX patterns for BigInteger, Decimal, UInt128 dotnet/runtime#134039": runs the same managed binary under both JITs.
  • "vs blst": divides by the blst column, measured in the .NET 10 run. blst's times in the patched run were within −16%/+3% of it.
Precompile n blst managed, .NET 10.0.12 managed, dotnet#134039 managed, dotnet#134039 + this PR this PR vs dotnet#134039 vs blst
G1ADD 1 2.7 µs 4.9 µs 2.6 µs 2.2 µs 1.16x faster 0.83x
G1MSM 1 83.7 µs 313.6 µs 106.6 µs 65.1 µs 1.64x faster 0.78x
G1MSM 8 406.7 µs 1.48 ms 481.0 µs 322.0 µs 1.49x faster 0.79x
G1MSM 128 2.73 ms 10.06 ms 3.38 ms 2.22 ms 1.53x faster 0.81x
G1MSM 4096 42.80 ms 141.60 ms 52.71 ms 32.84 ms 1.61x faster 0.77x
G2ADD 1 4.2 µs 7.5 µs 3.9 µs 3.1 µs 1.27x faster 0.73x
G2MSM 1 147.4 µs 346.2 µs 160.2 µs 99.7 µs 1.61x faster 0.68x
G2MSM 8 866.0 µs 1.83 ms 973.5 µs 595.1 µs 1.64x faster 0.69x
G2MSM 128 6.45 ms 14.39 ms 5.48 ms 3.64 ms 1.51x faster 0.56x
G2MSM 4096 104.81 ms 261.38 ms 107.25 ms 63.37 ms 1.69x faster 0.60x
MAP_FP_TO_G1 1 28.7 µs 107.2 µs 41.8 µs 26.7 µs 1.56x faster 0.93x
MAP_FP2_TO_G2 1 102.4 µs 300.8 µs 146.3 µs 87.3 µs 1.68x faster 0.85x
PAIRING_CHECK 1 476.6 µs 1.26 ms 691.5 µs 392.7 µs 1.76x faster 0.82x
PAIRING_CHECK 2 689.0 µs 1.76 ms 968.3 µs 595.8 µs 1.63x faster 0.86x
PAIRING_CHECK 8 1.45 ms 3.86 ms 2.17 ms 1.29 ms 1.68x faster 0.89x

Changes

All changes are x64-only and live in lower.cpp, plus small additions in lower.h, lsraxarch.cpp and emitxarch.cpp. The multiply parts use the same ADX gating as dotnet#134039. jit/README.md has more detail.

  1. TryLowerMultiplyCarryRows keeps CF and OF across the rows of a Montgomery multiplication: several rows per block, rows of any width, and the short first lanes of CIOS rows. Each lane becomes a mulx. adcx carries the previous high word plus the accumulator in CF, and adox adds the low product in OF. The last high word is drained as hi + CF + OF.
  2. LowerMaskSelects turns the constant-time conditional subtraction mask = 0 - carry; r = t ^ ((t ^ s) & mask) into cmovcc reading the chain's flags. This replaces setb; movzx; neg, plus xor; and; xor per limb.
  3. IsCarryFlagsCrossing lets loads, lea, non-zero constants, int→long casts and contained nodes sit between a carry and its consumer.
  4. Carry-use scans continue past their local allowance within the phase's shared budget, so the last carry of a long chain stays in flags.
  5. OSR methods get the carry passes too. Only root-method locals are excluded.
  6. Seeded carries: a first carry or borrow may be seeded from an independent bit-valued local, even after copy propagation. Every defining input must be proven to be a bit; arbitrary words and promoted fields are rejected.
  7. Stores: CF/OF propagate across nonvolatile integer stores. GC stores and write barriers are excluded, and alias and exception-order checks still govern reads.
  8. Invariant operands: closed invariant AND/OR/XOR and complement trees are hoisted before the chain root. Hoisting only ahead of an ADC/SBB would clobber its incoming flag.
  9. Final ADC/SBB: it is folded in place when moving its load would cross an aliased store, provided the instructions in between preserve flags.
  10. MULX: a shared invariant multiplier is kept in RDX and out of the result registers. Redundant register-to-RDX copies after MULX are removed in a bounded emitter scan. Unsigned scalar BigMul between carry limbs uses flag-preserving MULX.
  11. Containment is recomputed after the multiply-carry rewrites change operand roles. Stale containment caused a checked-JIT assertion in BigIntegerCalculator.MulAdd1 under tiering with JitStressRegs=1, which also reproduces with JIT: recognition of ADC/SBB, MULX/ADCX/ADOX patterns for BigInteger, Decimal, UInt128 dotnet/runtime#134039 alone.
  12. Budgets: the bounded analysis budgets are larger: full adders in methods up to 8,192 nodes and 128 candidates, 65,536 carry-use visits and 262,144 dead-on-exit visits. This lets composite field helpers keep their carries in flags; exhaustion still declines the optimization.

The safety conditions are unchanged. Each rewritten temporary must be the only reader of its value and dead afterwards. Only flag-neutral nodes may sit inside a chain. Memory accesses move only when alias checks allow it. Methods with EH are skipped, and every scan is budgeted.

Testing

  • Regression tests under src/tests/JIT/opt/Add/:

    • MontgomeryRows;
    • MaskSelect;
    • SeededMaskedCarry;
    • MulxMultiplierCopies;
    • ComplementedCarry;
    • CompositeCarry, sixteen unrolled six-word additions and subtractions checked against BigInteger;
    • ScalarProductCarry.

    The tests cover the accepted shapes, the shapes that must be rejected, and aliasing.

  • Stress runs: all 18 entry points pass on the checked JIT under the default configuration, JitStress=2 and JitStressRegs=1/3/8, each with TieredCompilation=0/1. They also pass with AVX2 disabled and with ADX disabled.

  • Library tests: 82,198 curve checks and 1,295,823 pairing and field checks, differential against native blst, pass on the release and checked JITs, including the stress modes.

  • Nethermind: all 2,184 BLS precompile tests pass on the patched runtime. These include thousands of random inputs per precompile that must match blst exactly.

  • Pre-existing failure: JIT: recognition of ADC/SBB, MULX/ADCX/ADOX patterns for BigInteger, Decimal, UInt128 dotnet/runtime#134039's own CarryTests crash under JitStress=1, and intermittently under JitStressRegs with tiering. This happens with and without this change.

Recognize the rows of a Montgomery multiplication (several rows per block,
any width, the short first lanes of CIOS rows) and emit them as MULX with
dual ADCX/ADOX carry chains. Turn the constant-time select
t ^ ((t ^ s) & (0 - carry)) after a carry chain into CMOVs on the carry
flag. Let loads, LEAs, non-zero constants and casts sit between a carry and
its consumer, follow the last carry of a long chain past 64 nodes, and run
the carry passes in OSR methods, excluding only root-method locals.
Accept first carries and borrows seeded from independent bit-valued locals,
propagate CF/OF across nonvolatile integer stores, hoist closed invariant
AND/OR/XOR operand trees ahead of a chain, fold the final ADC/SBB in place
when moving a load would cross an aliased store, keep flags across unsigned
scalar products between carry limbs, keep a shared MULX multiplier in RDX
and out of the result registers, recompute operand containment after the
multiply-carry rewrites (fixing a checked-JIT assert in
BigIntegerCalculator.MulAdd1 under tiering with JitStressRegs=1), and raise
the bounded carry-use scan allowance so wide subtractions keep their flags.
Add regression tests for each pattern.
@flcl42 flcl42 changed the title JIT: Montgomery rows on MULX/ADCX/ADOX and CMOV mask selects JIT: Montgomery rows, CMOV mask selects and carry chains through composite field kernels Oct 15, 2026
@benaadams
benaadams marked this pull request as ready for review October 15, 2026 11:10
@benaadams
benaadams merged commit 0a303c9 into benaadams:adc Oct 15, 2026
benaadams pushed a commit that referenced this pull request Nov 27, 2026
…ons (dotnet#135899)

## Root cause

`compareTypesForCast` in crossgen2
(`src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs`) ends with an
`#if READYTORUN` block that reported every `MustNot` back to the JIT as
`May`. The reason: in R2R, a cast that fails today may succeed after a
dependency outside the version bubble is updated, for example when a
type gains an interface. The JIT only folds `box T; isinst X; br` to a
constant when the answer is `Must` or `MustNot` (`impBoxPatternMatch`).
So in R2R code every *negative* check kept its box allocation and cast
helper call, while positive checks still folded. The runtime JIT and
NativeAOT already fold these casts.

The codegen difference is the same for every crossgen2 target, but its
impact depends on whether R2R code is ever replaced:
- **Where R2R code is never recompiled at a higher tier:** CoreCLR on
WebAssembly, iOS and tvOS. For example,
`MemoryExtensions.IndexOfAnyInRange<char>` checks `lowInclusive is byte
or sbyte` and `is short or ushort or char`, which allocated 48 B per
call.
- **MacCatalyst:** possibly affected the same way, depending on whether
it runs with the JIT; I haven't checked its runtime configuration.
- **Apps with `TieredCompilation=false`:** affected on any platform.
- **Elsewhere:** tiered compilation recompiles hot methods with the
runtime JIT, which already folds these casts, so the gain is limited to
startup and cold code.

I compiled the issue's repro for ios-arm64, tvos-arm64 and
maccatalyst-arm64 as well as osx-arm64 and browser-wasm. All show the
same before/after codegen.

## Change

In R2R, keep `MustNot` when neither type uses COM type equivalence and
either of these holds:
1. **Value-type rule:** `fromType` is a value type, and `toType` is not
an interface and is not `System.Enum`.
2. **Version-bubble rule:** `toType`, every type in `fromType`'s base
chain, and every interface `fromType` implements are in the version
bubble, with these excluded:
   - arrays;
   - generic interfaces and delegates with variance;
   - COM classes.

The policy lives in `IsNegativeCastResultVersionResilient` in
`CorInfoImpl.ReadyToRun.cs`.

**Why this is sound:**
- **No new cast logic:** for these types the `MustNot` answer is what
crossgen2 already computes and what the runtime JIT and NativeAOT
already fold to. The only new claim is that the answer can't change
between versions.
- **Value-type rule:**
- Value types are sealed and their base types (`ValueType`/`Object`) are
fixed, so a new version could only make such a cast succeed by adding an
interface. Interface targets stay `May`, and `System.Enum` is excluded
in case a struct becomes an enum.
- `Nullable<T>` sources don't need excluding: no object's exact type is
`Nullable<T>` (the box path already passes `getTypeForBox`), and the
VM's `compareTypesForCast` doesn't exclude them either.
- **Version-bubble rule:** when every type that decides the cast
versions with the compiled code, none of them can change without that
code being recompiled. The exclusions cover the cases where something
outside the static hierarchy decides the answer:
- array and variant casts also depend on element types and generic
arguments;
  - COM objects can be cast to interfaces through `QueryInterface`;
- `IDynamicInterfaceCastable` sources already return `May` earlier in
`compareTypesForCast`.
- **Shared generics:** `MustNot` with a canonical source is only
produced for a non-generic interface target. Under the bubble rule the
source's interfaces must also be in the bubble, so no instantiation can
add that interface.
- **Other JIT callers are safe:** every other place the JIT uses
`compareTypesForCast` requires an exact source type before folding a
negative result (`importer.cpp` `impCastClassOrIsInstToTree`,
`valuenum.cpp`, `helperexpansion.cpp`).
- **Build modes:** the value-type rule applies the same way in every
build mode. The bubble rule applies wherever all of the type's hierarchy
is in the bubble: when compiling CoreLib, in composite and input-bubble
builds, and for interface-only hierarchies in any build. For classes and
structs in an app compiled on its own, `System.Object` is outside the
bubble, so the bubble rule doesn't apply there.

The test harness's `Crossgen2Option.InputBubble` passed
`--input-bubble`, which crossgen2 doesn't accept (the option is
`--inputbubble`). No existing test used it; this PR fixes it so the new
test can cover input-bubble builds.

## Results

Repro from the issue, compiled with in-tree crossgen2 and JITs:

| | Before | After |
|---|---|---|
| `CallSame(char)` on osx-arm64 | 180 B, 4 box allocations + 3 cast
helper calls | 20 B (`mov w0, #2; ret`) |
| `CallSame(char)` on browser-wasm | 415 B | 23 B |

`CallSame` now matches the equivalent `typeof(T) ==` version.

CoreCLR browser-wasm R2R composite (CoreLib + benchmark app,
`--composite --opt-cross-module:*`), Node/V8 on an Apple M-series host,
5 interleaved rounds, medians. "Before" is the in-tree crossgen2 without
this PR; "value-type rule only" is this PR's first commit:

| Benchmark | Before | Value-type rule only | This PR (de835bf) |
|---|---|---|---|
| `IndexOfAnyInRange('!', '#')` on `ReadOnlySpan<char>`, len=16 | 89.2
ns | 11.8 ns | 11.6 ns |
| same, len=1024 | 114.9 ns | 42.7 ns | 42.7 ns |
| Allocations per call, `IndexOfAnyInRange`/`IndexOfAnyExceptInRange`
(char) | 48 B | 0 B | 0 B |

- **Other benchmarks:** for the 36 others, the median ratio of this PR
to before is 0.998 (range 0.96–1.13), and none differs from the
value-type-rule-only build by more than 5% with non-overlapping ranges.
One outlier, `SearchValues<string>` at len=1024, is consistently about
12 ns slower than before (91.1 → 103.3 ns). The methods it uses compile
to the same size with and without the change, so this is probably code
layout rather than codegen, but it is unexplained.
- **Code size (`JitDisasmSummary` over the composite):** 14 of 12,409
methods change size, all smaller; none grow and none are added or
removed. The total is −4,927 B, compared with 11 methods and −3,980 B
for the value-type rule only. Examples:
- from the value-type rule: `TextInfo.ToLowerAsciiInvariant` 898 → 574
B, `TimeSpanParse.StringParser.NextNonDigit` 616 → 297 B, and the four
`StringSearchValues.TryCreateSingleValuesThreeChars` instantiations 764
→ 445 B;
- added by the bubble rule:
`DefaultInterpolatedStringHandler.AppendFormatted<bool>` 1146 → 429 B,
and `RuntimeCustomAttributeData.Init` for
`DllImportAttribute`/`FieldOffsetAttribute` −125 B / −105 B.

## Testing

Baseline build: `./build.sh clr+libs -rc release`, then `./build.sh
clr.tools -rc release` after the change.

**New R2R test, `R2RTestSuites.CastFoldingRespectsVersionBubble`**
(fixture `TestCases/CastFolding/CastFolding.cs`). It's a theory that
runs once as a per-assembly build and once as an input-bubble build:

| Command | Result |
|---|---|
| `./dotnet.sh test src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests -c
Debug /p:RuntimeConfiguration=Release --filter
FullyQualifiedName~CastFoldingRespectsVersionBubble` | 2 passed; both
fail when `CorInfoImpl.cs` is reverted to before this PR |
| Same, with any one of the bubble rule's four guards removed (target in
bubble, interface list in bubble, COM, variance) | fails each time |
| `./dotnet.sh test src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests -c
Debug /p:RuntimeConfiguration=Release` | 149 passed, 15 skipped, 0
failed |

**How the test detects folding:**
- **Box/isinst casts:** it looks for the types in import entries of any
fixup kind, because x64/arm64 reference them through
`NEW_OBJECT`/`IS_INSTANCE_OF` imports while browser-wasm uses only
`TYPE_HANDLE` fixups.
- **`typeof(...)` assignability casts:** the type-handle imports remain
even when the cast folds, so the test checks for imports of the
`Type.IsAssignableFrom`/`IsAssignableTo` calls instead.

I checked the fixture's imports for linux-x64 and browser-wasm with
R2RDump, but didn't run the test project for those targets.

**Existing runtime tests compiled with crossgen2, osx-arm64 Release.**
These ran with the value-type rule alone. In these builds every class or
struct hierarchy includes `System.Object` from outside the bubble, so
the bubble rule wouldn't change them. I first confirmed that the
crossgen2 in Core_Root folds the repro's value-type casts. Build
commands:
```
src/tests/build.sh arm64 Release -test:<project> /p:LibrariesConfiguration=Debug
export CORE_ROOT=artifacts/tests/coreclr/osx.arm64.Release/Tests/Core_Root RunCrossGen2=1
```

| Test runner | Relevant tests | R2R per assembly (`RunCrossGen2=1`) |
R2R composite (`CompositeBuildMode=1`) |
|---|---|---|---|
| `JIT/Generics/JIT.Generics_o` | `box_isinst_br_nullable` | passed |
passed |
| `JIT/Generics/JIT.Generics_ro` | `box_isinst_unbox` | passed | passed
|
| `JIT/Methodical/Methodical_others` | `BoxPatternMatchAndSideEffects` |
passed | passed |
| `JIT/Directed/Directed_ro` | `nullabletypes/isinst*` | passed | passed
|

Every run ended with `END EXECUTION - PASSED` and included R2RDump
validation.

`JIT/Intrinsics/TypeIntrinsics_ro` (folding of
`IsAssignableFrom`/`IsAssignableTo`) and `JIT/opt/Casts` (`tests`,
`shared_Casts`, `shared2`) have no standalone runner. For those, I
compiled each assembly with Core_Root's crossgen2 (`-O --targetos:osx
--targetarch:arm64`) and ran its test methods through a small reflection
harness under `corerun`. All passed, with per-assembly R2R only. The R2R
runs JIT-compiled about half as many methods (e.g. 81 vs. 164), so the
precompiled code was used.

**CoreLib compiled with both rules, osx-arm64 Release.** CoreLib is its
own version bubble, so this is where the bubble rule applies most. I
rebuilt it with `./build.sh clr.nativecorelib -rc release` (which uses
the updated crossgen2), then ran with `DOTNET_TieredCompilation=0` so
the precompiled CoreLib code is never replaced:

| Tests | Result |
|---|---|
| The four runtime-test runners above, on a regenerated Core_Root
(`src/tests/build.sh arm64 Release -GenerateLayoutOnly`) | all passed |
| `TypeIntrinsics_ro` and `opt/Casts` through the harness | all passed |
| `System.Runtime.Tests` (`./dotnet.sh build -t:Test`, with the new
CoreLib copied into the testhost) | 80,039 total, 0 failed, 90 skipped |
| `System.Collections.Tests` (same setup) | 33,958 total, 0 failed, 0
skipped |

**Not covered:**
- runtime tests on x64, arm or wasm;
- runtime tests on a composite framework built with the bubble rule;
- checking which individual test methods actually hit the new fold;
- the full runtime test suite.

## Side finding (not addressed here)

During the investigation I found that crossgen2 doesn't inline a `where
T : struct` generic instantiated over `char` (`S<char>`). JitDump
reports `cannot get method info`, and `S<char>` isn't precompiled
either, so the call falls back to the runtime JIT. This is unrelated to
this change and may deserve its own issue.

Resolves dotnet#135892

> [!NOTE]
> This PR description was generated with GitHub Copilot.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e57ce813-cc00-4e28-824c-2eecc4d8fb9f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants