blob: 81d0411d60b465920322cf4b515a0f8f488eb00a [file] [log] [blame]
JF Bastien144829d2014-06-25 15:21:42 +00001//===-- 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//
JF Bastiene6acbdc2014-12-17 18:12:10 +000010// This file implements deterministic random number generation (RNG).
JF Bastien144829d2014-06-25 15:21:42 +000011// The current implementation is NOT cryptographically secure as it uses
12// the C++11 <random> facilities.
13//
14//===----------------------------------------------------------------------===//
15
Benjamin Kramer4073ce82015-03-23 18:19:41 +000016#include "llvm/Support/RandomNumberGenerator.h"
JF Bastien144829d2014-06-25 15:21:42 +000017#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Debug.h"
Benjamin Kramer4073ce82015-03-23 18:19:41 +000019#include "llvm/Support/raw_ostream.h"
JF Bastien144829d2014-06-25 15:21:42 +000020
21using namespace llvm;
22
Benjamin Kramer4073ce82015-03-23 18:19:41 +000023#define DEBUG_TYPE "rng"
24
JF Bastien144829d2014-06-25 15:21:42 +000025// Tracking BUG: 19665
26// http://llvm.org/bugs/show_bug.cgi?id=19665
27//
28// Do not change to cl::opt<uint64_t> since this silently breaks argument parsing.
29static cl::opt<unsigned long long>
30Seed("rng-seed", cl::value_desc("seed"),
31 cl::desc("Seed for the random number generator"), cl::init(0));
32
33RandomNumberGenerator::RandomNumberGenerator(StringRef Salt) {
34 DEBUG(
35 if (Seed == 0)
JF Bastiene6acbdc2014-12-17 18:12:10 +000036 dbgs() << "Warning! Using unseeded random number generator.\n"
JF Bastien144829d2014-06-25 15:21:42 +000037 );
38
JF Bastiene6acbdc2014-12-17 18:12:10 +000039 // Combine seed and salts using std::seed_seq.
40 // Data: Seed-low, Seed-high, Salt
41 // Note: std::seed_seq can only store 32-bit values, even though we
42 // are using a 64-bit RNG. This isn't a problem since the Mersenne
43 // twister constructor copies these correctly into its initial state.
JF Bastien144829d2014-06-25 15:21:42 +000044 std::vector<uint32_t> Data;
JF Bastiene6acbdc2014-12-17 18:12:10 +000045 Data.reserve(2 + Salt.size());
JF Bastien144829d2014-06-25 15:21:42 +000046 Data.push_back(Seed);
47 Data.push_back(Seed >> 32);
48
JF Bastiene6acbdc2014-12-17 18:12:10 +000049 std::copy(Salt.begin(), Salt.end(), Data.end());
JF Bastien144829d2014-06-25 15:21:42 +000050
51 std::seed_seq SeedSeq(Data.begin(), Data.end());
52 Generator.seed(SeedSeq);
53}
54
JF Bastiene6acbdc2014-12-17 18:12:10 +000055uint_fast64_t RandomNumberGenerator::operator()() {
56 return Generator();
JF Bastien144829d2014-06-25 15:21:42 +000057}