Skip to content

Commit a451b2a

Browse files
committed
Auto merge of rust-lang#126852 - scottmcm:more-checked-math-tweaks, r=Amanieu
Also get `add nuw` from `uN::checked_add` When I was doing this for `checked_{sub,shl,shr}`, it was mentioned rust-lang#124114 (comment) that it'd be worth trying for `checked_add` too. It makes a particularly-big difference for `x.checked_add(C)`, as doing this means that LLVM removes the intrinsic and does it as a normal `x <= MAX - C` instead. cc `@DianQK` who had commented about `checked_add` related to rust-lang/hashbrown#509 before cc llvm/llvm-project#80637 for how LLVM is unlikely to do this itself
2 parents 1bd207e + e4bc79d commit a451b2a

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

core/src/num/uint_macros.rs

+13-2
Original file line numberDiff line numberDiff line change
@@ -454,8 +454,19 @@ macro_rules! uint_impl {
454454
without modifying the original"]
455455
#[inline]
456456
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
457-
let (a, b) = self.overflowing_add(rhs);
458-
if unlikely!(b) { None } else { Some(a) }
457+
// This used to use `overflowing_add`, but that means it ends up being
458+
// a `wrapping_add`, losing some optimization opportunities. Notably,
459+
// phrasing it this way helps `.checked_add(1)` optimize to a check
460+
// against `MAX` and a `add nuw`.
461+
// Per <https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305>,
462+
// LLVM is happy to re-form the intrinsic later if useful.
463+
464+
if unlikely!(intrinsics::add_with_overflow(self, rhs).1) {
465+
None
466+
} else {
467+
// SAFETY: Just checked it doesn't overflow
468+
Some(unsafe { intrinsics::unchecked_add(self, rhs) })
469+
}
459470
}
460471

461472
/// Strict integer addition. Computes `self + rhs`, panicking

0 commit comments

Comments
 (0)