Skip to content

Allow transmute casts in pre-runtime-MIR #142124

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

Merged
merged 1 commit into from
Jun 10, 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
2 changes: 0 additions & 2 deletions compiler/rustc_middle/src/mir/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1531,8 +1531,6 @@ pub enum CastKind {
///
/// MIR is well-formed if the input and output types have different sizes,
/// but running a transmute between differently-sized types is UB.
///
/// Allowed only in [`MirPhase::Runtime`]; Earlier it's a [`TerminatorKind::Call`].
Transmute,
}

Expand Down
48 changes: 19 additions & 29 deletions compiler/rustc_mir_transform/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1308,37 +1308,27 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
}
}
CastKind::Transmute => {
if let MirPhase::Runtime(..) = self.body.phase {
// Unlike `mem::transmute`, a MIR `Transmute` is well-formed
// for any two `Sized` types, just potentially UB to run.

if !self
.tcx
.normalize_erasing_regions(self.typing_env, op_ty)
.is_sized(self.tcx, self.typing_env)
{
self.fail(
location,
format!("Cannot transmute from non-`Sized` type {op_ty}"),
);
}
if !self
.tcx
.normalize_erasing_regions(self.typing_env, *target_type)
.is_sized(self.tcx, self.typing_env)
{
self.fail(
location,
format!("Cannot transmute to non-`Sized` type {target_type:?}"),
);
}
} else {
// Unlike `mem::transmute`, a MIR `Transmute` is well-formed
// for any two `Sized` types, just potentially UB to run.

if !self
.tcx
.normalize_erasing_regions(self.typing_env, op_ty)
.is_sized(self.tcx, self.typing_env)
{
self.fail(
location,
format!(
"Transmute is not supported in non-runtime phase {:?}.",
self.body.phase
),
format!("Cannot transmute from non-`Sized` type {op_ty}"),
);
}
if !self
.tcx
.normalize_erasing_regions(self.typing_env, *target_type)
.is_sized(self.tcx, self.typing_env)
{
self.fail(
location,
format!("Cannot transmute to non-`Sized` type {target_type:?}"),
);
}
}
Expand Down
1 change: 1 addition & 0 deletions tests/ui/type/pattern_types/matching.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![feature(pattern_types, pattern_type_macro, structural_match)]

//@ check-pass
//@ compile-flags: -Zvalidate-mir

use std::marker::StructuralPartialEq;
use std::pat::pattern_type;
Expand Down
Loading