Skip to content

Commit 94e386b

Browse files
authored
Rollup merge of rust-lang#128666 - pitaj:intrinsic-overflow_checks, r=BoxyUwU
Add `overflow_checks` intrinsic This adds an intrinsic which allows code in a pre-built library to inherit the overflow checks option from a crate depending on it. This enables code in the standard library to explicitly change behavior based on whether `overflow_checks` are enabled, regardless of the setting used when standard library was compiled. This is very similar to the `ub_checks` intrinsic, and refactors the two to use a common mechanism. The primary use case for this is to allow the new `RangeFrom` iterator to yield the maximum element before overflowing, as requested [here](rust-lang#125687 (comment)). This PR includes a working `IterRangeFrom` implementation based on this new intrinsic that exhibits the desired behavior. [Prior discussion on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Ability.20to.20select.20code.20based.20on.20.60overflow_checks.60.3F)
2 parents d6e65f9 + 0c98a31 commit 94e386b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

core/src/intrinsics/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2589,6 +2589,24 @@ pub const fn ub_checks() -> bool {
25892589
cfg!(ub_checks)
25902590
}
25912591

2592+
/// Returns whether we should perform some overflow-checking at runtime. This eventually evaluates to
2593+
/// `cfg!(overflow_checks)`, but behaves different from `cfg!` when mixing crates built with different
2594+
/// flags: if the crate has overflow checks enabled or carries the `#[rustc_inherit_overflow_checks]`
2595+
/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2596+
/// a crate that does not delay evaluation further); otherwise it can happen any time.
2597+
///
2598+
/// The common case here is a user program built with overflow_checks linked against the distributed
2599+
/// sysroot which is built without overflow_checks but with `#[rustc_inherit_overflow_checks]`.
2600+
/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2601+
/// `#[inline]`), gating assertions on `overflow_checks()` rather than `cfg!(overflow_checks)` means that
2602+
/// assertions are enabled whenever the *user crate* has overflow checks enabled. However if the
2603+
/// user has overflow checks disabled, the checks will still get optimized out.
2604+
#[inline(always)]
2605+
#[rustc_intrinsic]
2606+
pub const fn overflow_checks() -> bool {
2607+
cfg!(debug_assertions)
2608+
}
2609+
25922610
/// Allocates a block of memory at compile time.
25932611
/// At runtime, just returns a null pointer.
25942612
///

0 commit comments

Comments
 (0)