[llvm-bugs] [Bug 42206] New: Missed optimization for (unsigned) log2((unsigned) X)

via llvm-bugs llvm-bugs at lists.llvm.org
Sun Jun 9 05:33:20 PDT 2019


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: unassignedbugs at nondot.org
          Reporter: david.bolvansky at gmail.com
                CC: llvm-bugs at lists.llvm.org

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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20190609/d4d5b936/attachment.html>


More information about the llvm-bugs mailing list