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
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