blob: b874d8392bdfd43c83ddbb8f4c09d4bbb1065918 [file] [log] [blame]
Matt Wala1bd2fce2014-08-08 14:02:09 -07001//===- subzero/src/IceRNG.cpp - PRNG implementation -----------------------===//
2//
3// The Subzero Code Generator
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 the random number generator.
11//
12//===----------------------------------------------------------------------===//
13
14#include <time.h>
15
16#include "llvm/Support/CommandLine.h"
17
18#include "IceRNG.h"
19
20namespace Ice {
21
22namespace {
23namespace cl = llvm::cl;
24
25cl::opt<unsigned long long>
26RandomSeed("rng-seed", cl::desc("Seed the random number generator"),
27 cl::init(time(0)));
28
Matt Walac3302742014-08-15 16:21:56 -070029const unsigned MAX = 2147483647;
30
Matt Wala1bd2fce2014-08-08 14:02:09 -070031} // end of anonymous namespace
32
33// TODO(wala,stichnot): Switch to RNG implementation from LLVM or C++11.
34//
35// TODO(wala,stichnot): Make it possible to replay the RNG sequence in a
36// subsequent run, for reproducing a bug. Print the seed in a comment
37// in the asm output. Embed the seed in the binary via metadata that an
38// attacker can't introspect.
39RandomNumberGenerator::RandomNumberGenerator(llvm::StringRef)
40 : State(RandomSeed) {}
41
42uint64_t RandomNumberGenerator::next(uint64_t Max) {
43 // Lewis, Goodman, and Miller (1969)
Matt Walac3302742014-08-15 16:21:56 -070044 State = (16807 * State) % MAX;
Matt Wala1bd2fce2014-08-08 14:02:09 -070045 return State % Max;
46}
47
Matt Walac3302742014-08-15 16:21:56 -070048bool RandomNumberGeneratorWrapper::getTrueWithProbability(float Probability) {
49 return RNG.next(MAX) < Probability * MAX;
50}
51
Matt Wala1bd2fce2014-08-08 14:02:09 -070052} // end of namespace Ice