blob: a6b9adf5b93bfb2b867ebc4ce3e84b33ec7a5e07 [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//===----------------------------------------------------------------------===//
Andrew Scull9612d322015-07-06 14:53:25 -07009///
10/// \file
11/// This file implements the random number generator.
12///
Matt Wala1bd2fce2014-08-08 14:02:09 -070013//===----------------------------------------------------------------------===//
14
Matt Wala1bd2fce2014-08-08 14:02:09 -070015#include "IceRNG.h"
16
John Porto67f8de92015-06-25 10:14:17 -070017#include <time.h>
18
Matt Wala1bd2fce2014-08-08 14:02:09 -070019namespace Ice {
20
21namespace {
John Porto67f8de92015-06-25 10:14:17 -070022constexpr unsigned MAX = 2147483647;
Matt Wala1bd2fce2014-08-08 14:02:09 -070023} // end of anonymous namespace
24
25// TODO(wala,stichnot): Switch to RNG implementation from LLVM or C++11.
26//
27// TODO(wala,stichnot): Make it possible to replay the RNG sequence in a
28// subsequent run, for reproducing a bug. Print the seed in a comment
29// in the asm output. Embed the seed in the binary via metadata that an
30// attacker can't introspect.
Jan Voung1f47ad02015-03-20 15:01:26 -070031RandomNumberGenerator::RandomNumberGenerator(uint64_t Seed, llvm::StringRef)
32 : State(Seed) {}
Matt Wala1bd2fce2014-08-08 14:02:09 -070033
34uint64_t RandomNumberGenerator::next(uint64_t Max) {
35 // Lewis, Goodman, and Miller (1969)
Matt Walac3302742014-08-15 16:21:56 -070036 State = (16807 * State) % MAX;
Matt Wala1bd2fce2014-08-08 14:02:09 -070037 return State % Max;
38}
39
Matt Walac3302742014-08-15 16:21:56 -070040bool RandomNumberGeneratorWrapper::getTrueWithProbability(float Probability) {
41 return RNG.next(MAX) < Probability * MAX;
42}
43
Matt Wala1bd2fce2014-08-08 14:02:09 -070044} // end of namespace Ice