Repository navigation
Implement IBinaryInteger<TSelf>.ReverseBits - #131145
huoyaoyuan wants to merge 21 commits into
Conversation
|
Azure Pipelines: Successfully started running 3 pipeline(s). 13 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
| } | ||
|
|
||
| /// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)" /> | ||
| static BigInteger IBinaryInteger<BigInteger>.ReverseBits(BigInteger value) |
There was a problem hiding this comment.
Though it doesn't make much sense for BigInteger, I'm trying to design a rule that reasonably round-trips, and behaves consistently on 32/64bit and LE/BE platforms.
There was a problem hiding this comment.
It doesn't look to be consistent for 32/64-bit right now? what about -(BigInt.One << 96)?
-- The ref assembly was also not updated
There was a problem hiding this comment.
The effective signed binary is .._FFFFFFFF_00000000_00000000_00000000, which is expected be treated samely with .._FFFFFFFF_00000000 case, which is included in the test. The expected result is round-tripping to itself. I can add a test caes for it.
There was a problem hiding this comment.
Well test shows difference for -(BigInt.One << 64) case. I'll debug more.
There was a problem hiding this comment.
I've reworded the rules, refactored the condition checks and added more comments about tests. Hopefully it's more understandable now.
|
Manually tagging @dotnet/area-system-numerics as the bot misses. |
|
@tannergooding tagged you for review and I marked the PR and issue as .NET 12. If we get this merged before the RC2 snap date, I'd be comfortable seeking tactics approval for backport to .NET 11 if you are. |
|
|
||
| if (BitConverter.IsLittleEndian) | ||
| { | ||
| return TSelf.ReadBigEndian(bytes, isUnsigned: false); |
There was a problem hiding this comment.
This can fail for a case like 1 on an unsigned type.
| if (Gfni.IsSupported) | ||
| { | ||
| Vector128<byte> vec = Vector128.CreateScalarUnsafe(value); | ||
| vec = Gfni.GaloisFieldAffineTransform(vec, Vector128.Create(0x8040201008040201).AsByte(), 0); | ||
| return vec.ToScalar(); | ||
| } |
There was a problem hiding this comment.
I'm not convinced this is faster, especially not when factoring in the SIMD/GPR transition, the memory load, etc
It's likely being skewed by the microbenchmark.
There was a problem hiding this comment.
The vector path shows 2.5x faster on uint32 even in dense loop unrolling benchmark, and undistinguishable time (<0.1ns) in scalar benchmark.
For dense case which consumes more memory and SIMD register, we could provide packed operation via TensorPrimitives.
For sparse use case, does it really matter for consumption for a few SIMD registers?
I know it can be skewed by microbenchmark given it's using SIMD effectively densely. However, xmm is used quite commonly. Would it matter?
There was a problem hiding this comment.
It's about how it interplays with the entire system. For vector, this is likely an optimization; but for simple scalar you are inserting multiple stalls (gpr to simd transitions), memory dependencies (likely uncached), and other considerations that likely make it a perf loss; particularly for code that isn't hot.
The scalar path will be around 9-16 cycles, depending on how well it pipelines. On the other hand, the vector path will also be 9-21 cycles (without factoring in the memory load cost), depending on how much penalty there is for the vmovd instructions (which have gotten slower on newer hardware, changing from <=3 to <=8 on regular cores and more on e-cores)
The GPR<->SIMD transition penalty can be a lot especially for hot code. Inversely the memory dependency can be a lot for cold code as its unlikely to be in the cache. A microbenchmark is setup in a way that masks both of these issues pretty well because the work is broken up enough to not expose the transition penalty but frequent enough to keep the method local constant in the L1 or at worst L2 cache.
There was a problem hiding this comment.
I can understand the mechanism here, but can't get a quantifiable conclusion here. How can we made the decision whether to use the vector path or not?
| value = (byte)(((value & 0xF0) >>> 4) | ((value & 0x0F) << 4)); | ||
| value = (byte)(((value & 0xCC) >>> 2) | ((value & 0x33) << 2)); | ||
| value = (byte)(((value & 0xAA) >>> 1) | ((value & 0x55) << 1)); |
There was a problem hiding this comment.
I think this can be parallelized a bit and avoid the redundant casting by using a uint result instead and only casting to byte at the end
There was a problem hiding this comment.
I performed a simple benchmark on following versions:
[Benchmark]
[Arguments(0x12345678u)]
public uint Reverse1(uint value)
{
value = ((value & 0xF0F0F0F0) >>> 4) | ((value & 0x0F0F0F0F) << 4);
value = ((value & 0xCCCCCCCC) >>> 2) | ((value & 0x33333333) << 2);
value = ((value & 0xAAAAAAAA) >>> 1) | ((value & 0x55555555) << 1);
return BinaryPrimitives.ReverseEndianness(value);
}
[Benchmark]
[Arguments(0x12345678u)]
public uint Reverse2(uint value)
{
value = ((value & 0xF0F0F0F0) >>> 4) | ((value & 0x0F0F0F0F) << 4);
value = ((value & 0x88888888) >>> 3) | ((value & 0x44444444) >>> 1) | ((value & 0x22222222) << 1) | ((value & 0x11111111) << 3);
return BinaryPrimitives.ReverseEndianness(value);
}The first version has longer dependency chain and the second version has one more OR operation. Benchmark shows the second version as slightly slower in unrolled loop.
There was a problem hiding this comment.
Pull request overview
This PR adds a new IBinaryInteger<TSelf>.ReverseBits(TSelf) API (with a default interface implementation) and wires up optimized ReverseBits implementations for the built-in integer types, along with corresponding generic-math test coverage (including BigInteger).
Changes:
- Add
static virtual TSelf ReverseBits(TSelf value)toIBinaryInteger<TSelf>with a DIM-based fallback implementation. - Implement
ReverseBitson the primitive integer types (andInt128/UInt128,nint/nuint), using hardware intrinsics when available and software fallbacks otherwise. - Add/extend generic-math tests to validate
ReverseBitsacross the supported numeric types, includingBigInteger.
Reviewed changes
Copilot reviewed 32 out of 32 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| src/libraries/System.Private.CoreLib/src/System/Numerics/IBinaryInteger.cs | Adds the ReverseBits DIM fallback implementation on IBinaryInteger<TSelf>. |
| src/libraries/System.Runtime/ref/System.Runtime.cs | Updates System.Runtime ref surface for the new public ReverseBits APIs and interface member. |
| src/libraries/System.Runtime.Numerics/ref/System.Runtime.Numerics.cs | Updates numerics ref surface to include BigInteger’s IBinaryInteger<BigInteger>.ReverseBits. |
| src/libraries/System.Private.CoreLib/src/System/Byte.cs | Adds byte.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/SByte.cs | Adds sbyte.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/UInt16.cs | Adds ushort.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/Int16.cs | Adds short.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/UInt32.cs | Adds uint.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/Int32.cs | Adds int.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/UInt64.cs | Adds ulong.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/Int64.cs | Adds long.ReverseBits implementation (intrinsics + fallback). |
| src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs | Adds nuint.ReverseBits forwarding to uint/ulong.ReverseBits by target bitness. |
| src/libraries/System.Private.CoreLib/src/System/IntPtr.cs | Adds nint.ReverseBits forwarding to int/long.ReverseBits by target bitness. |
| src/libraries/System.Private.CoreLib/src/System/UInt128.cs | Adds UInt128.ReverseBits (GFNI path + scalar composition). |
| src/libraries/System.Private.CoreLib/src/System/Int128.cs | Adds Int128.ReverseBits (GFNI path + scalar composition). |
| src/libraries/System.Private.CoreLib/src/System/Char.cs | Adds explicit IBinaryInteger<char>.ReverseBits forwarding via ushort.ReverseBits. |
| src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs | Adds IBinaryInteger<BigInteger>.ReverseBits implementation for BigInteger. |
| src/libraries/System.Runtime.Numerics/tests/BigIntegerTests.GenericMath.cs | Adds ReverseBits tests for BigInteger via BinaryIntegerHelper<>. |
| src/libraries/Common/tests/System/GenericMathHelpers.cs | Extends BinaryIntegerHelper<TSelf> with a ReverseBits forwarding helper. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/ByteTests.GenericMath.cs | Adds ReverseBitsTest for byte. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/SByteTests.GenericMath.cs | Adds ReverseBitsTest for sbyte. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/CharTests.GenericMath.cs | Adds ReverseBitsTest for char. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt16Tests.GenericMath.cs | Adds ReverseBitsTest for ushort. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int16Tests.GenericMath.cs | Adds ReverseBitsTest for short. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt32Tests.GenericMath.cs | Adds ReverseBitsTest for uint. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int32Tests.GenericMath.cs | Adds ReverseBitsTest for int. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt64Tests.GenericMath.cs | Adds ReverseBitsTest for ulong. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int64Tests.GenericMath.cs | Adds ReverseBitsTest for long. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt128Tests.GenericMath.cs | Adds ReverseBitsTest for UInt128. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int128Tests.GenericMath.cs | Adds ReverseBitsTest for Int128. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UIntPtrTests.GenericMath.cs | Adds ReverseBitsTest for nuint with 32/64-bit expected values. |
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/IntPtrTests.GenericMath.cs | Adds ReverseBitsTest for nint with 32/64-bit expected values. |
Suppressed comments (1)
src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs:3562
- Once the buffer is tracked by a
using var(see earlier), this explicit Dispose becomes redundant and easy to forget if new early-returns/throws are added.
BigInteger result = new BigInteger(byteBuffer, isBigEndian: !BitConverter.IsLittleEndian);
rentedBuffer.Dispose();
| int MSBstrip = 0; | ||
| // First handle round-tripping for the extra trailing word | ||
| // 33 bits differ from sign. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 32 out of 32 changed files in this pull request and generated no new comments.
Suppressed comments (5)
src/libraries/System.Private.CoreLib/src/System/Numerics/IBinaryInteger.cs:424
- The stackalloc path always allocates 256 bytes even when
byteCountis much smaller, which increases per-call stack usage for most primitive types (whereGetByteCount()is typically 1–16/32). Consider stackalloc’ingbyteCount(while keeping the threshold decision) to reduce stack pressure.
const int StackallocThreshold = 256;
int byteCount = value!.GetByteCount();
byte[]? rented = null;
Span<byte> bytes = byteCount <= StackallocThreshold
? stackalloc byte[StackallocThreshold]
: rented = ArrayPool<byte>.Shared.Rent(byteCount);
bytes = bytes.Slice(0, byteCount);
src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs:3563
rentedBuffer.Dispose()is not in afinally/usingscope. If theBigIntegerconstructor throws (even unexpectedly, e.g., OOM), the rented buffer may not be returned/disposed. Consider wrapping the post-rent logic sorentedBuffer.Dispose()is guaranteed to run.
// Let the constructor to strip any redundant bits
BigInteger result = new BigInteger(byteBuffer, isBigEndian: !BitConverter.IsLittleEndian);
rentedBuffer.Dispose();
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt128Tests.GenericMath.cs:283
- This is inside
UInt128’sReverseBitsTest, but it assertsBinaryIntegerHelper<ulong>.ReverseBits(...). This looks like a copy/paste mistake and weakens coverage of theUInt128implementation. Consider removing this line or converting it into an assertion againstBinaryIntegerHelper<UInt128>.ReverseBits(...).
Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int128Tests.GenericMath.cs:284
- This is inside
Int128’sReverseBitsTest, but it assertsBinaryIntegerHelper<ulong>.ReverseBits(...). This appears to be an accidentalulongassertion in the wrong test suite. Consider removing it or replacing it with anInt128-specific assertion.
Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));
src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs:337
nuint/nintbit-manipulation APIs in these files are often annotated with[Intrinsic](e.g.,PopCount,RotateLeft/Right) to help the JIT recognize and optimize patterns. If this method is intended to be treated similarly, consider adding[Intrinsic]for consistency and potential codegen benefits.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
public static nuint ReverseBits(nuint value)
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 32 out of 32 changed files in this pull request and generated no new comments.
Suppressed comments (2)
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/UInt128Tests.GenericMath.cs:283
- This assertion is testing
ulongbit-reversal inside theUInt128test file, duplicating coverage already present inUInt64Tests.GenericMathand making this test less focused onUInt128behavior. Consider removing it and keeping onlyUInt128-specific cases here.
Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));
src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Int128Tests.GenericMath.cs:284
- This assertion is exercising
ulongbit-reversal inside theInt128test file, duplicating theUInt64Tests.GenericMathcoverage and making this test less focused onInt128behavior. Consider removing it.
Assert.Equal(0x80402010_08040201, BinaryIntegerHelper<ulong>.ReverseBits(0x80402010_08040201));
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 32 out of 32 changed files in this pull request and generated no new comments.
Suppressed comments (7)
Previously missed (7) — in code that hasn't changed since the last review.
src/libraries/System.Private.CoreLib/src/System/UInt32.cs:330
ReverseBitsis the same kind of bit-operation helper asLeadingZeroCount/PopCount/Rotate*in this file, but it isn't marked[Intrinsic]. The approved proposal text also calls out[Intrinsic]for future JIT intrinsification, so this should likely be consistent with the other helpers here.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
public static uint ReverseBits(uint value)
{
src/libraries/System.Private.CoreLib/src/System/Int32.cs:317
ReverseBitsis missing[Intrinsic]even though the other core bit-operation helpers in this type are annotated (e.g.,LeadingZeroCount,PopCount,Rotate*). If this is intended to be a JIT intrinsic in the future, it should be marked consistently here.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
public static int ReverseBits(int value)
{
src/libraries/System.Private.CoreLib/src/System/UInt64.cs:337
ReverseBitsis missing[Intrinsic]while neighboringPopCount/Rotate*helpers are[Intrinsic]. Marking it would keep the API consistent and aligns with the linked proposal's expectation of[Intrinsic]for potential JIT recognition.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
public static ulong ReverseBits(ulong value)
{
src/libraries/System.Private.CoreLib/src/System/Int64.cs:314
ReverseBitsis missing the[Intrinsic]annotation used for other fundamental bit operations in this file. If the intent is future JIT intrinsification, it should be annotated consistently.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
public static long ReverseBits(long value)
{
src/libraries/System.Private.CoreLib/src/System/IntPtr.cs:347
nint.ReverseBitsis the native-size counterpart of the other[Intrinsic]bit helpers onIntPtr(e.g.,PopCount,Rotate*), but it isn't marked[Intrinsic]. Adding it would keep the pattern consistent and avoids it being "the odd one out" in this section.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
public static nint ReverseBits(nint value)
{
src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs:339
nuint.ReverseBitssits alongside other[Intrinsic]helpers (LeadingZeroCount,PopCount,Rotate*), but it isn't annotated[Intrinsic]. Even if it stays as a wrapper, marking it would keep this section consistent.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)"/>
public static nuint ReverseBits(nuint value)
{
src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs:3453
- The linked approved-API issue's top post currently states "BigInteger uses the DIM" (minimal two's complement byte representation), but this PR adds a substantial BigInteger-specific implementation with a different goal (explicit 32-bit semantics + round-tripping invariants). That might be the right behavior, but it should be reconciled with the issue/proposal text (or explicitly called out in the PR description) so the intended BigInteger semantics are clear to reviewers and API consumers.
/// <inheritdoc cref="IBinaryInteger{TSelf}.ReverseBits(TSelf)" />
static BigInteger IBinaryInteger<BigInteger>.ReverseBits(BigInteger value)
{
// Reversing bits makes little sense to BigInteger which is effectively infinite.
// Only ensure a proper round-tripping behavior.
Closes #125879