xref: /llvm-project/libc/src/stdlib/rand.cpp (revision ce9035f5bd3aa09cbd899489cdbc7f6c18acf1e3)
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/threads/sleep.h"
12 #include "src/stdlib/rand_util.h"
13 
14 namespace LIBC_NAMESPACE {
15 
16 // An implementation of the xorshift64star pseudo random number generator. This
17 // is a good general purpose generator for most non-cryptographics applications.
18 LLVM_LIBC_FUNCTION(int, rand, (void)) {
19   unsigned long orig = rand_next.load(cpp::MemoryOrder::RELAXED);
20   for (;;) {
21     unsigned long x = orig;
22     x ^= x >> 12;
23     x ^= x << 25;
24     x ^= x >> 27;
25     if (rand_next.compare_exchange_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
26                                           cpp::MemoryOrder::RELAXED))
27       return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
28     sleep_briefly();
29   }
30 }
31 
32 } // namespace LIBC_NAMESPACE
33