2017
[folly.git] / folly / portability / Builtins.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #ifdef _WIN32
20 #include <assert.h>
21 #include <intrin.h>
22 #include <folly/Portability.h>
23
24 FOLLY_ALWAYS_INLINE int __builtin_clz(unsigned int x) {
25   unsigned long index;
26   return (int)(_BitScanReverse(&index, (unsigned long)x) ? 31 - index : 32);
27 }
28
29 FOLLY_ALWAYS_INLINE int __builtin_clzl(unsigned long x) {
30   return __builtin_clz((unsigned int)x);
31 }
32
33 FOLLY_ALWAYS_INLINE int __builtin_clzll(unsigned long long x) {
34   unsigned long index;
35   return (int)(_BitScanReverse64(&index, x) ? 63 - index : 64);
36 }
37
38 FOLLY_ALWAYS_INLINE int __builtin_ctzll(unsigned long long x) {
39   unsigned long index;
40   return (int)(_BitScanForward64(&index, x) ? index : 64);
41 }
42
43 FOLLY_ALWAYS_INLINE int __builtin_ffs(int x) {
44   unsigned long index;
45   return (int)(_BitScanForward(&index, (unsigned long)x) ? index + 1 : 0);
46 }
47
48 FOLLY_ALWAYS_INLINE int __builtin_ffsl(long x) { return __builtin_ffs((int)x); }
49
50 FOLLY_ALWAYS_INLINE int __builtin_ffsll(long long x) {
51   unsigned long index;
52   return (int)(_BitScanForward64(&index, (unsigned long long)x) ? index + 1 : 0);
53 }
54
55 FOLLY_ALWAYS_INLINE int __builtin_popcountll(unsigned long long x) {
56   return (int)__popcnt64(x);
57 }
58
59 FOLLY_ALWAYS_INLINE void* __builtin_return_address(unsigned int frame) {
60   // I really hope frame is zero...
61   assert(frame == 0);
62   return _ReturnAddress();
63 }
64 #endif