Skip to content

Hardening checks in a std::copy-like loop aren't hoisted out of the loop #78917

Open
@davidben

Description

@davidben

For some context, see #78876.

Playing around with a bounds-checked iterator, and std::copy, I found another missed optimization. std::copy is interesting because it iterates over both a source and destination range in parallel. It uses the source range to bound the loop, which means we have a precondition on the destination range.

Ideally this would be checked once, a la dst.size() >= src.size() and then the loop itself be check-free. But if we add safety checks to the individual iterator accesses, there will initially be checks inside the loop.

I tried several variations, but I could not get Clang to determine that the inner check is redundant with some outer one.
https://godbolt.org/z/aen9vYjzz

This is less bad than it sounds because std::copy is often specialized to memmove. (Though there we have a different problem, #78771.) But sometimes it is just the loop, and ideally patterns like this could be optimized, so that code using LLVM can add more safety checks with less worry about the impact on tight loops.

(CC @danakj)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions