Skip to content

Commit f8ad92d

Browse files
committed
Random Number Generator (llvm)
Summary: Provides an abstraction for a random number generator (RNG) that produces a stream of pseudo-random numbers. The current implementation uses C++11 facilities and is therefore not cryptographically secure. The RNG is salted with the text of the current command line invocation. In addition, a user may specify a seed (reproducible builds). In clang, the seed can be set via -frandom-seed=X In the back end, the seed can be set via -rng-seed=X This is the llvm part of the patch. clang part: D3391 Reviewers: ahomescu, rinon, nicholas, jfb Reviewed By: jfb Subscribers: jfb, perl Differential Revision: http://reviews.llvm.org/D3390 llvm-svn: 211145
1 parent f0ec9af commit f8ad92d

File tree

5 files changed

+128
-1
lines changed

5 files changed

+128
-1
lines changed

‎llvm/include/llvm/IR/Module.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ namespace llvm {
2929
class FunctionType;
3030
class GVMaterializer;
3131
class LLVMContext;
32+
class RandomNumberGenerator;
3233
class StructType;
3334
template<typename T> struct DenseMapInfo;
3435
template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
@@ -201,6 +202,8 @@ class Module {
201202
std::string ModuleID; ///< Human readable identifier for the module
202203
std::string TargetTriple; ///< Platform target triple Module compiled on
203204
void *NamedMDSymTab; ///< NamedMDNode names.
205+
// Allow lazy initialization in const method.
206+
mutable RandomNumberGenerator *RNG; ///< The random number generator for this module.
204207

205208
// We need to keep the string because the C API expects us to own the string
206209
// representation.
@@ -249,6 +252,11 @@ class Module {
249252
/// @returns a string containing the module-scope inline assembly blocks.
250253
const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
251254

255+
/// Get the RandomNumberGenerator for this module. The RNG can be
256+
/// seeded via -rng-seed=<uint64> and is salted with the ModuleID.
257+
/// The returned RNG should not be shared across threads.
258+
RandomNumberGenerator &getRNG() const;
259+
252260
/// @}
253261
/// @name Module Level Mutators
254262
/// @{
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

‎llvm/lib/IR/Module.cpp‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
#include "llvm/IR/LLVMContext.h"
2525
#include "llvm/IR/LeakDetector.h"
2626
#include "llvm/Support/Dwarf.h"
27+
#include "llvm/Support/Path.h"
28+
#include "llvm/Support/RandomNumberGenerator.h"
2729
#include <algorithm>
2830
#include <cstdarg>
2931
#include <cstdlib>
@@ -44,7 +46,7 @@ template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
4446
//
4547

4648
Module::Module(StringRef MID, LLVMContext &C)
47-
: Context(C), Materializer(), ModuleID(MID), DL("") {
49+
: Context(C), Materializer(), ModuleID(MID), RNG(nullptr), DL("") {
4850
ValSymTab = new ValueSymbolTable();
4951
NamedMDSymTab = new StringMap<NamedMDNode *>();
5052
Context.addModule(this);
@@ -59,6 +61,7 @@ Module::~Module() {
5961
NamedMDList.clear();
6062
delete ValSymTab;
6163
delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
64+
delete RNG;
6265
}
6366

6467
/// getNamedValue - Return the first global value in the module with
@@ -355,6 +358,16 @@ const DataLayout *Module::getDataLayout() const {
355358
return &DL;
356359
}
357360

361+
// We want reproducible builds, but ModuleID may be a full path so we just use
362+
// the filename to salt the RNG (although it is not guaranteed to be unique).
363+
RandomNumberGenerator &Module::getRNG() const {
364+
if (RNG == nullptr) {
365+
StringRef Salt = sys::path::filename(ModuleID);
366+
RNG = new RandomNumberGenerator(Salt);
367+
}
368+
return *RNG;
369+
}
370+
358371
//===----------------------------------------------------------------------===//
359372
// Methods to control the materialization of GlobalValues in the Module.
360373
//

‎llvm/lib/Support/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ add_llvm_library(LLVMSupport
4141
MD5.cpp
4242
PluginLoader.cpp
4343
PrettyStackTrace.cpp
44+
RandomNumberGenerator.cpp
4445
Regex.cpp
4546
SmallPtrSet.cpp
4647
SmallVector.cpp
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
31+
RandomNumberGenerator::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+
size_t Size = Salt.size() + 2;
40+
uint32_t Data[Size];
41+
Data[0] = Seed;
42+
Data[1] = Seed >> 32;
43+
std::copy_n(Salt.begin(), Salt.size(), Data + 2);
44+
45+
std::seed_seq SeedSeq(Data, Data + Size);
46+
Generator.seed(SeedSeq);
47+
}
48+
49+
uint64_t RandomNumberGenerator::next(uint64_t Max) {
50+
std::uniform_int_distribution<uint64_t> distribution(0, Max - 1);
51+
return distribution(Generator);
52+
}

0 commit comments

Comments
 (0)