add LockTraits
[folly.git] / folly / Bits.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 /**
18  * Various low-level, bit-manipulation routines.
19  *
20  * findFirstSet(x)  [constexpr]
21  *    find first (least significant) bit set in a value of an integral type,
22  *    1-based (like ffs()).  0 = no bits are set (x == 0)
23  *
24  * findLastSet(x)  [constexpr]
25  *    find last (most significant) bit set in a value of an integral type,
26  *    1-based.  0 = no bits are set (x == 0)
27  *    for x != 0, findLastSet(x) == 1 + floor(log2(x))
28  *
29  * nextPowTwo(x)  [constexpr]
30  *    Finds the next power of two >= x.
31  *
32  * isPowTwo(x)  [constexpr]
33  *    return true iff x is a power of two
34  *
35  * popcount(x)
36  *    return the number of 1 bits in x
37  *
38  * Endian
39  *    convert between native, big, and little endian representation
40  *    Endian::big(x)      big <-> native
41  *    Endian::little(x)   little <-> native
42  *    Endian::swap(x)     big <-> little
43  *
44  * BitIterator
45  *    Wrapper around an iterator over an integral type that iterates
46  *    over its underlying bits in MSb to LSb order
47  *
48  * findFirstSet(BitIterator begin, BitIterator end)
49  *    return a BitIterator pointing to the first 1 bit in [begin, end), or
50  *    end if all bits in [begin, end) are 0
51  *
52  * @author Tudor Bosman (tudorb@fb.com)
53  */
54
55 #pragma once
56
57 #if !defined(__clang__) && !(defined(_MSC_VER) && (_MSC_VER < 1900))
58 #define FOLLY_INTRINSIC_CONSTEXPR constexpr
59 #else
60 // GCC and MSVC 2015+ are the only compilers with
61 // intrinsics constexpr.
62 #define FOLLY_INTRINSIC_CONSTEXPR const
63 #endif
64
65 #include <folly/Portability.h>
66
67 #include <folly/detail/BitsDetail.h>
68 #include <folly/detail/BitIteratorDetail.h>
69 #include <folly/Likely.h>
70
71 #if FOLLY_HAVE_BYTESWAP_H
72 # include <byteswap.h>
73 #endif
74
75 #include <cassert>
76 #include <cinttypes>
77 #include <iterator>
78 #include <limits>
79 #include <type_traits>
80 #include <boost/iterator/iterator_adaptor.hpp>
81 #include <stdint.h>
82
83 namespace folly {
84
85 // Generate overloads for findFirstSet as wrappers around
86 // appropriate ffs, ffsl, ffsll gcc builtins
87 template <class T>
88 inline FOLLY_INTRINSIC_CONSTEXPR
89 typename std::enable_if<
90   (std::is_integral<T>::value &&
91    std::is_unsigned<T>::value &&
92    sizeof(T) <= sizeof(unsigned int)),
93   unsigned int>::type
94   findFirstSet(T x) {
95   return __builtin_ffs(x);
96 }
97
98 template <class T>
99 inline FOLLY_INTRINSIC_CONSTEXPR
100 typename std::enable_if<
101   (std::is_integral<T>::value &&
102    std::is_unsigned<T>::value &&
103    sizeof(T) > sizeof(unsigned int) &&
104    sizeof(T) <= sizeof(unsigned long)),
105   unsigned int>::type
106   findFirstSet(T x) {
107   return __builtin_ffsl(x);
108 }
109
110 template <class T>
111 inline FOLLY_INTRINSIC_CONSTEXPR
112 typename std::enable_if<
113   (std::is_integral<T>::value &&
114    std::is_unsigned<T>::value &&
115    sizeof(T) > sizeof(unsigned long) &&
116    sizeof(T) <= sizeof(unsigned long long)),
117   unsigned int>::type
118   findFirstSet(T x) {
119   return __builtin_ffsll(x);
120 }
121
122 template <class T>
123 inline FOLLY_INTRINSIC_CONSTEXPR
124 typename std::enable_if<
125   (std::is_integral<T>::value && std::is_signed<T>::value),
126   unsigned int>::type
127   findFirstSet(T x) {
128   // Note that conversion from a signed type to the corresponding unsigned
129   // type is technically implementation-defined, but will likely work
130   // on any impementation that uses two's complement.
131   return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
132 }
133
134 // findLastSet: return the 1-based index of the highest bit set
135 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
136 template <class T>
137 inline FOLLY_INTRINSIC_CONSTEXPR
138 typename std::enable_if<
139   (std::is_integral<T>::value &&
140    std::is_unsigned<T>::value &&
141    sizeof(T) <= sizeof(unsigned int)),
142   unsigned int>::type
143   findLastSet(T x) {
144   return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
145 }
146
147 template <class T>
148 inline FOLLY_INTRINSIC_CONSTEXPR
149 typename std::enable_if<
150   (std::is_integral<T>::value &&
151    std::is_unsigned<T>::value &&
152    sizeof(T) > sizeof(unsigned int) &&
153    sizeof(T) <= sizeof(unsigned long)),
154   unsigned int>::type
155   findLastSet(T x) {
156   return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
157 }
158
159 template <class T>
160 inline FOLLY_INTRINSIC_CONSTEXPR
161 typename std::enable_if<
162   (std::is_integral<T>::value &&
163    std::is_unsigned<T>::value &&
164    sizeof(T) > sizeof(unsigned long) &&
165    sizeof(T) <= sizeof(unsigned long long)),
166   unsigned int>::type
167   findLastSet(T x) {
168   return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
169 }
170
171 template <class T>
172 inline FOLLY_INTRINSIC_CONSTEXPR
173 typename std::enable_if<
174   (std::is_integral<T>::value &&
175    std::is_signed<T>::value),
176   unsigned int>::type
177   findLastSet(T x) {
178   return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
179 }
180
181 template <class T>
182 inline FOLLY_INTRINSIC_CONSTEXPR
183 typename std::enable_if<
184   std::is_integral<T>::value && std::is_unsigned<T>::value,
185   T>::type
186 nextPowTwo(T v) {
187   return v ? (1ul << findLastSet(v - 1)) : 1;
188 }
189
190 template <class T>
191 inline constexpr
192 typename std::enable_if<
193   std::is_integral<T>::value && std::is_unsigned<T>::value,
194   bool>::type
195 isPowTwo(T v) {
196   return (v != 0) && !(v & (v - 1));
197 }
198
199 /**
200  * Population count
201  */
202 template <class T>
203 inline typename std::enable_if<
204   (std::is_integral<T>::value &&
205    std::is_unsigned<T>::value &&
206    sizeof(T) <= sizeof(unsigned int)),
207   size_t>::type
208   popcount(T x) {
209   return detail::popcount(x);
210 }
211
212 template <class T>
213 inline typename std::enable_if<
214   (std::is_integral<T>::value &&
215    std::is_unsigned<T>::value &&
216    sizeof(T) > sizeof(unsigned int) &&
217    sizeof(T) <= sizeof(unsigned long long)),
218   size_t>::type
219   popcount(T x) {
220   return detail::popcountll(x);
221 }
222
223 /**
224  * Endianness detection and manipulation primitives.
225  */
226 namespace detail {
227
228 template <class T>
229 struct EndianIntBase {
230  public:
231   static T swap(T x);
232 };
233
234 #ifndef _MSC_VER
235
236 /**
237  * If we have the bswap_16 macro from byteswap.h, use it; otherwise, provide our
238  * own definition.
239  */
240 #ifdef bswap_16
241 # define our_bswap16 bswap_16
242 #else
243
244 template<class Int16>
245 inline constexpr typename std::enable_if<
246   sizeof(Int16) == 2,
247   Int16>::type
248 our_bswap16(Int16 x) {
249   return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
250 }
251 #endif
252
253 #endif
254
255 #define FB_GEN(t, fn) \
256 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
257
258 // fn(x) expands to (x) if the second argument is empty, which is exactly
259 // what we want for [u]int8_t. Also, gcc 4.7 on Intel doesn't have
260 // __builtin_bswap16 for some reason, so we have to provide our own.
261 FB_GEN( int8_t,)
262 FB_GEN(uint8_t,)
263 #ifdef _MSC_VER
264 FB_GEN( int64_t, _byteswap_uint64)
265 FB_GEN(uint64_t, _byteswap_uint64)
266 FB_GEN( int32_t, _byteswap_ulong)
267 FB_GEN(uint32_t, _byteswap_ulong)
268 FB_GEN( int16_t, _byteswap_ushort)
269 FB_GEN(uint16_t, _byteswap_ushort)
270 #else
271 FB_GEN( int64_t, __builtin_bswap64)
272 FB_GEN(uint64_t, __builtin_bswap64)
273 FB_GEN( int32_t, __builtin_bswap32)
274 FB_GEN(uint32_t, __builtin_bswap32)
275 FB_GEN( int16_t, our_bswap16)
276 FB_GEN(uint16_t, our_bswap16)
277 #endif
278
279 #undef FB_GEN
280
281 template <class T>
282 struct EndianInt : public EndianIntBase<T> {
283  public:
284   static T big(T x) {
285     return kIsLittleEndian ? EndianInt::swap(x) : x;
286   }
287   static T little(T x) {
288     return kIsBigEndian ? EndianInt::swap(x) : x;
289   }
290 };
291
292 }  // namespace detail
293
294 // big* convert between native and big-endian representations
295 // little* convert between native and little-endian representations
296 // swap* convert between big-endian and little-endian representations
297 //
298 // ntohs, htons == big16
299 // ntohl, htonl == big32
300 #define FB_GEN1(fn, t, sz) \
301   static t fn##sz(t x) { return fn<t>(x); } \
302
303 #define FB_GEN2(t, sz) \
304   FB_GEN1(swap, t, sz) \
305   FB_GEN1(big, t, sz) \
306   FB_GEN1(little, t, sz)
307
308 #define FB_GEN(sz) \
309   FB_GEN2(uint##sz##_t, sz) \
310   FB_GEN2(int##sz##_t, sz)
311
312 class Endian {
313  public:
314   enum class Order : uint8_t {
315     LITTLE,
316     BIG
317   };
318
319   static constexpr Order order = kIsLittleEndian ? Order::LITTLE : Order::BIG;
320
321   template <class T> static T swap(T x) {
322     return folly::detail::EndianInt<T>::swap(x);
323   }
324   template <class T> static T big(T x) {
325     return folly::detail::EndianInt<T>::big(x);
326   }
327   template <class T> static T little(T x) {
328     return folly::detail::EndianInt<T>::little(x);
329   }
330
331 #if !defined(__ANDROID__)
332   FB_GEN(64)
333   FB_GEN(32)
334   FB_GEN(16)
335   FB_GEN(8)
336 #endif
337 };
338
339 #undef FB_GEN
340 #undef FB_GEN2
341 #undef FB_GEN1
342
343 /**
344  * Fast bit iteration facility.
345  */
346
347
348 template <class BaseIter> class BitIterator;
349 template <class BaseIter>
350 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
351                                    BitIterator<BaseIter>);
352 /**
353  * Wrapper around an iterator over an integer type that iterates
354  * over its underlying bits in LSb to MSb order.
355  *
356  * BitIterator models the same iterator concepts as the base iterator.
357  */
358 template <class BaseIter>
359 class BitIterator
360   : public bititerator_detail::BitIteratorBase<BaseIter>::type {
361  public:
362   /**
363    * Return the number of bits in an element of the underlying iterator.
364    */
365   static unsigned int bitsPerBlock() {
366     return std::numeric_limits<
367       typename std::make_unsigned<
368         typename std::iterator_traits<BaseIter>::value_type
369       >::type
370     >::digits;
371   }
372
373   /**
374    * Construct a BitIterator that points at a given bit offset (default 0)
375    * in iter.
376    */
377   #pragma GCC diagnostic push // bitOffset shadows a member
378   #pragma GCC diagnostic ignored "-Wshadow"
379   explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
380     : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
381       bitOffset_(bitOffset) {
382     assert(bitOffset_ < bitsPerBlock());
383   }
384   #pragma GCC diagnostic pop
385
386   size_t bitOffset() const {
387     return bitOffset_;
388   }
389
390   void advanceToNextBlock() {
391     bitOffset_ = 0;
392     ++this->base_reference();
393   }
394
395   BitIterator& operator=(const BaseIter& other) {
396     this->~BitIterator();
397     new (this) BitIterator(other);
398     return *this;
399   }
400
401  private:
402   friend class boost::iterator_core_access;
403   friend BitIterator findFirstSet<>(BitIterator, BitIterator);
404
405   typedef bititerator_detail::BitReference<
406       typename std::iterator_traits<BaseIter>::reference,
407       typename std::iterator_traits<BaseIter>::value_type
408     > BitRef;
409
410   void advanceInBlock(size_t n) {
411     bitOffset_ += n;
412     assert(bitOffset_ < bitsPerBlock());
413   }
414
415   BitRef dereference() const {
416     return BitRef(*this->base_reference(), bitOffset_);
417   }
418
419   void advance(ssize_t n) {
420     size_t bpb = bitsPerBlock();
421     ssize_t blocks = n / bpb;
422     bitOffset_ += n % bpb;
423     if (bitOffset_ >= bpb) {
424       bitOffset_ -= bpb;
425       ++blocks;
426     }
427     this->base_reference() += blocks;
428   }
429
430   void increment() {
431     if (++bitOffset_ == bitsPerBlock()) {
432       advanceToNextBlock();
433     }
434   }
435
436   void decrement() {
437     if (bitOffset_-- == 0) {
438       bitOffset_ = bitsPerBlock() - 1;
439       --this->base_reference();
440     }
441   }
442
443   bool equal(const BitIterator& other) const {
444     return (bitOffset_ == other.bitOffset_ &&
445             this->base_reference() == other.base_reference());
446   }
447
448   ssize_t distance_to(const BitIterator& other) const {
449     return
450       (other.base_reference() - this->base_reference()) * bitsPerBlock() +
451       other.bitOffset_ - bitOffset_;
452   }
453
454   unsigned int bitOffset_;
455 };
456
457 /**
458  * Helper function, so you can write
459  * auto bi = makeBitIterator(container.begin());
460  */
461 template <class BaseIter>
462 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
463   return BitIterator<BaseIter>(iter);
464 }
465
466
467 /**
468  * Find first bit set in a range of bit iterators.
469  * 4.5x faster than the obvious std::find(begin, end, true);
470  */
471 template <class BaseIter>
472 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
473                                    BitIterator<BaseIter> end) {
474   // shortcut to avoid ugly static_cast<>
475   static const typename BaseIter::value_type one = 1;
476
477   while (begin.base() != end.base()) {
478     typename BaseIter::value_type v = *begin.base();
479     // mask out the bits that don't matter (< begin.bitOffset)
480     v &= ~((one << begin.bitOffset()) - 1);
481     size_t firstSet = findFirstSet(v);
482     if (firstSet) {
483       --firstSet;  // now it's 0-based
484       assert(firstSet >= begin.bitOffset());
485       begin.advanceInBlock(firstSet - begin.bitOffset());
486       return begin;
487     }
488     begin.advanceToNextBlock();
489   }
490
491   // now begin points to the same block as end
492   if (end.bitOffset() != 0) {  // assume end is dereferenceable
493     typename BaseIter::value_type v = *begin.base();
494     // mask out the bits that don't matter (< begin.bitOffset)
495     v &= ~((one << begin.bitOffset()) - 1);
496     // mask out the bits that don't matter (>= end.bitOffset)
497     v &= (one << end.bitOffset()) - 1;
498     size_t firstSet = findFirstSet(v);
499     if (firstSet) {
500       --firstSet;  // now it's 0-based
501       assert(firstSet >= begin.bitOffset());
502       begin.advanceInBlock(firstSet - begin.bitOffset());
503       return begin;
504     }
505   }
506
507   return end;
508 }
509
510
511 template <class T, class Enable=void> struct Unaligned;
512
513 /**
514  * Representation of an unaligned value of a POD type.
515  */
516 FOLLY_PACK_PUSH
517 template <class T>
518 struct Unaligned<
519     T,
520     typename std::enable_if<std::is_pod<T>::value>::type> {
521   Unaligned() = default;  // uninitialized
522   /* implicit */ Unaligned(T v) : value(v) { }
523   T value;
524 } FOLLY_PACK_ATTR;
525 FOLLY_PACK_POP
526
527 /**
528  * Read an unaligned value of type T and return it.
529  */
530 template <class T>
531 inline T loadUnaligned(const void* p) {
532   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
533   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
534   if (kHasUnalignedAccess) {
535     return static_cast<const Unaligned<T>*>(p)->value;
536   } else {
537     T value;
538     memcpy(&value, p, sizeof(T));
539     return value;
540   }
541 }
542
543 /**
544  * Write an unaligned value of type T.
545  */
546 template <class T>
547 inline void storeUnaligned(void* p, T value) {
548   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
549   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
550   if (kHasUnalignedAccess) {
551     new (p) Unaligned<T>(value);
552   } else {
553     memcpy(p, &value, sizeof(T));
554   }
555 }
556
557 }  // namespace folly