Skip to content

Consider adding a LOCK CMPXCHG16B intrinsic method #28711

Open

Description

@gdkchan

Note

Edited by @tannergooding

The CMPXCHG16B instruction is required to do CAS or atomic read of 128-bits values in memory. Currently, atomic 64-bits read and CAS is supported on .NET with the Interlocked.CompareExchange and Interlocked.Read, however the same operations are not support for 128-bits values.

I believe that the main problem is that the required instruction (CMPXCHG16B) is not supported on all CPUs, for example, it is not supported by some very old AMD CPUs, however it is a requirement to run Windows 8.1 and 10, so I beleive that the amount of CPUs were this instruction is not supported is very small.

Due to the above limitation, I beleive that the best way to support it is through an intrinsic, and the user can check if the instruction is supported on the current CPU, much like the other IsSupported properties that are exposed on the other ISA classes. The API would be something like this:

namespace System.Runtime.Intrinsics.X86;

public static class Cmpxchg16B
{
    // Cx16 flag check using the CPUID instruction (cached).
    public static bool IsSupported { get; }
    
    // Returns the old value at destination.
    public static (ulong Lower, ulong Upper) InterlockedCompareExchange(void* destination, (ulong Lower, ulong Upper) value, (ulong Lower, ulong Upper) comparand);
}

The CMPXCHG16B sets the zero flag, if the values at destination and the comparand are equal, and clears it otherwise. It sets the ZF flag if the values were equal and leaves it clear otherwise. The address is required to be 16 byte aligned.

