Skip to content

a case where bounds checks should be eliminated #58602

Closed
@oconnor663

Description

@oconnor663

https://godbolt.org/z/y-GVc2

const INPUT: usize = 10;
const OUTPUT: usize = 3;

pub fn get_output1(input: &[u8; INPUT], offset: usize) -> Option<&[u8]> {
    if offset <= INPUT - OUTPUT {
        // This version optimizes out the extra bounds checks for the slice.
        Some(&input[offset..offset + OUTPUT])
    } else {
        None
    }
}

pub fn get_output2(input: &[u8; INPUT], offset: usize) -> Option<&[u8]> {
    if offset <= INPUT - OUTPUT {
        // This version fails to optimize bounds checks.
        Some(&input[offset..][..OUTPUT])
    } else {
        None
    }
}

This is a simplified version of a pessimization that came up when I was trying to optimize the array_ref! macro: droundy/arrayref#16

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.I-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.WG-llvmWorking group: LLVM backend code generation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions