about summary refs log tree commit diff
path: root/library
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2024-06-25 02:50:37 +0000
committerbors <bors@rust-lang.org>2024-06-25 02:50:37 +0000
commitfc555cd832ee743ff5410c35de2b0dd59ec4322e (patch)
tree421b3f2a5fd13889a9b4a09cb6bd35823be6af1a /library
parent5b270e1198e911247244b035a6f06ce3af0a4420 (diff)
parentec9e35618dd9d4b55282b340aa29fb8c78691aca (diff)
downloadrust-fc555cd832ee743ff5410c35de2b0dd59ec4322e.tar.gz
rust-fc555cd832ee743ff5410c35de2b0dd59ec4322e.zip
Auto merge of #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 https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305 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 https://github.com/rust-lang/hashbrown/issues/509 before

cc https://github.com/llvm/llvm-project/issues/80637 for how LLVM is unlikely to do this itself
Diffstat (limited to 'library')
-rw-r--r--library/core/src/num/uint_macros.rs15
1 files changed, 13 insertions, 2 deletions
diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs
index ffe2ca2440e..cd74cece0d1 100644
--- a/library/core/src/num/uint_macros.rs
+++ b/library/core/src/num/uint_macros.rs
@@ -454,8 +454,19 @@ macro_rules! uint_impl {
                       without modifying the original"]
         #[inline]
         pub const fn checked_add(self, rhs: Self) -> Option<Self> {
-            let (a, b) = self.overflowing_add(rhs);
-            if unlikely!(b) { None } else { Some(a) }
+            // This used to use `overflowing_add`, but that means it ends up being
+            // a `wrapping_add`, losing some optimization opportunities. Notably,
+            // phrasing it this way helps `.checked_add(1)` optimize to a check
+            // against `MAX` and a `add nuw`.
+            // Per <https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305>,
+            // LLVM is happy to re-form the intrinsic later if useful.
+
+            if unlikely!(intrinsics::add_with_overflow(self, rhs).1) {
+                None
+            } else {
+                // SAFETY: Just checked it doesn't overflow
+                Some(unsafe { intrinsics::unchecked_add(self, rhs) })
+            }
         }
 
         /// Strict integer addition. Computes `self + rhs`, panicking