Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions library/core/src/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,13 @@ pub fn forget_unsized<T: ?Sized>(t: T) {
#[rustc_const_stable(feature = "const_mem_size_of", since = "1.24.0")]
#[rustc_diagnostic_item = "mem_size_of"]
pub const fn size_of<T>() -> usize {
// By making this a constant, we also guarantee that the constant can be successfully evaluated
// in any program execution that actually executes `size_of`. Which is relevant because the
// constant can fail to evaluate if the type is too big. Someone might do something cursed where
// soundness relies on a certain type not being too big, and they check that by just invoking
// size_of on the type to ensure it exists, so if we fully DCE'd size_of calls that would be
// considered unsound... but by making this a constant, it participates in the usual "required
// consts" system, and we are safe.
<T as SizedTypeProperties>::SIZE
}

Expand Down
20 changes: 20 additions & 0 deletions tests/ui/layout/too-big-no-dce.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//! Ensure that we do not dead-code-eliminate `size_of` calls. That might hide "type too big"
//! errors!
//@ build-fail (test needs codegen)
//@ compile-flags: -O
//@ normalize-stderr: "\d{5}\d*" -> "NUMBER"

//~? ERROR too big for the target

#![crate_type = "lib"]

const PTR_BITS_MINUS_1: usize = std::mem::size_of::<*const ()>() * 8 - 1;

#[unsafe(no_mangle)] // ensure this gets monomorphized
pub fn f() {
assert_valid_type::<[u32; 1 << PTR_BITS_MINUS_1]>();
}

pub fn assert_valid_type<T>() {
std::mem::size_of::<T>();
}
8 changes: 8 additions & 0 deletions tests/ui/layout/too-big-no-dce.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
error[E0080]: values of the type `[u32; NUMBER]` are too big for the target architecture
--> $SRC_DIR/core/src/mem/mod.rs:LL:COL
|
= note: evaluation of `<[u32; NUMBER] as std::mem::SizedTypeProperties>::SIZE` failed here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0080`.
Loading