blob: a8bf3e726f6501e96ca471663b7fe6844e97070f [file] [log] [blame]
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
3#ifndef ART_SRC_UTILS_H_
4#define ART_SRC_UTILS_H_
5
6#include "src/globals.h"
7
Carl Shapiro6b6b5f02011-06-21 15:05:09 -07008namespace art {
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -07009
Carl Shapiroa2e18e12011-06-21 18:57:55 -070010template<typename T>
11static inline bool IsPowerOfTwo(T x) {
12 return (x & (x - 1)) == 0;
13}
14
15
16template<typename T>
17static inline bool IsAligned(T x, int n) {
18 CHECK(IsPowerOfTwo(n));
19 return (x & (n - 1)) == 0;
20}
21
22
23template<typename T>
24static inline bool IsAligned(T* x, int n) {
25 return IsAligned(reinterpret_cast<uintptr_t>(x), n);
26}
27
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070028// Check whether an N-bit two's-complement representation can hold value.
29static inline bool IsInt(int N, word value) {
30 CHECK_LT(0, N);
31 CHECK_LT(N, kBitsPerWord);
32 word limit = static_cast<word>(1) << (N - 1);
33 return (-limit <= value) && (value < limit);
34}
35
36
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070037static inline bool IsUint(int N, word value) {
38 CHECK_LT(0, N);
39 CHECK_LT(N, kBitsPerWord);
40 word limit = static_cast<word>(1) << N;
41 return (0 <= value) && (value < limit);
42}
43
44
Carl Shapiroa2e18e12011-06-21 18:57:55 -070045static inline bool IsAbsoluteUint(int N, word value) {
46 CHECK_LT(0, N);
47 CHECK_LT(N, kBitsPerWord);
48 if (value < 0) value = -value;
49 return IsUint(N, value);
50}
51
52
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070053static inline int32_t Low32Bits(int64_t value) {
54 return static_cast<int32_t>(value);
55}
56
57
58static inline int32_t High32Bits(int64_t value) {
59 return static_cast<int32_t>(value >> 32);
60}
61
Carl Shapiroa2e18e12011-06-21 18:57:55 -070062// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
63// figure 5-2, page 66, where the function is called pop.
64static inline int CountOneBits(uint32_t x) {
65 x = x - ((x >> 1) & 0x55555555);
66 x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
67 x = (x + (x >> 4)) & 0x0F0F0F0F;
68 x = x + (x >> 8);
69 x = x + (x >> 16);
70 return static_cast<int>(x & 0x0000003F);
71}
72
Carl Shapiro6b6b5f02011-06-21 15:05:09 -070073} // namespace art
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070074
75#endif // ART_SRC_UTILS_H_