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