clzsi2.c revision 1c5f89b1dd741135a4007ab577723d422f421eec
1/* ===-- clzsi2.c - Implement __clzsi2 -------------------------------------===
2 *
3 *               The LLVM Compiler Infrastructure
4 *
5 * This file is dual licensed under the MIT and the University of Illinois Open
6 * Source Licenses. See LICENSE.TXT for details.
7 *
8 * ===----------------------------------------------------------------------===
9 *
10 * This file implements __clzsi2 for the compiler_rt library.
11 *
12 * ===----------------------------------------------------------------------===
13 */
14#include "abi.h"
15
16#include "int_lib.h"
17
18/* Returns: the number of leading 0-bits */
19
20/* Precondition: a != 0 */
21
22COMPILER_RT_ABI si_int
23__clzsi2(si_int a)
24{
25    su_int x = (su_int)a;
26    si_int t = ((x & 0xFFFF0000) == 0) << 4;  /* if (x is small) t = 16 else 0 */
27    x >>= 16 - t;      /* x = [0 - 0xFFFF] */
28    su_int r = t;       /* r = [0, 16] */
29    /* return r + clz(x) */
30    t = ((x & 0xFF00) == 0) << 3;
31    x >>= 8 - t;       /* x = [0 - 0xFF] */
32    r += t;            /* r = [0, 8, 16, 24] */
33    /* return r + clz(x) */
34    t = ((x & 0xF0) == 0) << 2;
35    x >>= 4 - t;       /* x = [0 - 0xF] */
36    r += t;            /* r = [0, 4, 8, 12, 16, 20, 24, 28] */
37    /* return r + clz(x) */
38    t = ((x & 0xC) == 0) << 1;
39    x >>= 2 - t;       /* x = [0 - 3] */
40    r += t;            /* r = [0 - 30] and is even */
41    /* return r + clz(x) */
42/*     switch (x)
43 *     {
44 *     case 0:
45 *         return r + 2;
46 *     case 1:
47 *         return r + 1;
48 *     case 2:
49 *     case 3:
50 *         return r;
51 *     }
52 */
53    return r + ((2 - x) & -((x & 2) == 0));
54}
55