2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <glog/logging.h>
22 #include <immintrin.h>
25 #include <folly/CpuId.h>
26 #include <folly/Portability.h>
27 #include <folly/portability/Builtins.h>
29 namespace folly { namespace compression { namespace instructions {
31 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
32 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
33 // it for __builtin_popcountll intrinsic.
34 // But we provide an alternative way for the client code: it can switch to
35 // the appropriate version of EliasFanoReader<> in realtime (client should
36 // implement this switching logic itself) by specifying instruction set to
40 static bool supported(const folly::CpuId& /* cpuId */ = {}) {
43 static FOLLY_ALWAYS_INLINE uint64_t popcount(uint64_t value) {
44 return __builtin_popcountll(value);
46 static FOLLY_ALWAYS_INLINE int ctz(uint64_t value) {
48 return __builtin_ctzll(value);
50 static FOLLY_ALWAYS_INLINE int clz(uint64_t value) {
52 return __builtin_clzll(value);
54 static FOLLY_ALWAYS_INLINE uint64_t blsr(uint64_t value) {
55 return value & (value - 1);
59 struct Nehalem : public Default {
60 static bool supported(const folly::CpuId& cpuId = {}) {
61 return cpuId.popcnt();
64 static FOLLY_ALWAYS_INLINE uint64_t popcount(uint64_t value) {
65 // POPCNT is supported starting with Intel Nehalem, AMD K10.
66 #if defined(__GNUC__) || defined(__clang__)
67 // GCC and Clang won't inline the intrinsics.
69 asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
72 return _mm_popcnt_u64(value);
77 struct Haswell : public Nehalem {
78 static bool supported(const folly::CpuId& cpuId = {}) {
79 return Nehalem::supported(cpuId) && cpuId.bmi1();
82 static FOLLY_ALWAYS_INLINE uint64_t blsr(uint64_t value) {
83 // BMI1 is supported starting with Intel Haswell, AMD Piledriver.
84 // BLSR combines two instuctions into one and reduces register pressure.
85 #if defined(__GNUC__) || defined(__clang__)
86 // GCC and Clang won't inline the intrinsics.
88 asm ("blsrq %1, %0" : "=r" (result) : "r" (value));
91 return _blsr_u64(value);