[LLVMbugs] [Bug 20992] New: unexpected behavior using result of __lzcnt64() on x86_64

bugzilla-daemon at llvm.org bugzilla-daemon at llvm.org
Thu Sep 18 01:45:59 PDT 2014


http://llvm.org/bugs/show_bug.cgi?id=20992

            Bug ID: 20992
           Summary: unexpected behavior using result of __lzcnt64() on
                    x86_64
           Product: clang
           Version: 3.4
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: normal
          Priority: P
         Component: -New Bugs
          Assignee: unassignedclangbugs at nondot.org
          Reporter: klberger at gmail.com
                CC: llvmbugs at cs.uiuc.edu
    Classification: Unclassified

Created attachment 13050
  --> http://llvm.org/bugs/attachment.cgi?id=13050&action=edit
test case compile with: clang -Wall -pedantic -O2 -mlzcnt -o lzcnt lzcntm.c

Given the following function definition

--
#include <stdint.h>
#include <x86intrin.h>

/*
 *    return position [0..63] of highest bit set or -1 if val equals zero
 */

int highest_bit_set(uint64_t val)
{
    return 63 - __lzcnt64(val);
}
--

If called with val==0, the function returns 127 instead of -1.
Compiled on an x86_64 platform with

clang -Wall -pedantic -O2 -mlzcnt -S lzcnt.c

the compiler generates

-- clang 3.4 --
highest_bit_set:                        # @highest_bit_set
    .cfi_startproc
# BB#0:
  lzcntq    %rdi, %rax
  xorl    $63, %eax
                                        # kill: EAX<def> EAX<kill> RAX<kill>
  ret
--

whereas gcc generates the expected

-- gcc 4.8.3 --
highest_bit_set:
.LFB551:
  .cfi_startproc
  lzcntq    %rdi, %rdi
  movl    $63, %eax
  subl    %edi, %eax
  ret
--

Disabling optimization yields the expected result. It seems the compiler
assumes __lzcnt64() will return only values [0..63] and replaces the 63-x by
xor $63,x.
The instruction lzcnt is specified to return the operand width in bits (64) if
the source operand is 0.
I am aware that lzcnt is a "problematic" instruction because it is executed as
bsr on processors with no native lzcnt support and the result of bsr is
undefined for a zero operand. For a cpu with native lzcnt support (-mlzcnt or
implicit via -march) i'd expected the compiler to support the full range of
values returned by lzcnt.

Related intrinsics/built-ins that (may) show the same problem: __tzcnt64(),
__builtin_clzl() ...

I first used __builtin_clzl() which translates into the same code, but which is
explicitly declared to return an undefined result (gcc docs) if called with a
zero argument.

-- 
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/20140918/8b0064ef/attachment.html>


More information about the llvm-bugs mailing list