1 //==- llvm/Support/RandomNumberGenerator.h - RNG for diversity ---*- C++ -*-==//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines an abstraction for deterministic random number
10 // generation (RNG). Note that the current implementation is not
11 // cryptographically secure as it uses the C++11 <random> facilities.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
16 #define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows.
21 #include <system_error>
26 /// A random number generator.
28 /// Instances of this class should not be shared across threads. The
29 /// seed should be set by passing the -rng-seed=<uint64> option. Use
30 /// Module::createRNG to create a new RNG instance for use with that
32 class RandomNumberGenerator
{
34 // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000
35 // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
36 // This RNG is deterministically portable across C++11
38 using generator_type
= std::mt19937_64
;
41 using result_type
= generator_type::result_type
;
43 /// Returns a random number in the range [0, Max).
44 result_type
operator()();
46 static constexpr result_type
min() { return generator_type::min(); }
47 static constexpr result_type
max() { return generator_type::max(); }
50 /// Seeds and salts the underlying RNG engine.
52 /// This constructor should not be used directly. Instead use
53 /// Module::createRNG to create a new RNG salted with the Module ID.
54 RandomNumberGenerator(StringRef Salt
);
56 generator_type Generator
;
59 RandomNumberGenerator(const RandomNumberGenerator
&other
) = delete;
60 RandomNumberGenerator
&operator=(const RandomNumberGenerator
&other
) = delete;
65 // Get random vector of specified size
66 std::error_code
getRandomBytes(void *Buffer
, size_t Size
);