summaryrefslogtreecommitdiff
path: root/arch/riscv/lib/ctz.c
blob: 6c875e39f0eb6b864bb8578ea886e800e8b1ded1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * libgcc replacement - count trailing bits
 */

#include <linux/types.h>

/**
 * __ctzti2() - count number of trailing zero bits
 *
 * @x:		number to check
 * Return:	number of trailing zero bits
 */
int __ctzti2(long long x)
{
	int ret = 0;

	if (!x)
		return 64;

	if (!(x & 0xFFFFFFFFLL)) {
		ret += 32;
		x >>= 32;
	}
	if (!(x & 0xFFFFLL)) {
		ret += 16;
		x >>= 16;
	}
	if (!(x & 0xFFLL)) {
		ret += 8;
		x >>= 8;
	}
	if (!(x & 0xFLL)) {
		ret += 4;
		x >>= 4;
	}
	if (!(x & 0x3LL)) {
		ret += 2;
		x >>= 2;
	}
	if (!(x & 0x1ll))
		ret += 1;

	return ret;
}

/**
 * __ctzsi2() - count number of trailing zero bits
 *
 * @x:		number to check
 * Return:	number of trailing zero bits
 */
int __ctzsi2(int x)
{
	int ret = 0;

	if (!x)
		return 32;

	if (!(x & 0xFFFF)) {
		ret += 16;
		x >>= 16;
	}
	if (!(x & 0xFF)) {
		ret += 8;
		x >>= 8;
	}
	if (!(x & 0xF)) {
		ret += 4;
		x >>= 4;
	}
	if (!(x & 0x3)) {
		ret += 2;
		x >>= 2;
	}
	if (!(x & 0x1))
		ret += 1;

	return ret;
}

/**
 * __ctzdi2() - count number of trailing zero bits
 *
 * @x:		number to check
 * Return:	number of trailing zero bits
 */
int __ctzdi2(long x)
{
#if BITS_PER_LONG == 64
	return __ctzti2(x);
#else
	return __ctzsi2(x);
#endif
}