1 //===-- RandomNumberGenerator.cpp - Implement RNG class -------------------===// 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 implements random number generation (RNG). 11 // The current implementation is NOT cryptographically secure as it uses 12 // the C++11 <random> facilities. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #define DEBUG_TYPE "rng" 17 #include "llvm/Support/RandomNumberGenerator.h" 18 #include "llvm/Support/CommandLine.h" 19 #include "llvm/Support/Debug.h" 20 21 using namespace llvm; 22 23 // Tracking BUG: 19665 24 // http://llvm.org/bugs/show_bug.cgi?id=19665 25 // 26 // Do not change to cl::opt<uint64_t> since this silently breaks argument parsing. 27 static cl::opt<unsigned long long> 28 Seed("rng-seed", cl::value_desc("seed"), 29 cl::desc("Seed for the random number generator"), cl::init(0)); 30 RandomNumberGenerator(StringRef Salt)31RandomNumberGenerator::RandomNumberGenerator(StringRef Salt) { 32 DEBUG( 33 if (Seed == 0) 34 errs() << "Warning! Using unseeded random number generator.\n" 35 ); 36 37 // Combine seed and salt using std::seed_seq. 38 // Entropy: Seed-low, Seed-high, Salt... 39 std::vector<uint32_t> Data; 40 Data.reserve(2 + Salt.size()/4 + 1); 41 Data.push_back(Seed); 42 Data.push_back(Seed >> 32); 43 44 uint32_t Pack = 0; 45 for (size_t I = 0; I < Salt.size(); ++I) { 46 Pack <<= 8; 47 Pack += Salt[I]; 48 49 if (I%4 == 3) 50 Data.push_back(Pack); 51 } 52 Data.push_back(Pack); 53 54 std::seed_seq SeedSeq(Data.begin(), Data.end()); 55 Generator.seed(SeedSeq); 56 } 57 next(uint64_t Max)58uint64_t RandomNumberGenerator::next(uint64_t Max) { 59 std::uniform_int_distribution<uint64_t> distribution(0, Max - 1); 60 return distribution(Generator); 61 } 62