blob: bf8896d57f4da66688ca361d64e40f776b76cfa8 [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.,
Carl Shapiro1fb86202011-06-27 17:43:13 -070063// figure 3-3, page 48, where the function is called clp2.
64static inline uint32_t RoundUpToPowerOfTwo(uint32_t x) {
65 x = x - 1;
66 x = x | (x >> 1);
67 x = x | (x >> 2);
68 x = x | (x >> 4);
69 x = x | (x >> 8);
70 x = x | (x >> 16);
71 return x + 1;
72}
73
74// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
Carl Shapiroa2e18e12011-06-21 18:57:55 -070075// figure 5-2, page 66, where the function is called pop.
76static inline int CountOneBits(uint32_t x) {
77 x = x - ((x >> 1) & 0x55555555);
78 x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
79 x = (x + (x >> 4)) & 0x0F0F0F0F;
80 x = x + (x >> 8);
81 x = x + (x >> 16);
82 return static_cast<int>(x & 0x0000003F);
83}
84
Carl Shapiro6b6b5f02011-06-21 15:05:09 -070085} // namespace art
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070086
87#endif // ART_SRC_UTILS_H_