https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120904
Bug ID: 120904 Summary: Redundant pointer comparisons after arithmetic not deleted Product: gcc Version: 16.0 Status: UNCONFIRMED Keywords: missed-optimization Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: sjames at gcc dot gnu.org Target Milestone: --- Created attachment 61773 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=61773&action=edit test.cxx This is a mirror bug of https://github.com/llvm/llvm-project/issues/78784. Quoting the reporter there: """ I noticed this as I was exploring the compiler output for some of our (Chromium's) checked iterators. To be honest, I'm not sure this check makes sense, since we should just assume the container is self-consistent. But, nonetheless, I think Clang could have deleted this check, so I'm filing this as a missed optimization. Reproducer: godbolt.org/z/EzoWqGEEK This code ends up performing a few variations on checking that data_ <= data_ + size_, where size_ is a size_t. Of course, the real reason this is always valid is that [data_, data_ + size_) describes a span, but the compiler doesn't a priori know that. However, I believe it can infer this because: size_ is unsigned, so we're not adding a negative number to data_ Pointer arithmetic is required to stay in bounds, and is not defined to cast to ptrdiff_t first: eel.is/c++draft/expr.add#4.2 Therefore, the addition cannot have overflowed and data_ <= data_ + size_ is always true in all defined cases """ Clang trunk now produces just `ret`, but we still do a comparison. I'm not sure how much it matters really.