84fcdcbc76adf840ccb62cfdc95110b612327c79
[oota-llvm.git] / include / llvm / Support / RandomNumberGenerator.h
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 <random>
21
22 namespace llvm {
23
24 /// A random number generator.
25 /// Instances of this class should not be shared across threads.
26 class RandomNumberGenerator {
27 public:
28   /// Seeds and salts the underlying RNG engine. The salt of type StringRef
29   /// is passed into the constructor. The seed can be set on the command
30   /// line via -rng-seed=<uint64>.
31   /// The reason for the salt is to ensure different random streams even if
32   /// the same seed is used for multiple invocations of the compiler.
33   /// A good salt value should add additional entropy and be constant across
34   /// different machines (i.e., no paths) to allow for reproducible builds.
35   /// An instance of this class can be retrieved from the current Module.
36   /// \see Module::getRNG
37   RandomNumberGenerator(StringRef Salt);
38
39   /// Returns a random number in the range [0, Max).
40   uint64_t next(uint64_t Max);
41
42 private:
43   // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000
44   // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
45   std::mt19937_64 Generator;
46
47   // Noncopyable.
48   RandomNumberGenerator(const RandomNumberGenerator &other) = delete;
49   RandomNumberGenerator &operator=(const RandomNumberGenerator &other) = delete;
50 };
51 }
52
53 #endif