https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95674
Bug ID: 95674 Summary: Unnecessary move when doing division-by-multiplication Product: gcc Version: 10.1.0 Status: UNCONFIRMED Keywords: missed-optimization Severity: normal Priority: P3 Component: middle-end Assignee: unassigned at gcc dot gnu.org Reporter: josephcsible at gmail dot com Target Milestone: --- When GCC does division-by-multiplication, it seems to forget that multiplication is commutative. It moves the numerator into %rax, but if it moved the magic number there instead, then it wouldn't have to move the numerator at all. Input: unsigned long f(unsigned long x) { return x / 7; } Actual assembly: f: movabsq $2635249153387078803, %rdx movq %rdi, %rax mulq %rdx subq %rdx, %rdi shrq %rdi leaq (%rdx,%rdi), %rax shrq $2, %rax ret Desired assembly: f: movabsq $2635249153387078803, %rax mulq %rdi subq %rdx, %rdi shrq %rdi leaq (%rdx,%rdi), %rax shrq $2, %rax ret https://godbolt.org/z/RE45qg