Index: include/llvm/Support/RandomNumberGenerator.h =================================================================== --- include/llvm/Support/RandomNumberGenerator.h (revision 229790) +++ include/llvm/Support/RandomNumberGenerator.h (working copy) @@ -33,6 +33,9 @@ public: /// Returns a random number in the range [0, Max). uint_fast64_t operator()(); + /// Returns a random number in the range [0, Limit). + /// Limit must be in range [1, Max]. + uint_fast64_t operator()(uint_fast64_t Limit); private: /// Seeds and salts the underlying RNG engine. Index: lib/Support/RandomNumberGenerator.cpp =================================================================== --- lib/Support/RandomNumberGenerator.cpp (revision 229790) +++ lib/Support/RandomNumberGenerator.cpp (working copy) @@ -53,3 +53,18 @@ uint_fast64_t RandomNumberGenerator::operator()() { return Generator(); } + +uint_fast64_t RandomNumberGenerator::operator()(uint_fast64_t Limit) { + assert(Limit > 0 && Limit <= Generator.max()); + uint_fast64_t Value, Remainder; + // If Limit doesn't divide Generator.max(), the value range doesn't + // factorise into equal stripes as the last stripe is partial. + // This is the case if Limit + Value - Remainder is too large. + // The expression is reorganised slightly to avoid possible + // (unsigned) overflow. + do { + Value = Generator(); + Remainder = Value % Limit; + } while (Value - Remainder > Generator.max() - Limit); + return Remainder; +}