Skip to content

Optimization introduces a pointer dereference on unreachable path #159591

Description

@ChoKyuWon

I tried this code:

use std::hint::black_box;

#[inline(never)]
unsafe fn foo(q: u64, p: *const u64) -> u64 {
    'a: {
        match q {
            1 => match *p { 1 => break 'a 100, _ => {} },
            2 => match *p { 2 => break 'a 200, _ => {} },
            _ => {}
        }
        999
    }
}

fn main() {
    let q: u64 = black_box(3);
    let p: *const u64 = black_box(std::ptr::null());
    let r = unsafe { foo(q, p) };
    println!("{}", black_box(r));
}

I expected to see this happen: even with the null pointer p, its dereference is never reachable, so the program will print 999 for all optimization levels

Instead, this happened:

$ rustc ./prog.rs && ./prog
999
$ rustc ./prog.rs -Zmir-opt-level=1 -Copt-level=3 && ./prog
999
$ rustc ./prog.rs -Zmir-opt-level=2 -Copt-level=3 && ./prog
[1]    2636920 segmentation fault (core dumped)  ./prog
$ rustc ./prog.rs -Copt-level=3 && ./prog
[1]    2618500 segmentation fault (core dumped)  ./prog

Meta

rustc --version --verbose:

rustc 1.99.0-nightly (3659db0d3 2026-07-05)
binary: rustc
commit-hash: 3659db0d3e2cd634c766fcda79ed118eca31a9fd
commit-date: 2026-07-05
host: x86_64-unknown-linux-gnu
release: 1.99.0-nightly
LLVM version: 22.1.8
Backtrace

<backtrace>

Metadata

Metadata

Assignees

Labels

A-mir-optArea: MIR optimizationsC-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

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions