folly copyright 2015 -> copyright 2016
[folly.git] / folly / experimental / Instructions.h
1 /*
2  * Copyright 2016 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 #ifndef FOLLY_EXPERIMENTAL_INSTRUCTIONS_H
18 #define FOLLY_EXPERIMENTAL_INSTRUCTIONS_H
19
20 #include <folly/CpuId.h>
21
22 namespace folly { namespace compression { namespace instructions {
23
24 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
25 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
26 // it for __builtin_popcountll intrinsic.
27 // But we provide an alternative way for the client code: it can switch to
28 // the appropriate version of EliasFanoReader<> in realtime (client should
29 // implement this switching logic itself) by specifying instruction set to
30 // use explicitly.
31
32 struct Default {
33   static bool supported(const folly::CpuId& /* cpuId */ = {}) { return true; }
34   static inline uint64_t popcount(uint64_t value) {
35     return __builtin_popcountll(value);
36   }
37   static inline int ctz(uint64_t value) {
38     DCHECK_GT(value, 0);
39     return __builtin_ctzll(value);
40   }
41   static inline int clz(uint64_t value) {
42     DCHECK_GT(value, 0);
43     return __builtin_clzll(value);
44   }
45   static inline uint64_t blsr(uint64_t value) {
46     return value & (value - 1);
47   }
48 };
49
50 struct Nehalem : public Default {
51   static bool supported(const folly::CpuId& cpuId = {}) {
52     return cpuId.popcnt();
53   }
54   static inline uint64_t popcount(uint64_t value) {
55     // POPCNT is supported starting with Intel Nehalem, AMD K10.
56     uint64_t result;
57     asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
58     return result;
59   }
60 };
61
62 struct Haswell : public Nehalem {
63   static bool supported(const folly::CpuId& cpuId = {}) {
64     return Nehalem::supported(cpuId) && cpuId.bmi1();
65   }
66   static inline uint64_t blsr(uint64_t value) {
67     // BMI1 is supported starting with Intel Haswell, AMD Piledriver.
68     // BLSR combines two instuctions into one and reduces register pressure.
69     uint64_t result;
70     asm ("blsrq %1, %0" : "=r" (result) : "r" (value));
71     return result;
72   }
73 };
74
75 }}}  // namespaces
76
77 #endif  // FOLLY_EXPERIMENTAL_INSTRUCTIONS_H