[llvm-bugs] [Bug 36760] New: Arithmetic shift optimization for signed numbers

via llvm-bugs llvm-bugs at lists.llvm.org
Thu Mar 15 13:52:26 PDT 2018


https://bugs.llvm.org/show_bug.cgi?id=36760

            Bug ID: 36760
           Summary: Arithmetic shift optimization for signed numbers
           Product: libraries
           Version: 6.0
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Backend: X86
          Assignee: unassignedbugs at nondot.org
          Reporter: nruslan_devel at yahoo.com
                CC: llvm-bugs at lists.llvm.org

This was reported a while ago, but seems clang/llvm still does not optimize
this case well. (For the examples below -O2 option is used)

1. Consider the following example:

long long func(long long a)
{
    if (a < 0)
        return 0;
    return (a >> 63 ) ^ a;
}

Basically, since a is already checked to be non-negative, (a >> 63) must be 0.
Therefore, the shift operation should be optimized out.

clang/llvm 6.0 generates the following:
        movq    %rdi, %rcx
        sarq    $63, %rcx
        xorq    %rdi, %rcx
        xorl    %eax, %eax
        testq   %rdi, %rdi
        cmovnsq %rcx, %rax
        retq

whereas gcc can optimize it well:
        testq   %rdi, %rdi
        movl    $0, %eax
        cmovns  %rdi, %rax
        ret

2. Another example is when we reverse the condition:

long long func(long long a)
{
    if (a >= 0)
        return 0;
    return (a >> 63 ) ^ a;
}

In this case, again, the shift is unnecessary since (a >> 63) are all 1's.
Therefore, return statement is basically ~a.

clang/llvm:
        movq    %rdi, %rcx
        sarq    $63, %rcx
        xorq    %rdi, %rcx
        xorl    %eax, %eax
        testq   %rdi, %rdi
        cmovsq  %rcx, %rax
        retq

gcc:
        movq    %rdi, %rax
        testq   %rdi, %rdi
        movl    $0, %edx
        notq    %rax
        cmovns  %rdx, %rax
        ret

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20180315/c5a9997e/attachment.html>


More information about the llvm-bugs mailing list