rust/tests/mir-opt/instsimplify/casts.rs
Nilstrieb b6657a8ad4 Never consider raw pointer casts to be trival
HIR typeck tries to figure out which casts are trivial by doing them as
coercions and seeing whether this works. Since HIR typeck is oblivious
of lifetimes, this doesn't work for pointer casts that only change the
lifetime of the pointee, which are, as borrowck will tell you, not
trivial.

This change makes it so that raw pointer casts are never considered
trivial.

This also incidentally fixes the "trivial cast" lint false positive on
the same code. Unfortunately, "trivial cast" lints are now never emitted
on raw pointer casts, even if they truly are trivial. This could be
fixed by also doing the lint in borrowck for raw pointers specifically.
2023-10-25 23:15:18 +02:00

26 lines
739 B
Rust

// unit-test: InstSimplify
// compile-flags: -Zinline-mir
#![crate_type = "lib"]
#[inline(always)]
fn generic_cast<T, U>(x: *const T) -> *const U {
x as *const U
}
// EMIT_MIR casts.redundant.InstSimplify.diff
pub fn redundant<'a, 'b: 'a>(x: *const &'a u8) -> *const &'a u8 {
// CHECK-LABEL: fn redundant(
// CHECK: inlined generic_cast
// CHECK-NOT: as
generic_cast::<&'a u8, &'b u8>(x) as *const &'a u8
}
// EMIT_MIR casts.roundtrip.InstSimplify.diff
pub fn roundtrip(x: *const u8) -> *const u8 {
// CHECK-LABEL: fn roundtrip(
// CHECK: _4 = _1;
// CHECK: _3 = move _4 as *mut u8 (PtrToPtr);
// CHECK: _2 = move _3 as *const u8 (PointerCoercion(MutToConstPointer));
x as *mut u8 as *const u8
}