Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't re-assume in transmutes that don't change niches #137513

Merged
merged 1 commit into from
Mar 9, 2025
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 compiler/rustc_codegen_ssa/src/mir/rvalue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
) -> Bx::Value {
assert_eq!(from_scalar.size(self.cx), to_scalar.size(self.cx));

// While optimizations will remove no-op transmutes, they might still be
// there in debug or things that aren't no-op in MIR because they change
// the Rust type but not the underlying layout/niche.
if from_scalar == to_scalar && from_backend_ty == to_backend_ty {
return imm;
}

use abi::Primitive::*;
imm = bx.from_immediate(imm);

Expand Down
25 changes: 25 additions & 0 deletions tests/codegen/intrinsics/transmute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use std::intrinsics::mir::*;
use std::intrinsics::{transmute, transmute_unchecked};
use std::mem::MaybeUninit;
use std::num::NonZero;

// FIXME(LLVM18REMOVED): `trunc nuw` doesn't exist in LLVM 18, so once we no
// longer support it the optional flag checks can be changed to required.
Expand Down Expand Up @@ -470,3 +471,27 @@ pub unsafe fn check_from_overalign(x: HighAlignScalar) -> u64 {
// CHECK: ret i64 %[[VAL]]
transmute(x)
}

#[repr(transparent)]
struct Level1(std::num::NonZero<u32>);
#[repr(transparent)]
struct Level2(Level1);
#[repr(transparent)]
struct Level3(Level2);

// CHECK-LABEL: @repeatedly_transparent_transmute
// CHECK-SAME: (i32{{.+}}%[[ARG:[^)]+]])
#[no_mangle]
#[custom_mir(dialect = "runtime", phase = "optimized")]
pub unsafe fn repeatedly_transparent_transmute(x: NonZero<u32>) -> Level3 {
// CHECK: start
// CHECK-NEXT: ret i32 %[[ARG]]
mir! {
{
let A = CastTransmute::<NonZero<u32>, Level1>(x);
let B = CastTransmute::<Level1, Level2>(A);
RET = CastTransmute::<Level2, Level3>(B);
Return()
}
}
}
Loading