Skip to content

assert_eq! of trivially-equal enums with 2 non-empty variants is not optimized out #139733

Open
@ZhonghaoPan-nju

Description

@ZhonghaoPan-nju

https://godbolt.org/z/Wrq4EdvrP

This program should be optimized to an empty main, but it isn't:

#[derive(PartialEq)]
enum Foo {
    Bar(u8, u8),
    #[allow(dead_code)]
    Baz(u8),
}

impl std::fmt::Debug for Foo {
    #[inline]
    fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Ok(())
    }
}

pub fn main() {
    let a = Foo::Bar(1, 2);
    let b = Foo::Bar(1, 2);
    assert_eq!(a, b);
}

Note that if the assert is changed to just a panic that doesn't try to format a and b, the comparison does get optimized out. And also, if the Baz is a unit variant we will get the expected optimization but only with -Cdebuginfo=0.

rustc 1.85.0-nightly (d117b7f21 2024-12-31)
binary: rustc
commit-hash: d117b7f211835282b3b177dc64245fff0327c04c
commit-date: 2024-12-31
host: x86_64-unknown-linux-gnu
release: 1.85.0-nightly
LLVM version: 19.1.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.T-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