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