1214152Sed/* ===-- clzsi2.c - Implement __clzsi2 -------------------------------------===
2214152Sed *
3222656Sed *               The LLVM Compiler Infrastructure
4214152Sed *
5222656Sed * This file is dual licensed under the MIT and the University of Illinois Open
6222656Sed * Source Licenses. See LICENSE.TXT for details.
7214152Sed *
8214152Sed * ===----------------------------------------------------------------------===
9214152Sed *
10214152Sed * This file implements __clzsi2 for the compiler_rt library.
11214152Sed *
12214152Sed * ===----------------------------------------------------------------------===
13214152Sed */
14214152Sed
15214152Sed#include "int_lib.h"
16214152Sed
17214152Sed/* Returns: the number of leading 0-bits */
18214152Sed
19214152Sed/* Precondition: a != 0 */
20214152Sed
21222656SedCOMPILER_RT_ABI si_int
22214152Sed__clzsi2(si_int a)
23214152Sed{
24214152Sed    su_int x = (su_int)a;
25214152Sed    si_int t = ((x & 0xFFFF0000) == 0) << 4;  /* if (x is small) t = 16 else 0 */
26214152Sed    x >>= 16 - t;      /* x = [0 - 0xFFFF] */
27214152Sed    su_int r = t;       /* r = [0, 16] */
28214152Sed    /* return r + clz(x) */
29214152Sed    t = ((x & 0xFF00) == 0) << 3;
30214152Sed    x >>= 8 - t;       /* x = [0 - 0xFF] */
31214152Sed    r += t;            /* r = [0, 8, 16, 24] */
32214152Sed    /* return r + clz(x) */
33214152Sed    t = ((x & 0xF0) == 0) << 2;
34214152Sed    x >>= 4 - t;       /* x = [0 - 0xF] */
35214152Sed    r += t;            /* r = [0, 4, 8, 12, 16, 20, 24, 28] */
36214152Sed    /* return r + clz(x) */
37214152Sed    t = ((x & 0xC) == 0) << 1;
38214152Sed    x >>= 2 - t;       /* x = [0 - 3] */
39214152Sed    r += t;            /* r = [0 - 30] and is even */
40214152Sed    /* return r + clz(x) */
41214152Sed/*     switch (x)
42214152Sed *     {
43214152Sed *     case 0:
44214152Sed *         return r + 2;
45214152Sed *     case 1:
46214152Sed *         return r + 1;
47214152Sed *     case 2:
48214152Sed *     case 3:
49214152Sed *         return r;
50214152Sed *     }
51214152Sed */
52214152Sed    return r + ((2 - x) & -((x & 2) == 0));
53214152Sed}
54