rust-lang / rust-lang/rust

Range of index variables forgotten in an `else if`

Open
#144,522 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-LLVM C-optimization I-slow
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

LLVM issue: https://github.com/llvm/llvm-project/issues/151078

pub fn choose(v: &[i32], a: usize, b: usize, c: usize, cond1: i32, cond2: i32) -> usize {
    if a >= v.len() || b >= v.len() || c >= v.len() {
        return 0;
    }

    let va = v[a];
    let vb = v[b]; // v[a]

    let res = if va < cond1 {
        a
    } else if vb < cond2 {
        b
    } else {
        c
    };
    assert!(res < v.len());
    res
}

Godbolt link

I expected the assert to be optimized out, because the only possible values are a/b/c which have been checked at the start of the function. However, in this case the bounds check seems to be lost, and the assert stays.

The optimization failure happens when both conditions are met:

  • two different slice indices must be used (e.g. v[a] and v[b]). There's no problem when both conditions use the same v[a].
  • there must be an else if. There's no problem if there's only if/else even if the conditions uses two different values if va < cond1 || vb < cond2

Does not optimize:

    let res = if va < cond1 {
        a
    } else if vb < cond2 {
        a
    } else {
        b
    };

Does optimize:

    let res = if va < cond1 ||  vb < cond2 {
        a
    } else {
        b
    };

In C va < cond1 || vb < cond2 doens't optimize, but va < cond1 | vb < cond2 does, so it may be related to extra 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 provided Rust reproducer and Godbolt link, comparing the else if cases with the equivalent if/else form and checking the generated output. The fix is complete when the final bounds-check assertion is optimized out for the reported cases without regressing the other examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.