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

            Bug ID: 42206
           Summary: Missed optimization for (unsigned) log2((unsigned) X)
           Product: libraries
           Version: trunk
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Scalar Optimizations
          Assignee: [email protected]
          Reporter: [email protected]
                CC: [email protected]

It seems we could do following transformations:

(T) log2((T) x) -> x == 0 ? 0 : sizeof(T) * CHAR_BIT - 1 -__builtin_clz(x);


(T) floor(log2((T) x)) -> x == 0 ? 0 : sizeof(T) * CHAR_BIT - 1
-__builtin_clz(x);


where T is unsigned integer type.

Test program:
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <stdio.h>

#define T unsigned
#define TT unsigned
TT f(T x) {
    return log2(x);
}

TT f2(T x) {
    return x == 0 ? 0 : sizeof(T) * CHAR_BIT - 1 - __builtin_clz(x);
}

int main(int argc, char **argv) {
    for (T i = 0; i < INT_MAX; ++i) {
         if (f(i) != f2(i)) {
            abort();
         }
    } 

    return 0;
}

I see no crash so I think this is valid transformation. Am I wrong?

-- 
You are receiving this mail because:
You are on the CC list for the bug.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to