rust-lang / rust-lang/rust

Poor codegen for enumerations where variants have power-of-two values.

Open
#122,893 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-codegen A-LLVM C-optimization T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Background

Consider the code in the link below:
https://rust.godbolt.org/z/z6WrPEM68

It defines an enumeration where all variants have a value that are equal to a power-of-two.

Creation of an enumeration value

Two of the functions create an enummeration value out of an unsigned integer. The first function wraps the result in an Option with None being used for illegal inputs, the second function uses undefined behaviour instead. In both cases, legal input values and enumeration values are identical.

Expectation

Since legal input values and enumeration values are identical, the functions compile to little more than mov instructions and possibly checks.

Reality

Giant jump tables.

Matching on an enumeration value

Since the enumeration values have only one bit set, it is possible to make various tests much cheaper. In this instance, there are several functions testing wether an enumeration value is a member of a set.

Expectation

The functions compile to a bitwise AND or similar, using branchless instructions in all cases.

Reality

The functions are compiled into several instructions including branches.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Rust Compiler Explorer reproducer at https://rust.godbolt.org/z/z6WrPEM68 and inspect the generated assembly for the enumeration-construction and set-membership functions. Compare the output with the expected checks and bitwise operations described in the issue. Done means the relevant cases no longer generate giant jump tables or unnecessary branches while preserving correct behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.