Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/CodeGen/src/BitUtils.h
2725 views
1
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
2
#pragma once
3
4
#include <stdint.h>
5
6
#ifdef _MSC_VER
7
#include <intrin.h>
8
#endif
9
10
namespace Luau
11
{
12
namespace CodeGen
13
{
14
15
inline int countlz(uint32_t n)
16
{
17
#ifdef _MSC_VER
18
unsigned long rl;
19
return _BitScanReverse(&rl, n) ? 31 - int(rl) : 32;
20
#else
21
return n == 0 ? 32 : __builtin_clz(n);
22
#endif
23
}
24
25
inline int countrz(uint32_t n)
26
{
27
#ifdef _MSC_VER
28
unsigned long rl;
29
return _BitScanForward(&rl, n) ? int(rl) : 32;
30
#else
31
return n == 0 ? 32 : __builtin_ctz(n);
32
#endif
33
}
34
35
inline int countrz(uint64_t n)
36
{
37
#ifdef _MSC_VER
38
39
#ifdef _WIN64
40
unsigned long rl;
41
return _BitScanForward64(&rl, n) ? int(rl) : 64;
42
#else
43
unsigned long rl;
44
if (_BitScanForward(&rl, uint32_t(n)))
45
return rl;
46
return _BitScanForward(&rl, uint32_t(n >> 32)) ? int(rl) + 32 : 64;
47
#endif
48
49
#else
50
return n == 0 ? 64 : __builtin_ctzll(n);
51
#endif
52
}
53
54
inline int lrotate(uint32_t u, int s)
55
{
56
// MSVC doesn't recognize the rotate form that is UB-safe
57
#ifdef _MSC_VER
58
return _rotl(u, s);
59
#else
60
return (u << (s & 31)) | (u >> ((32 - s) & 31));
61
#endif
62
}
63
64
inline int rrotate(uint32_t u, int s)
65
{
66
// MSVC doesn't recognize the rotate form that is UB-safe
67
#ifdef _MSC_VER
68
return _rotr(u, s);
69
#else
70
return (u >> (s & 31)) | (u << ((32 - s) & 31));
71
#endif
72
}
73
74
} // namespace CodeGen
75
} // namespace Luau
76
77