1//==- llvm/Support/RandomNumberGenerator.h - RNG for diversity ---*- C++ -*-==// 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// 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. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_ 16#define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_ 17 18#include "llvm/Support/Compiler.h" 19#include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows. 20#include <random> 21#include <system_error> 22 23namespace llvm { 24class StringRef; 25 26/// A random number generator. 27/// 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 31/// module. 32class RandomNumberGenerator { 33 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 37 // implementations. 38 using generator_type = std::mt19937_64; 39 40public: 41 using result_type = generator_type::result_type; 42 43 /// Returns a random number in the range [0, Max). 44 result_type operator()(); 45 46 static constexpr result_type min() { return generator_type::min(); } 47 static constexpr result_type max() { return generator_type::max(); } 48 49private: 50 /// Seeds and salts the underlying RNG engine. 51 /// 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); 55 56 generator_type Generator; 57 58 // Noncopyable. 59 RandomNumberGenerator(const RandomNumberGenerator &other) = delete; 60 RandomNumberGenerator &operator=(const RandomNumberGenerator &other) = delete; 61 62 friend class Module; 63}; 64 65// Get random vector of specified size 66std::error_code getRandomBytes(void *Buffer, size_t Size); 67} 68 69#endif 70