shithub: drawcpu

ref: 746e0c9217ab9ee1884b721a955b712d59b13549
dir: /posix-riscv64/cas.c/

View raw version
#include "u.h"
#include "libc.h"

#ifndef __has_builtin
#define __has_builtin(x) 0
#endif

int
cas(int *x, int old, int new)
{
#if __has_builtin(__atomic_compare_exchange_n)
    return __atomic_compare_exchange_n(x, &old, new, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);
#else
    int result;
    __asm__ __volatile__(
        "lr.w %0, %2\n"
        "bne %0, %3, 1f\n"
        "sc.w %0, %4, %2\n"
        "seqz %0, %0\n"
        "1:"
        : "=&r" (result), "=m" (*x)
        : "m" (*x), "r" (old), "r" (new)
        : "cc");
    return result;
#endif
}