Skip to content

With GVN, Miri flags loads of a const packed struct field as insufficiently aligned #163782

Description

@saethlin

This safe program reports UB when run with Miri (note that you need to use RUSTFLAGS=-Zmir-enable-passes=+GVN cargo +nightly miri run because Miri explicitly turns off GVN for a different reason)

#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct Packed {
    pub a: u8,
    pub b: (u32, u32),
}

#[derive(Clone, Copy)]
pub struct Outer {
    pub x: u64,
    pub p: Packed,
}

const C: Outer = Outer {
    x: 7,
    p: Packed { a: 1, b: (2, 3) },
};

#[inline(never)]
fn get() -> (u32, u32) {
    C.p.b
}

fn main() {
    println!("{:?}", get());
}
error: Undefined Behavior: accessing memory based on pointer with alignment 1, but alignment 4 is required
  --> src/main.rs:18:5
   |
18 |     C.p.b
   |     ^^^^^ Undefined Behavior occurred here
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
   = note: stack backtrace:
           0: get
               at src/main.rs:18:5: 18:10
           1: main
               at src/main.rs:22:22: 22:27

Whatever Miri is seeing here, I can't see it in our MIR dumps. I wonder if our pretty-printing is obscuring the problem?

fn get() -> (u32, u32) {
    let mut _0: (u32, u32);
    let mut _1: Outer;

    bb0: {
        StorageLive(_1);
        _1 = const C;
        _0 = const (2_u32, 3_u32);
        StorageDead(_1);
        return;
    }
}

alloc1 (size: 24, align: 8) {
    0x00 │ 07 00 00 00 00 00 00 00 01 02 00 00 00 03 00 00 │ ................
    0x10 │ 00 __ __ __ __ __ __ __                         │ .░░░░░░░
}

This was found by an LLM

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-mir-optArea: MIR optimizationsA-mir-opt-GVNArea: MIR opt Global Value Numbering (GVN)C-bugCategory: This is a bug.I-miscompileIssue: Correct Rust code lowers to incorrect machine codeP-highHigh priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions