Harden failure signal handler in the face of memory corruptions
[folly.git] / folly / Bits.h
1 /*
2  * Copyright 2014 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 #ifndef FOLLY_BITS_H_
56 #define FOLLY_BITS_H_
57
58 #include "folly/Portability.h"
59
60 #ifndef __GNUC__
61 #error GCC required
62 #endif
63
64 #ifndef __clang__
65 #define FOLLY_INTRINSIC_CONSTEXPR constexpr
66 #else
67 // Unlike GCC, in Clang (as of 3.2) intrinsics aren't constexpr.
68 #define FOLLY_INTRINSIC_CONSTEXPR const
69 #endif
70
71 #ifndef FOLLY_NO_CONFIG
72 #include "folly/folly-config.h"
73 #endif
74
75 #include "folly/detail/BitsDetail.h"
76 #include "folly/detail/BitIteratorDetail.h"
77 #include "folly/Likely.h"
78
79 #if FOLLY_HAVE_BYTESWAP_H
80 # include <byteswap.h>
81 #endif
82
83 #include <cassert>
84 #include <cinttypes>
85 #include <iterator>
86 #include <limits>
87 #include <type_traits>
88 #include <boost/iterator/iterator_adaptor.hpp>
89 #include <stdint.h>
90
91 namespace folly {
92
93 // Generate overloads for findFirstSet as wrappers around
94 // appropriate ffs, ffsl, ffsll gcc builtins
95 template <class T>
96 inline FOLLY_INTRINSIC_CONSTEXPR
97 typename std::enable_if<
98   (std::is_integral<T>::value &&
99    std::is_unsigned<T>::value &&
100    sizeof(T) <= sizeof(unsigned int)),
101   unsigned int>::type
102   findFirstSet(T x) {
103   return __builtin_ffs(x);
104 }
105
106 template <class T>
107 inline FOLLY_INTRINSIC_CONSTEXPR
108 typename std::enable_if<
109   (std::is_integral<T>::value &&
110    std::is_unsigned<T>::value &&
111    sizeof(T) > sizeof(unsigned int) &&
112    sizeof(T) <= sizeof(unsigned long)),
113   unsigned int>::type
114   findFirstSet(T x) {
115   return __builtin_ffsl(x);
116 }
117
118 template <class T>
119 inline FOLLY_INTRINSIC_CONSTEXPR
120 typename std::enable_if<
121   (std::is_integral<T>::value &&
122    std::is_unsigned<T>::value &&
123    sizeof(T) > sizeof(unsigned long) &&
124    sizeof(T) <= sizeof(unsigned long long)),
125   unsigned int>::type
126   findFirstSet(T x) {
127   return __builtin_ffsll(x);
128 }
129
130 template <class T>
131 inline FOLLY_INTRINSIC_CONSTEXPR
132 typename std::enable_if<
133   (std::is_integral<T>::value && std::is_signed<T>::value),
134   unsigned int>::type
135   findFirstSet(T x) {
136   // Note that conversion from a signed type to the corresponding unsigned
137   // type is technically implementation-defined, but will likely work
138   // on any impementation that uses two's complement.
139   return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
140 }
141
142 // findLastSet: return the 1-based index of the highest bit set
143 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
144 template <class T>
145 inline FOLLY_INTRINSIC_CONSTEXPR
146 typename std::enable_if<
147   (std::is_integral<T>::value &&
148    std::is_unsigned<T>::value &&
149    sizeof(T) <= sizeof(unsigned int)),
150   unsigned int>::type
151   findLastSet(T x) {
152   return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
153 }
154
155 template <class T>
156 inline FOLLY_INTRINSIC_CONSTEXPR
157 typename std::enable_if<
158   (std::is_integral<T>::value &&
159    std::is_unsigned<T>::value &&
160    sizeof(T) > sizeof(unsigned int) &&
161    sizeof(T) <= sizeof(unsigned long)),
162   unsigned int>::type
163   findLastSet(T x) {
164   return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
165 }
166
167 template <class T>
168 inline FOLLY_INTRINSIC_CONSTEXPR
169 typename std::enable_if<
170   (std::is_integral<T>::value &&
171    std::is_unsigned<T>::value &&
172    sizeof(T) > sizeof(unsigned long) &&
173    sizeof(T) <= sizeof(unsigned long long)),
174   unsigned int>::type
175   findLastSet(T x) {
176   return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
177 }
178
179 template <class T>
180 inline FOLLY_INTRINSIC_CONSTEXPR
181 typename std::enable_if<
182   (std::is_integral<T>::value &&
183    std::is_signed<T>::value),
184   unsigned int>::type
185   findLastSet(T x) {
186   return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
187 }
188
189 template <class T>
190 inline FOLLY_INTRINSIC_CONSTEXPR
191 typename std::enable_if<
192   std::is_integral<T>::value && std::is_unsigned<T>::value,
193   T>::type
194 nextPowTwo(T v) {
195   return v ? (1ul << findLastSet(v - 1)) : 1;
196 }
197
198 template <class T>
199 inline constexpr
200 typename std::enable_if<
201   std::is_integral<T>::value && std::is_unsigned<T>::value,
202   bool>::type
203 isPowTwo(T v) {
204   return (v != 0) && !(v & (v - 1));
205 }
206
207 /**
208  * Population count
209  */
210 template <class T>
211 inline typename std::enable_if<
212   (std::is_integral<T>::value &&
213    std::is_unsigned<T>::value &&
214    sizeof(T) <= sizeof(unsigned int)),
215   size_t>::type
216   popcount(T x) {
217   return detail::popcount(x);
218 }
219
220 template <class T>
221 inline typename std::enable_if<
222   (std::is_integral<T>::value &&
223    std::is_unsigned<T>::value &&
224    sizeof(T) > sizeof(unsigned int) &&
225    sizeof(T) <= sizeof(unsigned long long)),
226   size_t>::type
227   popcount(T x) {
228   return detail::popcountll(x);
229 }
230
231 /**
232  * Endianness detection and manipulation primitives.
233  */
234 namespace detail {
235
236 template <class T>
237 struct EndianIntBase {
238  public:
239   static T swap(T x);
240 };
241
242 /**
243  * If we have the bswap_16 macro from byteswap.h, use it; otherwise, provide our
244  * own definition.
245  */
246 #ifdef bswap_16
247 # define our_bswap16 bswap_16
248 #else
249
250 template<class Int16>
251 inline constexpr typename std::enable_if<
252   sizeof(Int16) == 2,
253   Int16>::type
254 our_bswap16(Int16 x) {
255   return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
256 }
257 #endif
258
259 #define FB_GEN(t, fn) \
260 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
261
262 // fn(x) expands to (x) if the second argument is empty, which is exactly
263 // what we want for [u]int8_t. Also, gcc 4.7 on Intel doesn't have
264 // __builtin_bswap16 for some reason, so we have to provide our own.
265 FB_GEN( int8_t,)
266 FB_GEN(uint8_t,)
267 FB_GEN( int64_t, __builtin_bswap64)
268 FB_GEN(uint64_t, __builtin_bswap64)
269 FB_GEN( int32_t, __builtin_bswap32)
270 FB_GEN(uint32_t, __builtin_bswap32)
271 FB_GEN( int16_t, our_bswap16)
272 FB_GEN(uint16_t, our_bswap16)
273
274 #undef FB_GEN
275
276 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
277
278 template <class T>
279 struct EndianInt : public detail::EndianIntBase<T> {
280  public:
281   static T big(T x) { return EndianInt::swap(x); }
282   static T little(T x) { return x; }
283 };
284
285 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
286
287 template <class T>
288 struct EndianInt : public detail::EndianIntBase<T> {
289  public:
290   static T big(T x) { return x; }
291   static T little(T x) { return EndianInt::swap(x); }
292 };
293
294 #else
295 # error Your machine uses a weird endianness!
296 #endif  /* __BYTE_ORDER__ */
297
298 }  // namespace detail
299
300 // big* convert between native and big-endian representations
301 // little* convert between native and little-endian representations
302 // swap* convert between big-endian and little-endian representations
303 //
304 // ntohs, htons == big16
305 // ntohl, htonl == big32
306 #define FB_GEN1(fn, t, sz) \
307   static t fn##sz(t x) { return fn<t>(x); } \
308
309 #define FB_GEN2(t, sz) \
310   FB_GEN1(swap, t, sz) \
311   FB_GEN1(big, t, sz) \
312   FB_GEN1(little, t, sz)
313
314 #define FB_GEN(sz) \
315   FB_GEN2(uint##sz##_t, sz) \
316   FB_GEN2(int##sz##_t, sz)
317
318 class Endian {
319  public:
320   enum class Order : uint8_t {
321     LITTLE,
322     BIG
323   };
324
325   static constexpr Order order =
326 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
327     Order::LITTLE;
328 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
329     Order::BIG;
330 #else
331 # error Your machine uses a weird endianness!
332 #endif  /* __BYTE_ORDER__ */
333
334   template <class T> static T swap(T x) {
335     return detail::EndianInt<T>::swap(x);
336   }
337   template <class T> static T big(T x) {
338     return detail::EndianInt<T>::big(x);
339   }
340   template <class T> static T little(T x) {
341     return detail::EndianInt<T>::little(x);
342   }
343
344   FB_GEN(64)
345   FB_GEN(32)
346   FB_GEN(16)
347   FB_GEN(8)
348 };
349
350 #undef FB_GEN
351 #undef FB_GEN2
352 #undef FB_GEN1
353
354 /**
355  * Fast bit iteration facility.
356  */
357
358
359 template <class BaseIter> class BitIterator;
360 template <class BaseIter>
361 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
362                                    BitIterator<BaseIter>);
363 /**
364  * Wrapper around an iterator over an integer type that iterates
365  * over its underlying bits in LSb to MSb order.
366  *
367  * BitIterator models the same iterator concepts as the base iterator.
368  */
369 template <class BaseIter>
370 class BitIterator
371   : public bititerator_detail::BitIteratorBase<BaseIter>::type {
372  public:
373   /**
374    * Return the number of bits in an element of the underlying iterator.
375    */
376   static size_t bitsPerBlock() {
377     return std::numeric_limits<
378       typename std::make_unsigned<
379         typename std::iterator_traits<BaseIter>::value_type
380       >::type
381     >::digits;
382   }
383
384   /**
385    * Construct a BitIterator that points at a given bit offset (default 0)
386    * in iter.
387    */
388   #pragma GCC diagnostic push // bitOffset shadows a member
389   #pragma GCC diagnostic ignored "-Wshadow"
390   explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
391     : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
392       bitOffset_(bitOffset) {
393     assert(bitOffset_ < bitsPerBlock());
394   }
395   #pragma GCC diagnostic pop
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   ssize_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 template <class T>
528 struct Unaligned<
529     T,
530     typename std::enable_if<std::is_pod<T>::value>::type> {
531   Unaligned() = default;  // uninitialized
532   /* implicit */ Unaligned(T v) : value(v) { }
533   T value;
534 } __attribute__((packed));
535
536 /**
537  * Read an unaligned value of type T and return it.
538  */
539 template <class T>
540 inline T loadUnaligned(const void* p) {
541   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
542   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
543   return static_cast<const Unaligned<T>*>(p)->value;
544 }
545
546 /**
547  * Write an unaligned value of type T.
548  */
549 template <class T>
550 inline void storeUnaligned(void* p, T value) {
551   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
552   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
553   new (p) Unaligned<T>(value);
554 }
555
556 }  // namespace folly
557
558 #endif /* FOLLY_BITS_H_ */