Skip to content

Missed optimization with core::cmp::{min,max} {<,>} n and the range of one the values is known #92967

Closed
@paolobarbolini

Description

@paolobarbolini

I tried this code:

#![feature(core_intrinsics)]

pub unsafe fn foo1(a: usize, b: usize) {
    std::intrinsics::assume(a < 6);

    assert!(a.min(b) < 6);
}

I expected to see this happen: the assert is optimized away. By proving a < 6, even without knowing b, we can assume a.min(b) < 6.

Instead, this happened: it doesn't optimize, but it does in the following conditions:

#![feature(core_intrinsics)]

pub unsafe fn foo2(a: usize, b: usize) {
    std::intrinsics::assume(a < 6);

    assert!(a < 6 || b < 6);

    assert!((if a < b { a } else { b }) < 6);
    assert!((if a <= b { a } else { b }) < 6);
}

// or...

pub unsafe fn foo3(a: usize, b: usize) {
    std::intrinsics::assume(a == 3);

    assert!(a.min(b) < 6);
}


// or...

pub unsafe fn foo4(a: usize, b: usize) {
    std::intrinsics::assume(a < 6);
    std::intrinsics::assume(b < 6);

    assert!(a.min(b) < 6);
}

Why this matters

Prevents the ptr_rotate implementation from optimizing here

} else if cmp::min(left, right) <= mem::size_of::<BufType>() / mem::size_of::<T>() {

which would reduce the amount of assembly generated by #89714

Meta

rustc --version --verbose:

rustc 1.60.0-nightly (ec4bcaac4 2022-01-15)
binary: rustc
commit-hash: ec4bcaac450279b029f3480b8b8f1b82ab36a5eb
commit-date: 2022-01-15
host: x86_64-unknown-linux-gnu
release: 1.60.0-nightly
LLVM version: 13.0.0

Metadata

Metadata

Assignees

Labels

A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-bugCategory: This is a bug.I-slowIssue: Problems and improvements with respect to performance of generated code.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions