https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92592
Bug ID: 92592 Summary: Redundant comparison after subtraction on x86 Product: gcc Version: 10.0 Status: UNCONFIRMED Keywords: missed-optimization Severity: normal Priority: P3 Component: target Assignee: unassigned at gcc dot gnu.org Reporter: antoshkka at gmail dot com Target Milestone: --- Consider the example: int sample(int a, int b) { unsigned diff = (unsigned)b - (unsigned)a; unsigned sign_bit = b < a; return diff + sign_bit; } With -O2 and -O3 GCC produces the assembly: sample(int, int): mov eax, esi ; <=== not required xor edx, edx sub eax, edi cmp esi, edi ; <=== not required setl dl add eax, edx ret However, `sub` changes the status flags and there's no need to call `cmp`: sample(int, int): xor eax, eax sub esi, edi setl al add eax, esi ret The above sample is a minimized version of std::midpoint. Godbolt playground: https://godbolt.org/z/j6FGq4