IR: Remove implicit iterator conversions from lib/IR, NFC
[oota-llvm.git] / include / llvm / Support / OnDiskHashTable.h
1 //===--- OnDiskHashTable.h - On-Disk Hash Table Implementation --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Defines facilities for reading and writing on-disk hash tables.
12 ///
13 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_ONDISKHASHTABLE_H
15 #define LLVM_SUPPORT_ONDISKHASHTABLE_H
16
17 #include "llvm/Support/AlignOf.h"
18 #include "llvm/Support/Allocator.h"
19 #include "llvm/Support/DataTypes.h"
20 #include "llvm/Support/EndianStream.h"
21 #include "llvm/Support/Host.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <cassert>
25 #include <cstdlib>
26
27 namespace llvm {
28
29 /// \brief Generates an on disk hash table.
30 ///
31 /// This needs an \c Info that handles storing values into the hash table's
32 /// payload and computes the hash for a given key. This should provide the
33 /// following interface:
34 ///
35 /// \code
36 /// class ExampleInfo {
37 /// public:
38 ///   typedef ExampleKey key_type;   // Must be copy constructible
39 ///   typedef ExampleKey &key_type_ref;
40 ///   typedef ExampleData data_type; // Must be copy constructible
41 ///   typedef ExampleData &data_type_ref;
42 ///   typedef uint32_t hash_value_type; // The type the hash function returns.
43 ///   typedef uint32_t offset_type; // The type for offsets into the table.
44 ///
45 ///   /// Calculate the hash for Key
46 ///   static hash_value_type ComputeHash(key_type_ref Key);
47 ///   /// Return the lengths, in bytes, of the given Key/Data pair.
48 ///   static std::pair<offset_type, offset_type>
49 ///   EmitKeyDataLength(raw_ostream &Out, key_type_ref Key, data_type_ref Data);
50 ///   /// Write Key to Out.  KeyLen is the length from EmitKeyDataLength.
51 ///   static void EmitKey(raw_ostream &Out, key_type_ref Key,
52 ///                       offset_type KeyLen);
53 ///   /// Write Data to Out.  DataLen is the length from EmitKeyDataLength.
54 ///   static void EmitData(raw_ostream &Out, key_type_ref Key,
55 ///                        data_type_ref Data, offset_type DataLen);
56 ///   /// Determine if two keys are equal. Optional, only needed by contains.
57 ///   static bool EqualKey(key_type_ref Key1, key_type_ref Key2);
58 /// };
59 /// \endcode
60 template <typename Info> class OnDiskChainedHashTableGenerator {
61   /// \brief A single item in the hash table.
62   class Item {
63   public:
64     typename Info::key_type Key;
65     typename Info::data_type Data;
66     Item *Next;
67     const typename Info::hash_value_type Hash;
68
69     Item(typename Info::key_type_ref Key, typename Info::data_type_ref Data,
70          Info &InfoObj)
71         : Key(Key), Data(Data), Next(nullptr), Hash(InfoObj.ComputeHash(Key)) {}
72   };
73
74   typedef typename Info::offset_type offset_type;
75   offset_type NumBuckets;
76   offset_type NumEntries;
77   llvm::SpecificBumpPtrAllocator<Item> BA;
78
79   /// \brief A linked list of values in a particular hash bucket.
80   struct Bucket {
81     offset_type Off;
82     unsigned Length;
83     Item *Head;
84   };
85
86   Bucket *Buckets;
87
88 private:
89   /// \brief Insert an item into the appropriate hash bucket.
90   void insert(Bucket *Buckets, size_t Size, Item *E) {
91     Bucket &B = Buckets[E->Hash & (Size - 1)];
92     E->Next = B.Head;
93     ++B.Length;
94     B.Head = E;
95   }
96
97   /// \brief Resize the hash table, moving the old entries into the new buckets.
98   void resize(size_t NewSize) {
99     Bucket *NewBuckets = (Bucket *)std::calloc(NewSize, sizeof(Bucket));
100     // Populate NewBuckets with the old entries.
101     for (size_t I = 0; I < NumBuckets; ++I)
102       for (Item *E = Buckets[I].Head; E;) {
103         Item *N = E->Next;
104         E->Next = nullptr;
105         insert(NewBuckets, NewSize, E);
106         E = N;
107       }
108
109     free(Buckets);
110     NumBuckets = NewSize;
111     Buckets = NewBuckets;
112   }
113
114 public:
115   /// \brief Insert an entry into the table.
116   void insert(typename Info::key_type_ref Key,
117               typename Info::data_type_ref Data) {
118     Info InfoObj;
119     insert(Key, Data, InfoObj);
120   }
121
122   /// \brief Insert an entry into the table.
123   ///
124   /// Uses the provided Info instead of a stack allocated one.
125   void insert(typename Info::key_type_ref Key,
126               typename Info::data_type_ref Data, Info &InfoObj) {
127     ++NumEntries;
128     if (4 * NumEntries >= 3 * NumBuckets)
129       resize(NumBuckets * 2);
130     insert(Buckets, NumBuckets, new (BA.Allocate()) Item(Key, Data, InfoObj));
131   }
132
133   /// \brief Determine whether an entry has been inserted.
134   bool contains(typename Info::key_type_ref Key, Info &InfoObj) {
135     unsigned Hash = InfoObj.ComputeHash(Key);
136     for (Item *I = Buckets[Hash & (NumBuckets - 1)].Head; I; I = I->Next)
137       if (I->Hash == Hash && InfoObj.EqualKey(I->Key, Key))
138         return true;
139     return false;
140   }
141
142   /// \brief Emit the table to Out, which must not be at offset 0.
143   offset_type Emit(raw_ostream &Out) {
144     Info InfoObj;
145     return Emit(Out, InfoObj);
146   }
147
148   /// \brief Emit the table to Out, which must not be at offset 0.
149   ///
150   /// Uses the provided Info instead of a stack allocated one.
151   offset_type Emit(raw_ostream &Out, Info &InfoObj) {
152     using namespace llvm::support;
153     endian::Writer<little> LE(Out);
154
155     // Emit the payload of the table.
156     for (offset_type I = 0; I < NumBuckets; ++I) {
157       Bucket &B = Buckets[I];
158       if (!B.Head)
159         continue;
160
161       // Store the offset for the data of this bucket.
162       B.Off = Out.tell();
163       assert(B.Off && "Cannot write a bucket at offset 0. Please add padding.");
164
165       // Write out the number of items in the bucket.
166       LE.write<uint16_t>(B.Length);
167       assert(B.Length != 0 && "Bucket has a head but zero length?");
168
169       // Write out the entries in the bucket.
170       for (Item *I = B.Head; I; I = I->Next) {
171         LE.write<typename Info::hash_value_type>(I->Hash);
172         const std::pair<offset_type, offset_type> &Len =
173             InfoObj.EmitKeyDataLength(Out, I->Key, I->Data);
174         InfoObj.EmitKey(Out, I->Key, Len.first);
175         InfoObj.EmitData(Out, I->Key, I->Data, Len.second);
176       }
177     }
178
179     // Pad with zeros so that we can start the hashtable at an aligned address.
180     offset_type TableOff = Out.tell();
181     uint64_t N = llvm::OffsetToAlignment(TableOff, alignOf<offset_type>());
182     TableOff += N;
183     while (N--)
184       LE.write<uint8_t>(0);
185
186     // Emit the hashtable itself.
187     LE.write<offset_type>(NumBuckets);
188     LE.write<offset_type>(NumEntries);
189     for (offset_type I = 0; I < NumBuckets; ++I)
190       LE.write<offset_type>(Buckets[I].Off);
191
192     return TableOff;
193   }
194
195   OnDiskChainedHashTableGenerator() {
196     NumEntries = 0;
197     NumBuckets = 64;
198     // Note that we do not need to run the constructors of the individual
199     // Bucket objects since 'calloc' returns bytes that are all 0.
200     Buckets = (Bucket *)std::calloc(NumBuckets, sizeof(Bucket));
201   }
202
203   ~OnDiskChainedHashTableGenerator() { std::free(Buckets); }
204 };
205
206 /// \brief Provides lookup on an on disk hash table.
207 ///
208 /// This needs an \c Info that handles reading values from the hash table's
209 /// payload and computes the hash for a given key. This should provide the
210 /// following interface:
211 ///
212 /// \code
213 /// class ExampleLookupInfo {
214 /// public:
215 ///   typedef ExampleData data_type;
216 ///   typedef ExampleInternalKey internal_key_type; // The stored key type.
217 ///   typedef ExampleKey external_key_type; // The type to pass to find().
218 ///   typedef uint32_t hash_value_type; // The type the hash function returns.
219 ///   typedef uint32_t offset_type; // The type for offsets into the table.
220 ///
221 ///   /// Compare two keys for equality.
222 ///   static bool EqualKey(internal_key_type &Key1, internal_key_type &Key2);
223 ///   /// Calculate the hash for the given key.
224 ///   static hash_value_type ComputeHash(internal_key_type &IKey);
225 ///   /// Translate from the semantic type of a key in the hash table to the
226 ///   /// type that is actually stored and used for hashing and comparisons.
227 ///   /// The internal and external types are often the same, in which case this
228 ///   /// can simply return the passed in value.
229 ///   static const internal_key_type &GetInternalKey(external_key_type &EKey);
230 ///   /// Read the key and data length from Buffer, leaving it pointing at the
231 ///   /// following byte.
232 ///   static std::pair<offset_type, offset_type>
233 ///   ReadKeyDataLength(const unsigned char *&Buffer);
234 ///   /// Read the key from Buffer, given the KeyLen as reported from
235 ///   /// ReadKeyDataLength.
236 ///   const internal_key_type &ReadKey(const unsigned char *Buffer,
237 ///                                    offset_type KeyLen);
238 ///   /// Read the data for Key from Buffer, given the DataLen as reported from
239 ///   /// ReadKeyDataLength.
240 ///   data_type ReadData(StringRef Key, const unsigned char *Buffer,
241 ///                      offset_type DataLen);
242 /// };
243 /// \endcode
244 template <typename Info> class OnDiskChainedHashTable {
245   const typename Info::offset_type NumBuckets;
246   const typename Info::offset_type NumEntries;
247   const unsigned char *const Buckets;
248   const unsigned char *const Base;
249   Info InfoObj;
250
251 public:
252   typedef typename Info::internal_key_type internal_key_type;
253   typedef typename Info::external_key_type external_key_type;
254   typedef typename Info::data_type         data_type;
255   typedef typename Info::hash_value_type   hash_value_type;
256   typedef typename Info::offset_type       offset_type;
257
258   OnDiskChainedHashTable(offset_type NumBuckets, offset_type NumEntries,
259                          const unsigned char *Buckets,
260                          const unsigned char *Base,
261                          const Info &InfoObj = Info())
262       : NumBuckets(NumBuckets), NumEntries(NumEntries), Buckets(Buckets),
263         Base(Base), InfoObj(InfoObj) {
264     assert((reinterpret_cast<uintptr_t>(Buckets) & 0x3) == 0 &&
265            "'buckets' must have a 4-byte alignment");
266   }
267
268   /// Read the number of buckets and the number of entries from a hash table
269   /// produced by OnDiskHashTableGenerator::Emit, and advance the Buckets
270   /// pointer past them.
271   static std::pair<offset_type, offset_type>
272   readNumBucketsAndEntries(const unsigned char *&Buckets) {
273     assert((reinterpret_cast<uintptr_t>(Buckets) & 0x3) == 0 &&
274            "buckets should be 4-byte aligned.");
275     using namespace llvm::support;
276     offset_type NumBuckets =
277         endian::readNext<offset_type, little, aligned>(Buckets);
278     offset_type NumEntries =
279         endian::readNext<offset_type, little, aligned>(Buckets);
280     return std::make_pair(NumBuckets, NumEntries);
281   }
282
283   offset_type getNumBuckets() const { return NumBuckets; }
284   offset_type getNumEntries() const { return NumEntries; }
285   const unsigned char *getBase() const { return Base; }
286   const unsigned char *getBuckets() const { return Buckets; }
287
288   bool isEmpty() const { return NumEntries == 0; }
289
290   class iterator {
291     internal_key_type Key;
292     const unsigned char *const Data;
293     const offset_type Len;
294     Info *InfoObj;
295
296   public:
297     iterator() : Data(nullptr), Len(0) {}
298     iterator(const internal_key_type K, const unsigned char *D, offset_type L,
299              Info *InfoObj)
300         : Key(K), Data(D), Len(L), InfoObj(InfoObj) {}
301
302     data_type operator*() const { return InfoObj->ReadData(Key, Data, Len); }
303
304     const unsigned char *getDataPtr() const { return Data; }
305     offset_type getDataLen() const { return Len; }
306
307     bool operator==(const iterator &X) const { return X.Data == Data; }
308     bool operator!=(const iterator &X) const { return X.Data != Data; }
309   };
310
311   /// \brief Look up the stored data for a particular key.
312   iterator find(const external_key_type &EKey, Info *InfoPtr = nullptr) {
313     const internal_key_type &IKey = InfoObj.GetInternalKey(EKey);
314     hash_value_type KeyHash = InfoObj.ComputeHash(IKey);
315     return find_hashed(IKey, KeyHash, InfoPtr);
316   }
317
318   /// \brief Look up the stored data for a particular key with a known hash.
319   iterator find_hashed(const internal_key_type &IKey, hash_value_type KeyHash,
320                        Info *InfoPtr = nullptr) {
321     using namespace llvm::support;
322
323     if (!InfoPtr)
324       InfoPtr = &InfoObj;
325
326     // Each bucket is just an offset into the hash table file.
327     offset_type Idx = KeyHash & (NumBuckets - 1);
328     const unsigned char *Bucket = Buckets + sizeof(offset_type) * Idx;
329
330     offset_type Offset = endian::readNext<offset_type, little, aligned>(Bucket);
331     if (Offset == 0)
332       return iterator(); // Empty bucket.
333     const unsigned char *Items = Base + Offset;
334
335     // 'Items' starts with a 16-bit unsigned integer representing the
336     // number of items in this bucket.
337     unsigned Len = endian::readNext<uint16_t, little, unaligned>(Items);
338
339     for (unsigned i = 0; i < Len; ++i) {
340       // Read the hash.
341       hash_value_type ItemHash =
342           endian::readNext<hash_value_type, little, unaligned>(Items);
343
344       // Determine the length of the key and the data.
345       const std::pair<offset_type, offset_type> &L =
346           Info::ReadKeyDataLength(Items);
347       offset_type ItemLen = L.first + L.second;
348
349       // Compare the hashes.  If they are not the same, skip the entry entirely.
350       if (ItemHash != KeyHash) {
351         Items += ItemLen;
352         continue;
353       }
354
355       // Read the key.
356       const internal_key_type &X =
357           InfoPtr->ReadKey((const unsigned char *const)Items, L.first);
358
359       // If the key doesn't match just skip reading the value.
360       if (!InfoPtr->EqualKey(X, IKey)) {
361         Items += ItemLen;
362         continue;
363       }
364
365       // The key matches!
366       return iterator(X, Items + L.first, L.second, InfoPtr);
367     }
368
369     return iterator();
370   }
371
372   iterator end() const { return iterator(); }
373
374   Info &getInfoObj() { return InfoObj; }
375
376   /// \brief Create the hash table.
377   ///
378   /// \param Buckets is the beginning of the hash table itself, which follows
379   /// the payload of entire structure. This is the value returned by
380   /// OnDiskHashTableGenerator::Emit.
381   ///
382   /// \param Base is the point from which all offsets into the structure are
383   /// based. This is offset 0 in the stream that was used when Emitting the
384   /// table.
385   static OnDiskChainedHashTable *Create(const unsigned char *Buckets,
386                                         const unsigned char *const Base,
387                                         const Info &InfoObj = Info()) {
388     assert(Buckets > Base);
389     auto NumBucketsAndEntries = readNumBucketsAndEntries(Buckets);
390     return new OnDiskChainedHashTable<Info>(NumBucketsAndEntries.first,
391                                             NumBucketsAndEntries.second,
392                                             Buckets, Base, InfoObj);
393   }
394 };
395
396 /// \brief Provides lookup and iteration over an on disk hash table.
397 ///
398 /// \copydetails llvm::OnDiskChainedHashTable
399 template <typename Info>
400 class OnDiskIterableChainedHashTable : public OnDiskChainedHashTable<Info> {
401   const unsigned char *Payload;
402
403 public:
404   typedef OnDiskChainedHashTable<Info>          base_type;
405   typedef typename base_type::internal_key_type internal_key_type;
406   typedef typename base_type::external_key_type external_key_type;
407   typedef typename base_type::data_type         data_type;
408   typedef typename base_type::hash_value_type   hash_value_type;
409   typedef typename base_type::offset_type       offset_type;
410
411 private:
412   /// \brief Iterates over all of the keys in the table.
413   class iterator_base {
414     const unsigned char *Ptr;
415     offset_type NumItemsInBucketLeft;
416     offset_type NumEntriesLeft;
417
418   public:
419     typedef external_key_type value_type;
420
421     iterator_base(const unsigned char *const Ptr, offset_type NumEntries)
422         : Ptr(Ptr), NumItemsInBucketLeft(0), NumEntriesLeft(NumEntries) {}
423     iterator_base()
424         : Ptr(nullptr), NumItemsInBucketLeft(0), NumEntriesLeft(0) {}
425
426     friend bool operator==(const iterator_base &X, const iterator_base &Y) {
427       return X.NumEntriesLeft == Y.NumEntriesLeft;
428     }
429     friend bool operator!=(const iterator_base &X, const iterator_base &Y) {
430       return X.NumEntriesLeft != Y.NumEntriesLeft;
431     }
432
433     /// Move to the next item.
434     void advance() {
435       using namespace llvm::support;
436       if (!NumItemsInBucketLeft) {
437         // 'Items' starts with a 16-bit unsigned integer representing the
438         // number of items in this bucket.
439         NumItemsInBucketLeft =
440             endian::readNext<uint16_t, little, unaligned>(Ptr);
441       }
442       Ptr += sizeof(hash_value_type); // Skip the hash.
443       // Determine the length of the key and the data.
444       const std::pair<offset_type, offset_type> &L =
445           Info::ReadKeyDataLength(Ptr);
446       Ptr += L.first + L.second;
447       assert(NumItemsInBucketLeft);
448       --NumItemsInBucketLeft;
449       assert(NumEntriesLeft);
450       --NumEntriesLeft;
451     }
452
453     /// Get the start of the item as written by the trait (after the hash and
454     /// immediately before the key and value length).
455     const unsigned char *getItem() const {
456       return Ptr + (NumItemsInBucketLeft ? 0 : 2) + sizeof(hash_value_type);
457     }
458   };
459
460 public:
461   OnDiskIterableChainedHashTable(offset_type NumBuckets, offset_type NumEntries,
462                                  const unsigned char *Buckets,
463                                  const unsigned char *Payload,
464                                  const unsigned char *Base,
465                                  const Info &InfoObj = Info())
466       : base_type(NumBuckets, NumEntries, Buckets, Base, InfoObj),
467         Payload(Payload) {}
468
469   /// \brief Iterates over all of the keys in the table.
470   class key_iterator : public iterator_base {
471     Info *InfoObj;
472
473   public:
474     typedef external_key_type value_type;
475
476     key_iterator(const unsigned char *const Ptr, offset_type NumEntries,
477                  Info *InfoObj)
478         : iterator_base(Ptr, NumEntries), InfoObj(InfoObj) {}
479     key_iterator() : iterator_base(), InfoObj() {}
480
481     key_iterator &operator++() {
482       this->advance();
483       return *this;
484     }
485     key_iterator operator++(int) { // Postincrement
486       key_iterator tmp = *this;
487       ++*this;
488       return tmp;
489     }
490
491     internal_key_type getInternalKey() const {
492       auto *LocalPtr = this->getItem();
493
494       // Determine the length of the key and the data.
495       auto L = Info::ReadKeyDataLength(LocalPtr);
496
497       // Read the key.
498       return InfoObj->ReadKey(LocalPtr, L.first);
499     }
500
501     value_type operator*() const {
502       return InfoObj->GetExternalKey(getInternalKey());
503     }
504   };
505
506   key_iterator key_begin() {
507     return key_iterator(Payload, this->getNumEntries(), &this->getInfoObj());
508   }
509   key_iterator key_end() { return key_iterator(); }
510
511   iterator_range<key_iterator> keys() {
512     return make_range(key_begin(), key_end());
513   }
514
515   /// \brief Iterates over all the entries in the table, returning the data.
516   class data_iterator : public iterator_base {
517     Info *InfoObj;
518
519   public:
520     typedef data_type value_type;
521
522     data_iterator(const unsigned char *const Ptr, offset_type NumEntries,
523                   Info *InfoObj)
524         : iterator_base(Ptr, NumEntries), InfoObj(InfoObj) {}
525     data_iterator() : iterator_base(), InfoObj() {}
526
527     data_iterator &operator++() { // Preincrement
528       this->advance();
529       return *this;
530     }
531     data_iterator operator++(int) { // Postincrement
532       data_iterator tmp = *this;
533       ++*this;
534       return tmp;
535     }
536
537     value_type operator*() const {
538       auto *LocalPtr = this->getItem();
539
540       // Determine the length of the key and the data.
541       auto L = Info::ReadKeyDataLength(LocalPtr);
542
543       // Read the key.
544       const internal_key_type &Key = InfoObj->ReadKey(LocalPtr, L.first);
545       return InfoObj->ReadData(Key, LocalPtr + L.first, L.second);
546     }
547   };
548
549   data_iterator data_begin() {
550     return data_iterator(Payload, this->getNumEntries(), &this->getInfoObj());
551   }
552   data_iterator data_end() { return data_iterator(); }
553
554   iterator_range<data_iterator> data() {
555     return make_range(data_begin(), data_end());
556   }
557
558   /// \brief Create the hash table.
559   ///
560   /// \param Buckets is the beginning of the hash table itself, which follows
561   /// the payload of entire structure. This is the value returned by
562   /// OnDiskHashTableGenerator::Emit.
563   ///
564   /// \param Payload is the beginning of the data contained in the table.  This
565   /// is Base plus any padding or header data that was stored, ie, the offset
566   /// that the stream was at when calling Emit.
567   ///
568   /// \param Base is the point from which all offsets into the structure are
569   /// based. This is offset 0 in the stream that was used when Emitting the
570   /// table.
571   static OnDiskIterableChainedHashTable *
572   Create(const unsigned char *Buckets, const unsigned char *const Payload,
573          const unsigned char *const Base, const Info &InfoObj = Info()) {
574     assert(Buckets > Base);
575     auto NumBucketsAndEntries =
576         OnDiskIterableChainedHashTable<Info>::readNumBucketsAndEntries(Buckets);
577     return new OnDiskIterableChainedHashTable<Info>(
578         NumBucketsAndEntries.first, NumBucketsAndEntries.second,
579         Buckets, Payload, Base, InfoObj);
580   }
581 };
582
583 } // end namespace llvm
584
585 #endif