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