[libcxx-commits] [PATCH] D114129: [libc++] Fix `uniform_int_distribution` for 128-bit result type

Fabian Wolff via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Wed Nov 17 16:46:33 PST 2021


fwolff created this revision.
fwolff added reviewers: Quuxplusone, Mordante, libc++.
fwolff added a project: libc++.
fwolff requested review of this revision.
Herald added a subscriber: libcxx-commits.
Herald added 1 blocking reviewer(s): libc++.

Fixes PR#51520 <https://bugs.llvm.org/show_bug.cgi?id=51520>. The problem is that `uniform_int_distribution` currently uses an unsigned integer with at most 64 bits internally, which is then casted to the desired result type. If the result type is `int64_t`, this will produce a negative number if the most significant bit is set, but if the result type is `__int128_t`, the value remains non-negative and will be out of bounds for the example in PR#51520. (The reason why it also seems to work if the upper or lower bound is changed is because this branch <https://github.com/llvm/llvm-project/blob/6d28dffb6bf4c97848290b9aee3c19025470e54a/libcxx/include/__random/uniform_int_distribution.h#L266-L267> will then no longer be taken, and proper rejection sampling takes place.)

The bigger issue here is probably that `uniform_int_distribution` can be instantiated with `__int128_t` but will silently produce incorrect results (only the lowest 64 bits can ever be set). libstdc++ also supports `__int128_t` as a result type, so I have simply extended the maximum width of the internal intermediate result type.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114129

Files:
  libcxx/include/__bits
  libcxx/include/__random/uniform_int_distribution.h
  libcxx/test/std/numerics/rand/rand.dis/rand.dist.uni/rand.dist.uni.int/int128.pass.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D114129.388060.patch
Type: text/x-patch
Size: 5290 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20211118/e657e2db/attachment.bin>


More information about the libcxx-commits mailing list