Repository navigation
JIT: Montgomery rows, CMOV mask selects and carry chains through composite field kernels - #2
Merged
Merged
Conversation
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.
benaadams
marked this pull request as ready for review
October 15, 2026 11:10
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This builds on dotnet#134039. It targets that PR's
adcbranch, 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):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.Nethermind.Crypto.Bls0.3.17.15 (blst with ADX).Changes
All changes are x64-only and live in
lower.cpp, plus small additions inlower.h,lsraxarch.cppandemitxarch.cpp. The multiply parts use the same ADX gating as dotnet#134039.jit/README.mdhas more detail.TryLowerMultiplyCarryRowskeeps 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 amulx.adcxcarries the previous high word plus the accumulator in CF, andadoxadds the low product in OF. The last high word is drained as hi + CF + OF.LowerMaskSelectsturns the constant-time conditional subtractionmask = 0 - carry; r = t ^ ((t ^ s) & mask)intocmovccreading the chain's flags. This replacessetb; movzx; neg, plusxor; and; xorper limb.IsCarryFlagsCrossinglets loads,lea, non-zero constants, int→long casts and contained nodes sit between a carry and its consumer.BigMulbetween carry limbs uses flag-preserving MULX.BigIntegerCalculator.MulAdd1under tiering withJitStressRegs=1, which also reproduces with JIT: recognition of ADC/SBB, MULX/ADCX/ADOX patterns for BigInteger, Decimal, UInt128 dotnet/runtime#134039 alone.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 againstBigInteger;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=2andJitStressRegs=1/3/8, each withTieredCompilation=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
CarryTestscrash underJitStress=1, and intermittently underJitStressRegswith tiering. This happens with and without this change.