Skip to content

Incorrect Release Code Generation (Works in Debug) #91027

Closed
@ghost

Description

I tried this code:

// Note: original reduced to a minimal reproducing sample
fn main() {
    let foos = 1;
    let mut iter = FooIter {foos: &foos, current: Some(Foo::A)};
    match iter.next() {
        None => println!("INCORRECT"), // Occurs in release mode
        Some(_) => println!("CORRECT") // Occurs in debug mode
    }
}

#[derive(Copy, Clone)]
pub enum Foo {
    A,
    B,
    C
}

pub struct FooIter<'a> {
    foos: &'a u32,
    current: Option<Foo>
}

impl<'a> Iterator for FooIter<'a> {
    type Item = Foo;
    
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let current = self.current?;
            self.current = None;
            
            if *self.foos == 1 {
                return Some(current)
            }
        }
    }
}

I expected to see this happen: In both debug and release builds, I expect to see "CORRECT" be printed.

Instead, this happened: The debug build correctly prints "CORRECT", but the release build incorrectly prints "INCORRECT". Minor perturbations cause the release build to print "CORRECT". Presumably the code is triggering an excessively-aggressive optimization.

Meta

  • I reproduced this on version 1.56.0, target triple x86_64-pc-windows-msvc. As this was on a different system from the one on which I am filing the bug report, I cannot show rustc --version output.
  • As a sanity check, I also reproduced this on the rust playground using 1.56.1 stable: [(https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=af0b28cf2eafd458e51a554e8e007332)]
  • On rust playground using beta and nightly, the bug did NOT reproduce. As this does not necessarily mean it was fixed (as opposed to merely hidden), I opted to file the report anyway.

Thank you for your time and attention!

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.I-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.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions