[libc-commits] [libc] [libc] Change rand implementation so all tests pass in both 32- and 64-bit systems (PR #98692)

Joseph Huber via libc-commits libc-commits at lists.llvm.org
Fri Jul 12 20:49:31 PDT 2024


================
@@ -13,20 +13,33 @@
 
 namespace LIBC_NAMESPACE {
 
-// An implementation of the xorshift64star pseudo random number generator. This
+// An implementation of the xorshift* pseudo random number generator. This
 // is a good general purpose generator for most non-cryptographics applications.
-LLVM_LIBC_FUNCTION(int, rand, (void)) {
+static inline unsigned long xorshiftstar(unsigned long a, unsigned long b,
+                                         unsigned long c, unsigned long d) {
   unsigned long orig = rand_next.load(cpp::MemoryOrder::RELAXED);
   for (;;) {
     unsigned long x = orig;
-    x ^= x >> 12;
-    x ^= x << 25;
-    x ^= x >> 27;
+    x ^= x >> a;
+    x ^= x << b;
+    x ^= x >> c;
     if (rand_next.compare_exchange_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
                                           cpp::MemoryOrder::RELAXED))
-      return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
+      return x * d;
     sleep_briefly();
   }
 }
 
+// An implementation of the xorshift64star pseudo random number generator. This
+// is a good general purpose generator for most non-cryptographics applications.
+LLVM_LIBC_FUNCTION(int, rand, (void)) {
+  int res;
+  if constexpr (sizeof(void *) == sizeof(uint64_t))
----------------
jhuber6 wrote:

I think this should also be a common macro because I guarantee it's used somewhere else.

https://github.com/llvm/llvm-project/pull/98692


More information about the libc-commits mailing list