Make folly::Singleton's destruction happen earlier
[folly.git] / folly / experimental / EliasFanoCoding.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  * @author Philip Pronin (philipp@fb.com)
19  *
20  * Based on the paper by Sebastiano Vigna,
21  * "Quasi-succinct indices" (arxiv:1206.4300).
22  */
23
24 #ifndef FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
25 #define FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
26
27 #ifndef __GNUC__
28 #error EliasFanoCoding.h requires GCC
29 #endif
30
31 #if !FOLLY_X64
32 #error EliasFanoCoding.h requires x86_64
33 #endif
34
35 #include <cstdlib>
36 #include <limits>
37 #include <type_traits>
38 #include <boost/noncopyable.hpp>
39 #include <glog/logging.h>
40
41 #include <folly/Bits.h>
42 #include <folly/CpuId.h>
43 #include <folly/Likely.h>
44 #include <folly/Range.h>
45
46 #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
47 #error EliasFanoCoding.h requires little endianness
48 #endif
49
50 namespace folly { namespace compression {
51
52 struct EliasFanoCompressedList {
53   EliasFanoCompressedList() { }
54
55   void free() {
56     ::free(const_cast<unsigned char*>(lower.data()));
57     ::free(const_cast<unsigned char*>(upper.data()));
58     ::free(const_cast<unsigned char*>(skipPointers.data()));
59     ::free(const_cast<unsigned char*>(forwardPointers.data()));
60   }
61
62   size_t size = 0;
63   uint8_t numLowerBits = 0;
64
65   // WARNING: EliasFanoCompressedList has no ownership of
66   // lower, upper, skipPointers and forwardPointers.
67   // The 7 bytes following the last byte of lower and upper
68   // sequences should be readable.
69   folly::ByteRange lower;
70   folly::ByteRange upper;
71
72   folly::ByteRange skipPointers;
73   folly::ByteRange forwardPointers;
74 };
75
76 // Version history:
77 // In version 1 skip / forward pointers encoding has been changed,
78 // so SkipValue = uint32_t is able to address up to ~4B elements,
79 // instead of only ~2B.
80 template <class Value,
81           class SkipValue = size_t,
82           size_t kSkipQuantum = 0,     // 0 = disabled
83           size_t kForwardQuantum = 0,  // 0 = disabled
84           size_t kVersion = 0>
85 struct EliasFanoEncoder {
86   static_assert(std::is_integral<Value>::value &&
87                 std::is_unsigned<Value>::value,
88                 "Value should be unsigned integral");
89
90   typedef EliasFanoCompressedList CompressedList;
91
92   typedef Value ValueType;
93   typedef SkipValue SkipValueType;
94
95   static constexpr size_t skipQuantum = kSkipQuantum;
96   static constexpr size_t forwardQuantum = kForwardQuantum;
97   static constexpr size_t version = kVersion;
98
99   static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
100     if (size == 0 || upperBound < size) {
101       return 0;
102     }
103     // floor(log(upperBound / size));
104     return folly::findLastSet(upperBound / size) - 1;
105   }
106
107   // Requires: input range (begin, end) is sorted (encoding
108   // crashes if it's not).
109   // WARNING: encode() mallocates lower, upper, skipPointers
110   // and forwardPointers. As EliasFanoCompressedList has
111   // no ownership of them, you need to call free() explicitly.
112   template <class RandomAccessIterator>
113   static EliasFanoCompressedList encode(RandomAccessIterator begin,
114                                         RandomAccessIterator end) {
115     if (begin == end) {
116       return EliasFanoCompressedList();
117     }
118     EliasFanoEncoder encoder(end - begin, *(end - 1));
119     for (; begin != end; ++begin) {
120       encoder.add(*begin);
121     }
122     return encoder.finish();
123   }
124
125   EliasFanoEncoder(size_t size, ValueType upperBound) {
126     if (size == 0) {
127       return;
128     }
129
130     uint8_t numLowerBits = defaultNumLowerBits(upperBound, size);
131
132     // This is detail::writeBits56 limitation.
133     numLowerBits = std::min<uint8_t>(numLowerBits, 56);
134     CHECK_LT(numLowerBits, 8 * sizeof(Value));  // As we shift by numLowerBits.
135
136     // WARNING: Current read/write logic assumes that the 7 bytes
137     // following the last byte of lower and upper sequences are
138     // readable (stored value doesn't matter and won't be changed),
139     // so we allocate additional 7B, but do not include them in size
140     // of returned value.
141
142     // *** Lower bits.
143     const size_t lowerSize = (numLowerBits * size + 7) / 8;
144     if (lowerSize > 0) {  // numLowerBits != 0
145       lower_ = static_cast<unsigned char*>(calloc(lowerSize + 7, 1));
146     }
147
148     // *** Upper bits.
149     // Upper bits are stored using unary delta encoding.
150     // For example, (3 5 5 9) will be encoded as 1000011001000_2.
151     const size_t upperSizeBits =
152       (upperBound >> numLowerBits) +  // Number of 0-bits to be stored.
153       size;                           // 1-bits.
154     const size_t upperSize = (upperSizeBits + 7) / 8;
155     upper_ = static_cast<unsigned char*>(calloc(upperSize + 7, 1));
156
157     // *** Skip pointers.
158     // Store (1-indexed) position of every skipQuantum-th
159     // 0-bit in upper bits sequence.
160     size_t numSkipPointers = 0;
161     /* static */ if (skipQuantum != 0) {
162       /* static */ if (kVersion > 0) {
163         CHECK_LT(size, std::numeric_limits<SkipValueType>::max());
164       } else {
165         CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
166       }
167       // 8 * upperSize is used here instead of upperSizeBits, as that is
168       // more serialization-friendly way (upperSizeBits isn't known outside of
169       // this function, unlike upperSize; thus numSkipPointers could easily be
170       // deduced from upperSize).
171       numSkipPointers = (8 * upperSize - size) / (skipQuantum ?: 1);
172       skipPointers_ = static_cast<SkipValueType*>(
173           numSkipPointers == 0
174             ? nullptr
175             : calloc(numSkipPointers, sizeof(SkipValueType)));
176     }
177
178     // *** Forward pointers.
179     // Store (1-indexed) position of every forwardQuantum-th
180     // 1-bit in upper bits sequence.
181     size_t numForwardPointers = 0;
182     /* static */ if (forwardQuantum != 0) {
183       /* static */ if (kVersion > 0) {
184         CHECK_LT(upperBound >> numLowerBits,
185                  std::numeric_limits<SkipValueType>::max());
186       } else {
187         CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
188       }
189
190       // '?: 1' is a workaround for false 'division by zero' compile-time error.
191       numForwardPointers = size / (forwardQuantum ?: 1);
192       forwardPointers_ = static_cast<SkipValueType*>(
193         numForwardPointers == 0
194           ? nullptr
195           : malloc(numForwardPointers * sizeof(SkipValueType)));
196     }
197
198     // *** Result.
199     result_.size = size;
200     result_.numLowerBits = numLowerBits;
201     result_.lower.reset(lower_, lowerSize);
202     result_.upper.reset(upper_, upperSize);
203     result_.skipPointers.reset(
204         reinterpret_cast<unsigned char*>(skipPointers_),
205         numSkipPointers * sizeof(SkipValueType));
206     result_.forwardPointers.reset(
207         reinterpret_cast<unsigned char*>(forwardPointers_),
208         numForwardPointers * sizeof(SkipValueType));
209   }
210
211   void add(ValueType value) {
212     CHECK_GE(value, lastValue_);
213
214     const auto numLowerBits = result_.numLowerBits;
215     const ValueType upperBits = value >> numLowerBits;
216
217     // Upper sequence consists of upperBits 0-bits and (size_ + 1) 1-bits.
218     const size_t pos = upperBits + size_;
219     upper_[pos / 8] |= 1U << (pos % 8);
220     // Append numLowerBits bits to lower sequence.
221     if (numLowerBits != 0) {
222       const ValueType lowerBits = value & ((ValueType(1) << numLowerBits) - 1);
223       writeBits56(lower_, size_ * numLowerBits, numLowerBits, lowerBits);
224     }
225
226     /* static */ if (skipQuantum != 0) {
227       while ((skipPointersSize_ + 1) * skipQuantum <= upperBits) {
228         /* static */ if (kVersion > 0) {
229           // Since version 1, just the number of preceding 1-bits is stored.
230           skipPointers_[skipPointersSize_] = size_;
231         } else {
232           skipPointers_[skipPointersSize_] =
233             size_ + (skipPointersSize_ + 1) * skipQuantum;
234         }
235         ++skipPointersSize_;
236       }
237     }
238
239     /* static */ if (forwardQuantum != 0) {
240       if ((size_ + 1) % forwardQuantum == 0) {
241         const auto pos = size_ / forwardQuantum;
242         /* static */ if (kVersion > 0) {
243           // Since version 1, just the number of preceding 0-bits is stored.
244           forwardPointers_[pos] = upperBits;
245         } else {
246           forwardPointers_[pos] = upperBits + size_ + 1;
247         }
248       }
249     }
250
251     lastValue_ = value;
252     ++size_;
253   }
254
255   const EliasFanoCompressedList& finish() const {
256     CHECK_EQ(size_, result_.size);
257     return result_;
258   }
259
260  private:
261   // Writes value (with len up to 56 bits) to data starting at pos-th bit.
262   static void writeBits56(unsigned char* data, size_t pos,
263                           uint8_t len, uint64_t value) {
264     DCHECK_LE(uint32_t(len), 56);
265     DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
266     unsigned char* const ptr = data + (pos / 8);
267     uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
268     ptrv |= value << (pos % 8);
269     folly::storeUnaligned<uint64_t>(ptr, ptrv);
270   }
271
272   unsigned char* lower_ = nullptr;
273   unsigned char* upper_ = nullptr;
274   SkipValueType* skipPointers_ = nullptr;
275   SkipValueType* forwardPointers_ = nullptr;
276
277   ValueType lastValue_ = 0;
278   size_t size_ = 0;
279   size_t skipPointersSize_ = 0;
280
281   EliasFanoCompressedList result_;
282 };
283
284 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
285 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
286 // it for __builtin_popcountll intrinsic.
287 // But we provide an alternative way for the client code: it can switch to
288 // the appropriate version of EliasFanoReader<> in realtime (client should
289 // implement this switching logic itself) by specifying instruction set to
290 // use explicitly.
291 namespace instructions {
292
293 struct Default {
294   static bool supported(const folly::CpuId& cpuId = {}) {
295     return true;
296   }
297   static inline uint64_t popcount(uint64_t value) {
298     return __builtin_popcountll(value);
299   }
300   static inline int ctz(uint64_t value) {
301     DCHECK_GT(value, 0);
302     return __builtin_ctzll(value);
303   }
304   static inline uint64_t blsr(uint64_t value) {
305     return value & (value - 1);
306   }
307 };
308
309 struct Nehalem : public Default {
310   static bool supported(const folly::CpuId& cpuId = {}) {
311     return cpuId.popcnt();
312   }
313   static inline uint64_t popcount(uint64_t value) {
314     // POPCNT is supported starting with Intel Nehalem, AMD K10.
315     uint64_t result;
316     asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
317     return result;
318   }
319 };
320
321 struct Haswell : public Nehalem {
322   static bool supported(const folly::CpuId& cpuId = {}) {
323     return Nehalem::supported(cpuId) && cpuId.bmi1();
324   }
325   static inline uint64_t blsr(uint64_t value) {
326     // BMI1 is supported starting with Intel Haswell, AMD Piledriver.
327     // BLSR combines two instuctions into one and reduces register pressure.
328     uint64_t result;
329     asm ("blsrq %1, %0" : "=r" (result) : "r" (value));
330     return result;
331   }
332 };
333
334 }  // namespace instructions
335
336 namespace detail {
337
338 template <class Encoder, class Instructions>
339 class UpperBitsReader {
340   typedef typename Encoder::SkipValueType SkipValueType;
341  public:
342   typedef typename Encoder::ValueType ValueType;
343
344   explicit UpperBitsReader(const EliasFanoCompressedList& list)
345     : forwardPointers_(list.forwardPointers.data()),
346       skipPointers_(list.skipPointers.data()),
347       start_(list.upper.data()) {
348     reset();
349   }
350
351   void reset() {
352     block_ = start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0;
353     outer_ = 0;
354     inner_ = -1;
355     position_ = -1;
356     value_ = 0;
357   }
358
359   size_t position() const { return position_; }
360   ValueType value() const { return value_; }
361
362   ValueType next() {
363     // Skip to the first non-zero block.
364     while (block_ == 0) {
365       outer_ += sizeof(block_t);
366       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
367     }
368
369     ++position_;
370     inner_ = Instructions::ctz(block_);
371     block_ = Instructions::blsr(block_);
372
373     return setValue();
374   }
375
376   ValueType skip(size_t n) {
377     DCHECK_GT(n, 0);
378
379     position_ += n;  // n 1-bits will be read.
380
381     // Use forward pointer.
382     if (Encoder::forwardQuantum > 0 && n > Encoder::forwardQuantum) {
383       // Workaround to avoid 'division by zero' compile-time error.
384       constexpr size_t q = Encoder::forwardQuantum ?: 1;
385
386       const size_t steps = position_ / q;
387       const size_t dest =
388         folly::loadUnaligned<SkipValueType>(
389             forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
390
391       /* static */ if (Encoder::version > 0) {
392         reposition(dest + steps * q);
393       } else {
394         reposition(dest);
395       }
396       n = position_ + 1 - steps * q;  // n is > 0.
397       // correct inner_ will be set at the end.
398     }
399
400     size_t cnt;
401     // Find necessary block.
402     while ((cnt = Instructions::popcount(block_)) < n) {
403       n -= cnt;
404       outer_ += sizeof(block_t);
405       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
406     }
407
408     // NOTE: Trying to skip half-block here didn't show any
409     // performance improvements.
410
411     DCHECK_GT(n, 0);
412
413     // Kill n - 1 least significant 1-bits.
414     for (size_t i = 0; i < n - 1; ++i) {
415       block_ = Instructions::blsr(block_);
416     }
417
418     inner_ = Instructions::ctz(block_);
419     block_ = Instructions::blsr(block_);
420
421     return setValue();
422   }
423
424   // Skip to the first element that is >= v and located *after* the current
425   // one (so even if current value equals v, position will be increased by 1).
426   ValueType skipToNext(ValueType v) {
427     DCHECK_GE(v, value_);
428
429     // Use skip pointer.
430     if (Encoder::skipQuantum > 0 && v >= value_ + Encoder::skipQuantum) {
431       // Workaround to avoid 'division by zero' compile-time error.
432       constexpr size_t q = Encoder::skipQuantum ?: 1;
433
434       const size_t steps = v / q;
435       const size_t dest =
436         folly::loadUnaligned<SkipValueType>(
437             skipPointers_ + (steps - 1) * sizeof(SkipValueType));
438
439       /* static */ if (Encoder::version > 0) {
440         reposition(dest + q * steps);
441         position_ = dest - 1;
442       } else {
443         reposition(dest);
444         position_ = dest - q * steps - 1;
445       }
446       // Correct inner_ and value_ will be set during the next()
447       // call at the end.
448
449       // NOTE: Corresponding block of lower bits sequence may be
450       // prefetched here (via __builtin_prefetch), but experiments
451       // didn't show any significant improvements.
452     }
453
454     // Skip by blocks.
455     size_t cnt;
456     size_t skip = v - (8 * outer_ - position_ - 1);
457
458     constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
459     while ((cnt = Instructions::popcount(~block_)) < skip) {
460       skip -= cnt;
461       position_ += kBitsPerBlock - cnt;
462       outer_ += sizeof(block_t);
463       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
464     }
465
466     // Try to skip half-block.
467     constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
468     constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
469     if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
470       position_ += kBitsPerHalfBlock - cnt;
471       block_ &= ~halfBlockMask;
472     }
473
474     // Just skip until we see expected value.
475     while (next() < v) { }
476     return value_;
477   }
478
479   ValueType jump(size_t n) {
480     if (Encoder::forwardQuantum == 0 || n <= Encoder::forwardQuantum) {
481       reset();
482     } else {
483       position_ = -1;  // Avoid reading the head, skip() will reposition.
484     }
485     return skip(n);
486   }
487
488   ValueType jumpToNext(ValueType v) {
489     if (Encoder::skipQuantum == 0 || v < Encoder::skipQuantum) {
490       reset();
491     } else {
492       value_ = 0;  // Avoid reading the head, skipToNext() will reposition.
493     }
494     return skipToNext(v);
495   }
496
497  private:
498   ValueType setValue() {
499     value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
500     return value_;
501   }
502
503   void reposition(size_t dest) {
504     outer_ = dest / 8;
505     block_ = folly::loadUnaligned<block_t>(start_ + outer_);
506     block_ &= ~((block_t(1) << (dest % 8)) - 1);
507   }
508
509   typedef unsigned long long block_t;
510   const unsigned char* const forwardPointers_;
511   const unsigned char* const skipPointers_;
512   const unsigned char* const start_;
513   block_t block_;
514   size_t outer_;  // Outer offset: number of consumed bytes in upper.
515   size_t inner_;  // Inner offset: (bit) position in current block.
516   size_t position_;  // Index of current value (= #reads - 1).
517   ValueType value_;
518 };
519
520 }  // namespace detail
521
522 template <class Encoder,
523           class Instructions = instructions::Default>
524 class EliasFanoReader : private boost::noncopyable {
525  public:
526   typedef Encoder EncoderType;
527   typedef typename Encoder::ValueType ValueType;
528
529   explicit EliasFanoReader(const EliasFanoCompressedList& list)
530     : list_(list),
531       lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
532       upper_(list_) {
533     DCHECK(Instructions::supported());
534     // To avoid extra branching during skipTo() while reading
535     // upper sequence we need to know the last element.
536     if (UNLIKELY(list_.size == 0)) {
537       lastValue_ = 0;
538       return;
539     }
540     ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
541     auto it = list_.upper.end() - 1;
542     DCHECK_NE(*it, 0);
543     lastUpperValue -= 8 - folly::findLastSet(*it);
544     lastValue_ = readLowerPart(list_.size - 1) |
545                  (lastUpperValue << list_.numLowerBits);
546   }
547
548   void reset() {
549     upper_.reset();
550     progress_ = 0;
551     value_ = 0;
552   }
553
554   bool next() {
555     if (UNLIKELY(progress_ == list_.size)) {
556       value_ = std::numeric_limits<ValueType>::max();
557       return false;
558     }
559     value_ = readLowerPart(progress_) |
560              (upper_.next() << list_.numLowerBits);
561     ++progress_;
562     return true;
563   }
564
565   bool skip(size_t n) {
566     CHECK_GT(n, 0);
567
568     progress_ += n;
569     if (LIKELY(progress_ <= list_.size)) {
570       value_ = readLowerPart(progress_ - 1) |
571                (upper_.skip(n) << list_.numLowerBits);
572       return true;
573     }
574
575     progress_ = list_.size;
576     value_ = std::numeric_limits<ValueType>::max();
577     return false;
578   }
579
580   bool skipTo(ValueType value) {
581     DCHECK_GE(value, value_);
582     if (value <= value_) {
583       return true;
584     } else if (value > lastValue_) {
585       progress_ = list_.size;
586       value_ = std::numeric_limits<ValueType>::max();
587       return false;
588     }
589
590     upper_.skipToNext(value >> list_.numLowerBits);
591     iterateTo(value);
592     return true;
593   }
594
595   bool jump(size_t n) {
596     if (LIKELY(n - 1 < list_.size)) {  // n > 0 && n <= list_.size
597       progress_ = n;
598       value_ = readLowerPart(n - 1) | (upper_.jump(n) << list_.numLowerBits);
599       return true;
600     } else if (n == 0) {
601       reset();
602       return true;
603     }
604     progress_ = list_.size;
605     value_ = std::numeric_limits<ValueType>::max();
606     return false;
607   }
608
609   ValueType jumpTo(ValueType value) {
610     if (value <= 0) {
611       reset();
612       return true;
613     } else if (value > lastValue_) {
614       progress_ = list_.size;
615       value_ = std::numeric_limits<ValueType>::max();
616       return false;
617     }
618
619     upper_.jumpToNext(value >> list_.numLowerBits);
620     iterateTo(value);
621     return true;
622   }
623
624   size_t size() const { return list_.size; }
625
626   size_t position() const { return progress_ - 1; }
627   ValueType value() const { return value_; }
628
629  private:
630   ValueType readLowerPart(size_t i) const {
631     DCHECK_LT(i, list_.size);
632     const size_t pos = i * list_.numLowerBits;
633     const unsigned char* ptr = list_.lower.data() + (pos / 8);
634     const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
635     return lowerMask_ & (ptrv >> (pos % 8));
636   }
637
638   void iterateTo(ValueType value) {
639     progress_ = upper_.position();
640     value_ = readLowerPart(progress_) | (upper_.value() << list_.numLowerBits);
641     ++progress_;
642     while (value_ < value) {
643       value_ = readLowerPart(progress_) | (upper_.next() << list_.numLowerBits);
644       ++progress_;
645     }
646   }
647
648   const EliasFanoCompressedList list_;
649   const ValueType lowerMask_;
650   detail::UpperBitsReader<Encoder, Instructions> upper_;
651   size_t progress_ = 0;
652   ValueType value_ = 0;
653   ValueType lastValue_;
654 };
655
656 }}  // namespaces
657
658 #endif  // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H