Skip to content

CopyProp miscompilation when src is moved more than once #137936

Open
@tmiasko

Description

@tmiasko
#![feature(custom_mir, core_intrinsics, freeze)]
#![allow(internal_features, unused_assignments)]
extern crate core;
use core::intrinsics::mir::*;
use core::mem::MaybeUninit;
use core::marker::Freeze;

#[custom_mir(dialect = "analysis", phase = "post-cleanup")]
fn f<T: Copy + Freeze>(a: MaybeUninit<T>) {
    mir! {
        {
            let b = Move(a);
            let c = Move(a);
            Call(RET = g(Move(b), Move(c)), ReturnTo(ret), UnwindContinue())
        }
        ret = {
            Return()
        }
    }
}

fn g<T: Copy + Freeze>(mut a: T, mut b: T) {
    assert_ne!(&mut a as *mut _ as usize, &mut b as *mut _ as usize);
}

fn main() {
    f(MaybeUninit::<[u8;  64]>::uninit());
}

The CopyProp introduces following changes:

--- a.f.005-021.CopyProp.before.mir	2025-03-03 13:42:20.628850669 +0100
+++ a.f.005-021.CopyProp.after.mir	2025-03-03 13:42:20.628850669 +0100
@@ -1,17 +1,15 @@
-// MIR for `f` before CopyProp
+// MIR for `f` after CopyProp
 
 fn f(_1: MaybeUninit<T>) -> () {
     let mut _0: ();
     let mut _2: std::mem::MaybeUninit<T>;
     let mut _3: std::mem::MaybeUninit<T>;
 
     bb0: {
-        _2 = move _1;
-        _3 = move _1;
-        _0 = g::<MaybeUninit<T>>(move _2, move _3) -> [return: bb1, unwind continue];
+        _0 = g::<MaybeUninit<T>>(move _1, move _1) -> [return: bb1, unwind continue];
     }
 
     bb1: {
         return;
     }
 }
$ rustc a.rs -Zmir-opt-level=0 && ./a
$ rustc a.rs -Zmir-opt-level=1 && ./a

thread 'main' panicked at a.rs:23:5:
assertion `left != right` failed
  left: 140729201385720
 right: 140729201385720
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-mir-optArea: MIR optimizationsC-bugCategory: This is a bug.I-miscompileIssue: Correct Rust code lowers to incorrect machine codeI-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.requires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions