blob: 25b8ed2c4c240f5c0e64cad0dd3d821dd2dfaeaa [file] [log] [blame]
Edward O'Callaghan2bf62722009-08-05 04:02:56 +00001/* ===-- clzsi2.c - Implement __clzsi2 -------------------------------------===
2 *
Anton Korobeynikov1c5f89b2011-04-19 17:52:09 +00003 * The LLVM Compiler Infrastructure
Edward O'Callaghan2bf62722009-08-05 04:02:56 +00004 *
Howard Hinnant9ad441f2010-11-16 22:13:33 +00005 * This file is dual licensed under the MIT and the University of Illinois Open
6 * Source Licenses. See LICENSE.TXT for details.
Edward O'Callaghan2bf62722009-08-05 04:02:56 +00007 *
8 * ===----------------------------------------------------------------------===
9 *
10 * This file implements __clzsi2 for the compiler_rt library.
11 *
12 * ===----------------------------------------------------------------------===
13 */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000014
15#include "int_lib.h"
16
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000017/* Returns: the number of leading 0-bits */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000018
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000019/* Precondition: a != 0 */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000020
Anton Korobeynikov1c5f89b2011-04-19 17:52:09 +000021COMPILER_RT_ABI si_int
Daniel Dunbarb3a69012009-06-26 16:47:03 +000022__clzsi2(si_int a)
23{
24 su_int x = (su_int)a;
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000025 si_int t = ((x & 0xFFFF0000) == 0) << 4; /* if (x is small) t = 16 else 0 */
26 x >>= 16 - t; /* x = [0 - 0xFFFF] */
27 su_int r = t; /* r = [0, 16] */
28 /* return r + clz(x) */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000029 t = ((x & 0xFF00) == 0) << 3;
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000030 x >>= 8 - t; /* x = [0 - 0xFF] */
31 r += t; /* r = [0, 8, 16, 24] */
32 /* return r + clz(x) */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000033 t = ((x & 0xF0) == 0) << 2;
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000034 x >>= 4 - t; /* x = [0 - 0xF] */
35 r += t; /* r = [0, 4, 8, 12, 16, 20, 24, 28] */
36 /* return r + clz(x) */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000037 t = ((x & 0xC) == 0) << 1;
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000038 x >>= 2 - t; /* x = [0 - 3] */
39 r += t; /* r = [0 - 30] and is even */
40 /* return r + clz(x) */
41/* switch (x)
42 * {
43 * case 0:
44 * return r + 2;
45 * case 1:
46 * return r + 1;
47 * case 2:
48 * case 3:
49 * return r;
50 * }
51 */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000052 return r + ((2 - x) & -((x & 2) == 0));
53}