xref: /llvm-project/libc/src/stdlib/rand.cpp (revision 5ff3ff33ff930e4ec49da7910612d8a41eb068cb)
1 //===-- Implementation of rand --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/stdlib/rand.h"
10 #include "src/__support/common.h"
11 #include "src/__support/macros/config.h"
12 #include "src/__support/threads/sleep.h"
13 #include "src/stdlib/rand_util.h"
14 
15 namespace LIBC_NAMESPACE_DECL {
16 
17 // An implementation of the xorshift64star pseudo random number generator. This
18 // is a good general purpose generator for most non-cryptographics applications.
19 LLVM_LIBC_FUNCTION(int, rand, (void)) {
20   unsigned long orig = rand_next.load(cpp::MemoryOrder::RELAXED);
21   for (;;) {
22     unsigned long x = orig;
23     x ^= x >> 12;
24     x ^= x << 25;
25     x ^= x >> 27;
26     if (rand_next.compare_exchange_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
27                                           cpp::MemoryOrder::RELAXED))
28       return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
29     sleep_briefly();
30   }
31 }
32 
33 } // namespace LIBC_NAMESPACE_DECL
34