Activity

  1. jduncanator commented on Feb 17, 2019

    @jduncanator

    Thinking about this a little, a more appropriate signature might be one using an out parameter for the old value, something like:

    bool InterlockedCompareExchange16Bytes(Int128* destination, Int128 value, Int128 comparand, out Int128 oldValue);

    This would consolidate both InterlockedCompareExchange16Bytes and InterlockedCompareExchange16BytesEqual into a single method that covered both use cases.

    This would be fairly trivial to implement, as both the comparand and the "old value" (read from destination on failure) are stored in RDX:RAX, so an unconditional copy from RDX:RAX to oldValue at the end of the function call would be enough to handle setting oldValue.

  2. transferred this issue fromdotnet/corefxon Feb 1, 2020
  3. added this to the Future milestone on Feb 1, 2020
  4. added
    untriaged
    on Feb 23, 2020
  5. added
    api-suggestion
    and removed
    untriaged
    on Mar 25, 2020
  6. tannergooding commented on Mar 25, 2020

    @tannergooding
    Member

    We can't support this without either taking in a set of void* or exposing a new Int128 type

  7. jkotas commented on Mar 25, 2020

    @jkotas
    Member

    This is related/duplicate of #31911 . #31911 is a more general proposal.

  8. tannergooding commented on Mar 25, 2020

    @tannergooding
    Member

    I thought we couldn't support CMPXCHG16B on 32-bit systems due to tearing and so it needed to be an intrinsic?

  9. jkotas commented on Mar 25, 2020

    @jkotas
    Member

    #31911 avoids that problem by targeting pairs of pointer-sized items only.

  10. jkotas commented on Mar 25, 2020

    @jkotas
    Member

    But you are right that there are still problems with alignment with #31911 that would need to be solved (on both 32-bit and 64-bit platforms).

  11. omariom commented on Apr 30, 2021

    @omariom
    Contributor

    @jkotas

    there are still problems with alignment

    Then may be it should go Unsafe?
    Or a special unsafe subset of intrinsics.

  12. ayende commented on Jul 22, 2021

    @ayende
    Contributor

    How about handling it with:

    bool InterlockedCompareDCAS(Span<nint> destination, ReadOnly<nint>value, ReadOnlySpan<nint>comparand, Span<nint>oldValue);

    With the idea that nint will sort it out?

    This can be really useful for many scenarios, and the other options is:
    https://gist.github.com/jduncanator/ab17e4e476300d3eb0b7c19f6f38429a

  13. tannergooding commented on Jul 30, 2022

    @tannergooding
    Member

    But you are right that there are still problems with alignment with #31911

    There is also the consideration that while CMPXCHG8B is a "baseline" instruction, CMPXCHG16B is a newer instruction and not guaranteed to be available (similar for Arm64 since Atomics aren't required).

    We'd end up needing some IsSupported API to avoid any issues with tearing.

  14. 13 remaining items

  15. tannergooding commented on Feb 18, 2025

    @tannergooding
    Member

    couldn't BitwiseAtomic have its alignment set to 16?

    The GC has no support for such alignment today. If it did, then Int128, Vector128<T>, and some other types (which are ABI primitives and have a natural alignment of 16) would all be sufficient. Today, we only pack these types correctly (thus, struct S { byte x; Int128 y; } has a size of 32, but is only 8-byte aligned on a typical 64-bit computer).

    The GC adding such support is complex and is tracked by various other issues, all of which have been indicated by the GC team to be very complex and potentially not "pay for play". To my knowledge the GC is also not in a position to be able to even test the benefit vs drawbacks of supporting new alignments or changing the default alignment.

  16. colejohnson66 commented on Feb 19, 2025

    @colejohnson66
    Contributor

    If I'm understanding correctly, a "simple" alignment attribute like below would be very difficult to implement, especially considering GC interactions like compaction?

    namespace System.Runtime.InteropServices;
    
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field)]
    public sealed class AlignmentAttribute(int alignment)
    {
        public int Alignment { get; } = alignment;
    }
  17. jkotas commented on Feb 19, 2025

    @jkotas
    Member

    a "simple" alignment attribute like below would be very difficult to implement, especially considering GC interactions like compaction?

    #22990 (comment) is a discussion about what it would take.

  18. tannergooding commented on Jul 11, 2026

    @tannergooding
    Member

    While we have an Int128 type now, we still can't do this without the requisite alignment guarantees and so it'd have to be updated to be a signature taking void*

    I do believe that is reasonable and there's enough interest overall that it might be worth explicitly exposing this as a platform specific intrinsics or perhaps some explicit general-purpose API with a corresponding IsSupported check that can be queried about whether it even works.

    @jkotas, any objections to exposing this as a platform specific intrinsic, given that we're unlikely to get GC support or other features that allow such a general purpose API?

  19. jkotas commented on Jul 12, 2026

    @jkotas
    Member

    exposing this as a platform specific intrinsic

    fine with me

  20. added
    api-ready-for-review
    and removed
    api-suggestion
    on Jul 12, 2026
  21. tannergooding commented on Jul 12, 2026

    @tannergooding
    Member

    Updated to be:

    namespace System.Runtime.Intrinsics.X86;
    
    public static class Cmpxchg16B
    {
        // Cx16 flag check using the CPUID instruction (cached).
        public static bool IsSupported { get; }
        
        // Returns the old value at destination.
        public static (ulong Lower, ulong Upper) InterlockedCompareExchange(void* destination, (ulong Lower, ulong Upper) value, (ulong Lower, ulong Upper) comparand);
    }

    CMPXCHG16B is the official CPUID name, so using this matches our existing conventions.

    The JIT currently has no special understanding of Int128/UInt128 like it does for tuples and there are strict requirements to the registers used here, so this should simplify the JIT implementation. We could add that support, but it's then a bit "unique" compared to the rest of the intrinsics.

    The instruction technically has both LOCK# and non-locked versions, but the non-locked isn't super optimized on most hardware and can be added in the future if we really need some weaker 16 byte compare exchange.

    The ZF flag is written, but we really shouldn't have an issue with recognizing result == comparand after like we use for all the other cases.

  22. MichalPetryka commented on Jul 12, 2026

    @MichalPetryka
    Contributor

    Could it still be under System.Runtime.Intrinsics but not arch specific, keeping the 16B alignment semantics? That way all archs could share the intrinsic.

    EDIT: If that'll be the case, it might make more sense to make it pairwise and use nuint so that its usable for 32bit too.

  23. tannergooding commented on Jul 12, 2026

    @tannergooding
    Member

    That'd be a net new design, but not impossible. I'm willing to consider it if there's no pushback.

  24. bartonjs commented on Aug 11, 2026

    @bartonjs
    Member

    Video

    Added the missing "unsafe", otherwise looks good as proposed.

    namespace System.Runtime.Intrinsics.X86;
    
    public static class Cmpxchg16B
    {
        // Cx16 flag check using the CPUID instruction (cached).
        public static bool IsSupported { get; }
        
        // Returns the old value at destination.
        public static unsafe (ulong Lower, ulong Upper) InterlockedCompareExchange(void* destination, (ulong Lower, ulong Upper) value, (ulong Lower, ulong Upper) comparand);
    }
  25. added
    api-approved
    and removed
    api-ready-for-review
    on Aug 11, 2026
  26. to11mtm commented on Aug 26, 2026

    @to11mtm

    While we have an Int128 type now, we still can't do this without the requisite alignment guarantees and so it'd have to be updated to be a signature taking void*

    I do believe that is reasonable and there's enough interest overall that it might be worth explicitly exposing this as a platform specific intrinsics or perhaps some explicit general-purpose API with a corresponding IsSupported check that can be queried about whether it even works.

    @jkotas, any objections to exposing this as a platform specific intrinsic, given that we're unlikely to get GC support or other features that allow such a general purpose API?

    Possibly Dumb/dangerous question...

    Given how long this has been wanted (Won't quote all the other cases, but I think some issues are 10ish years old,) would it be worth having some sort of either Variant of or Attribute for Int128/UInt128 to hint at alignment in a way that fits well with how the GC aligns things today? Or would that still be just too much work to make happen without touching the GC?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarch-x64area-System.Runtime.Intrinsics

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions