[llvm] MathExtras: rewrite some methods to never overflow (PR #95556)
Jay Foad via llvm-commits
llvm-commits at lists.llvm.org
Sat Jun 15 01:05:35 PDT 2024
================
@@ -461,9 +467,13 @@ inline int64_t mod(int64_t Numerator, int64_t Denominator) {
return Mod < 0 ? Mod + Denominator : Mod;
}
-/// Returns the integer nearest(Numerator / Denominator).
+/// Returns (Numerator / Denominator) rounded by round-half-up. Guaranteed to
+/// never overflow.
inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
- return (Numerator + (Denominator / 2)) / Denominator;
+ uint64_t Mod = Numerator % Denominator;
+ uint64_t HalfDenomFloor = Denominator / 2;
+ uint64_t TieBreaker = ((Mod == HalfDenomFloor) & ~(Denominator & 1));
+ return (Numerator / Denominator) + (Mod > HalfDenomFloor || TieBreaker);
----------------
jayfoad wrote:
```suggestion
return (Numerator / Denominator) + (Mod > (Denominator - 1) / 2);
```
https://github.com/llvm/llvm-project/pull/95556
More information about the llvm-commits
mailing list