1 //==- llvm/Support/RandomNumberGenerator.h - RNG for diversity ---*- C++ -*-==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines an abstraction for random number generation (RNG). 11 // Note that the current implementation is not cryptographically secure 12 // as it uses the C++11 <random> facilities. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_ 17 #define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_ 18 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/Support/Compiler.h" 21 #include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows. 22 #include <random> 23 24 namespace llvm { 25 26 /// A random number generator. 27 /// Instances of this class should not be shared across threads. 28 class RandomNumberGenerator { 29 public: 30 /// Seeds and salts the underlying RNG engine. The salt of type StringRef 31 /// is passed into the constructor. The seed can be set on the command 32 /// line via -rng-seed=<uint64>. 33 /// The reason for the salt is to ensure different random streams even if 34 /// the same seed is used for multiple invocations of the compiler. 35 /// A good salt value should add additional entropy and be constant across 36 /// different machines (i.e., no paths) to allow for reproducible builds. 37 /// An instance of this class can be retrieved from the current Module. 38 /// \see Module::getRNG 39 RandomNumberGenerator(StringRef Salt); 40 41 /// Returns a random number in the range [0, Max). 42 uint64_t next(uint64_t Max); 43 44 private: 45 // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000 46 // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine 47 std::mt19937_64 Generator; 48 49 // Noncopyable. 50 RandomNumberGenerator(const RandomNumberGenerator &other) 51 LLVM_DELETED_FUNCTION; 52 RandomNumberGenerator & 53 operator=(const RandomNumberGenerator &other) LLVM_DELETED_FUNCTION; 54 }; 55 } 56 57 #endif 58