Fix $urandom_range when the range is 0 ... UINT_MAX (#3161)

This commit is contained in:
Iru Cai 2021-10-11 20:45:19 +08:00 committed by GitHub
parent a9646cf45c
commit 9731ec76e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 0 deletions

View File

@ -82,9 +82,12 @@ extern IData VL_RANDOM_SEEDED_II(int obits, IData seed) VL_MT_SAFE;
inline IData VL_URANDOM_RANGE_I(IData hi, IData lo) {
vluint64_t rnd = vl_rand64();
if (VL_LIKELY(hi > lo)) {
// (hi - lo + 1) can be zero when hi is UINT_MAX and lo is zero
if (VL_UNLIKELY(hi - lo + 1 == 0)) return rnd;
// Modulus isn't very fast but it's common that hi-low is power-of-two
return (rnd % (hi - lo + 1)) + lo;
} else {
if (VL_UNLIKELY(lo - hi + 1 == 0)) return rnd;
return (rnd % (lo - hi + 1)) + hi;
}
}

View File

@ -37,6 +37,9 @@ module t(/*AUTOARG*/);
v2 = $urandom_range(v1, v1);
if (v1 != v2) $stop;
v2 = $urandom_range(0, 32'hffffffff);
if (v2 == v1) $stop;
for (int test = 0; test < 20; ++test) begin
v1 = 2;
v1 = $urandom_range(0, v1);