MultiOnDiskHashTable.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. //===- MultiOnDiskHashTable.h - Merged set of hash tables -------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides a hash table data structure suitable for incremental and
  10. // distributed storage across a set of files.
  11. //
  12. // Multiple hash tables from different files are implicitly merged to improve
  13. // performance, and on reload the merged table will override those from other
  14. // files.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_LIB_SERIALIZATION_MULTIONDISKHASHTABLE_H
  18. #define LLVM_CLANG_LIB_SERIALIZATION_MULTIONDISKHASHTABLE_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/ADT/PointerUnion.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/TinyPtrVector.h"
  25. #include "llvm/ADT/iterator_range.h"
  26. #include "llvm/Support/Endian.h"
  27. #include "llvm/Support/EndianStream.h"
  28. #include "llvm/Support/OnDiskHashTable.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <algorithm>
  31. #include <cstdint>
  32. #include <vector>
  33. namespace clang {
  34. namespace serialization {
  35. /// A collection of on-disk hash tables, merged when relevant for performance.
  36. template<typename Info> class MultiOnDiskHashTable {
  37. public:
  38. /// A handle to a file, used when overriding tables.
  39. using file_type = typename Info::file_type;
  40. /// A pointer to an on-disk representation of the hash table.
  41. using storage_type = const unsigned char *;
  42. using external_key_type = typename Info::external_key_type;
  43. using internal_key_type = typename Info::internal_key_type;
  44. using data_type = typename Info::data_type;
  45. using data_type_builder = typename Info::data_type_builder;
  46. using hash_value_type = unsigned;
  47. private:
  48. /// The generator is permitted to read our merged table.
  49. template<typename ReaderInfo, typename WriterInfo>
  50. friend class MultiOnDiskHashTableGenerator;
  51. /// A hash table stored on disk.
  52. struct OnDiskTable {
  53. using HashTable = llvm::OnDiskIterableChainedHashTable<Info>;
  54. file_type File;
  55. HashTable Table;
  56. OnDiskTable(file_type File, unsigned NumBuckets, unsigned NumEntries,
  57. storage_type Buckets, storage_type Payload, storage_type Base,
  58. const Info &InfoObj)
  59. : File(File),
  60. Table(NumBuckets, NumEntries, Buckets, Payload, Base, InfoObj) {}
  61. };
  62. struct MergedTable {
  63. std::vector<file_type> Files;
  64. llvm::DenseMap<internal_key_type, data_type> Data;
  65. };
  66. using Table = llvm::PointerUnion<OnDiskTable *, MergedTable *>;
  67. using TableVector = llvm::TinyPtrVector<void *>;
  68. /// The current set of on-disk and merged tables.
  69. /// We manually store the opaque value of the Table because TinyPtrVector
  70. /// can't cope with holding a PointerUnion directly.
  71. /// There can be at most one MergedTable in this vector, and if present,
  72. /// it is the first table.
  73. TableVector Tables;
  74. /// Files corresponding to overridden tables that we've not yet
  75. /// discarded.
  76. llvm::TinyPtrVector<file_type> PendingOverrides;
  77. struct AsOnDiskTable {
  78. using result_type = OnDiskTable *;
  79. result_type operator()(void *P) const {
  80. return Table::getFromOpaqueValue(P).template get<OnDiskTable *>();
  81. }
  82. };
  83. using table_iterator =
  84. llvm::mapped_iterator<TableVector::iterator, AsOnDiskTable>;
  85. using table_range = llvm::iterator_range<table_iterator>;
  86. /// The current set of on-disk tables.
  87. table_range tables() {
  88. auto Begin = Tables.begin(), End = Tables.end();
  89. if (getMergedTable())
  90. ++Begin;
  91. return llvm::make_range(llvm::map_iterator(Begin, AsOnDiskTable()),
  92. llvm::map_iterator(End, AsOnDiskTable()));
  93. }
  94. MergedTable *getMergedTable() const {
  95. // If we already have a merged table, it's the first one.
  96. return Tables.empty() ? nullptr : Table::getFromOpaqueValue(*Tables.begin())
  97. .template dyn_cast<MergedTable*>();
  98. }
  99. /// Delete all our current on-disk tables.
  100. void clear() {
  101. for (auto *T : tables())
  102. delete T;
  103. if (auto *M = getMergedTable())
  104. delete M;
  105. Tables.clear();
  106. }
  107. void removeOverriddenTables() {
  108. llvm::DenseSet<file_type> Files;
  109. Files.insert(PendingOverrides.begin(), PendingOverrides.end());
  110. // Explicitly capture Files to work around an MSVC 2015 rejects-valid bug.
  111. auto ShouldRemove = [&Files](void *T) -> bool {
  112. auto *ODT = Table::getFromOpaqueValue(T).template get<OnDiskTable *>();
  113. bool Remove = Files.count(ODT->File);
  114. if (Remove)
  115. delete ODT;
  116. return Remove;
  117. };
  118. Tables.erase(std::remove_if(tables().begin().getCurrent(), Tables.end(),
  119. ShouldRemove),
  120. Tables.end());
  121. PendingOverrides.clear();
  122. }
  123. void condense() {
  124. MergedTable *Merged = getMergedTable();
  125. if (!Merged)
  126. Merged = new MergedTable;
  127. // Read in all the tables and merge them together.
  128. // FIXME: Be smarter about which tables we merge.
  129. for (auto *ODT : tables()) {
  130. auto &HT = ODT->Table;
  131. Info &InfoObj = HT.getInfoObj();
  132. for (auto I = HT.data_begin(), E = HT.data_end(); I != E; ++I) {
  133. auto *LocalPtr = I.getItem();
  134. // FIXME: Don't rely on the OnDiskHashTable format here.
  135. auto L = InfoObj.ReadKeyDataLength(LocalPtr);
  136. const internal_key_type &Key = InfoObj.ReadKey(LocalPtr, L.first);
  137. data_type_builder ValueBuilder(Merged->Data[Key]);
  138. InfoObj.ReadDataInto(Key, LocalPtr + L.first, L.second,
  139. ValueBuilder);
  140. }
  141. Merged->Files.push_back(ODT->File);
  142. delete ODT;
  143. }
  144. Tables.clear();
  145. Tables.push_back(Table(Merged).getOpaqueValue());
  146. }
  147. public:
  148. MultiOnDiskHashTable() = default;
  149. MultiOnDiskHashTable(MultiOnDiskHashTable &&O)
  150. : Tables(std::move(O.Tables)),
  151. PendingOverrides(std::move(O.PendingOverrides)) {
  152. O.Tables.clear();
  153. }
  154. MultiOnDiskHashTable &operator=(MultiOnDiskHashTable &&O) {
  155. if (&O == this)
  156. return *this;
  157. clear();
  158. Tables = std::move(O.Tables);
  159. O.Tables.clear();
  160. PendingOverrides = std::move(O.PendingOverrides);
  161. return *this;
  162. }
  163. ~MultiOnDiskHashTable() { clear(); }
  164. /// Add the table \p Data loaded from file \p File.
  165. void add(file_type File, storage_type Data, Info InfoObj = Info()) {
  166. using namespace llvm::support;
  167. storage_type Ptr = Data;
  168. uint32_t BucketOffset = endian::readNext<uint32_t, little, unaligned>(Ptr);
  169. // Read the list of overridden files.
  170. uint32_t NumFiles = endian::readNext<uint32_t, little, unaligned>(Ptr);
  171. // FIXME: Add a reserve() to TinyPtrVector so that we don't need to make
  172. // an additional copy.
  173. llvm::SmallVector<file_type, 16> OverriddenFiles;
  174. OverriddenFiles.reserve(NumFiles);
  175. for (/**/; NumFiles != 0; --NumFiles)
  176. OverriddenFiles.push_back(InfoObj.ReadFileRef(Ptr));
  177. PendingOverrides.insert(PendingOverrides.end(), OverriddenFiles.begin(),
  178. OverriddenFiles.end());
  179. // Read the OnDiskChainedHashTable header.
  180. storage_type Buckets = Data + BucketOffset;
  181. auto NumBucketsAndEntries =
  182. OnDiskTable::HashTable::readNumBucketsAndEntries(Buckets);
  183. // Register the table.
  184. Table NewTable = new OnDiskTable(File, NumBucketsAndEntries.first,
  185. NumBucketsAndEntries.second,
  186. Buckets, Ptr, Data, std::move(InfoObj));
  187. Tables.push_back(NewTable.getOpaqueValue());
  188. }
  189. /// Find and read the lookup results for \p EKey.
  190. data_type find(const external_key_type &EKey) {
  191. data_type Result;
  192. if (!PendingOverrides.empty())
  193. removeOverriddenTables();
  194. if (Tables.size() > static_cast<unsigned>(Info::MaxTables))
  195. condense();
  196. internal_key_type Key = Info::GetInternalKey(EKey);
  197. auto KeyHash = Info::ComputeHash(Key);
  198. if (MergedTable *M = getMergedTable()) {
  199. auto It = M->Data.find(Key);
  200. if (It != M->Data.end())
  201. Result = It->second;
  202. }
  203. data_type_builder ResultBuilder(Result);
  204. for (auto *ODT : tables()) {
  205. auto &HT = ODT->Table;
  206. auto It = HT.find_hashed(Key, KeyHash);
  207. if (It != HT.end())
  208. HT.getInfoObj().ReadDataInto(Key, It.getDataPtr(), It.getDataLen(),
  209. ResultBuilder);
  210. }
  211. return Result;
  212. }
  213. /// Read all the lookup results into a single value. This only makes
  214. /// sense if merging values across keys is meaningful.
  215. data_type findAll() {
  216. data_type Result;
  217. data_type_builder ResultBuilder(Result);
  218. if (!PendingOverrides.empty())
  219. removeOverriddenTables();
  220. if (MergedTable *M = getMergedTable()) {
  221. for (auto &KV : M->Data)
  222. Info::MergeDataInto(KV.second, ResultBuilder);
  223. }
  224. for (auto *ODT : tables()) {
  225. auto &HT = ODT->Table;
  226. Info &InfoObj = HT.getInfoObj();
  227. for (auto I = HT.data_begin(), E = HT.data_end(); I != E; ++I) {
  228. auto *LocalPtr = I.getItem();
  229. // FIXME: Don't rely on the OnDiskHashTable format here.
  230. auto L = InfoObj.ReadKeyDataLength(LocalPtr);
  231. const internal_key_type &Key = InfoObj.ReadKey(LocalPtr, L.first);
  232. InfoObj.ReadDataInto(Key, LocalPtr + L.first, L.second, ResultBuilder);
  233. }
  234. }
  235. return Result;
  236. }
  237. };
  238. /// Writer for the on-disk hash table.
  239. template<typename ReaderInfo, typename WriterInfo>
  240. class MultiOnDiskHashTableGenerator {
  241. using BaseTable = MultiOnDiskHashTable<ReaderInfo>;
  242. using Generator = llvm::OnDiskChainedHashTableGenerator<WriterInfo>;
  243. Generator Gen;
  244. public:
  245. MultiOnDiskHashTableGenerator() : Gen() {}
  246. void insert(typename WriterInfo::key_type_ref Key,
  247. typename WriterInfo::data_type_ref Data, WriterInfo &Info) {
  248. Gen.insert(Key, Data, Info);
  249. }
  250. void emit(llvm::SmallVectorImpl<char> &Out, WriterInfo &Info,
  251. const BaseTable *Base) {
  252. using namespace llvm::support;
  253. llvm::raw_svector_ostream OutStream(Out);
  254. // Write our header information.
  255. {
  256. endian::Writer Writer(OutStream, little);
  257. // Reserve four bytes for the bucket offset.
  258. Writer.write<uint32_t>(0);
  259. if (auto *Merged = Base ? Base->getMergedTable() : nullptr) {
  260. // Write list of overridden files.
  261. Writer.write<uint32_t>(Merged->Files.size());
  262. for (const auto &F : Merged->Files)
  263. Info.EmitFileRef(OutStream, F);
  264. // Add all merged entries from Base to the generator.
  265. for (auto &KV : Merged->Data) {
  266. if (!Gen.contains(KV.first, Info))
  267. Gen.insert(KV.first, Info.ImportData(KV.second), Info);
  268. }
  269. } else {
  270. Writer.write<uint32_t>(0);
  271. }
  272. }
  273. // Write the table itself.
  274. uint32_t BucketOffset = Gen.Emit(OutStream, Info);
  275. // Replace the first four bytes with the bucket offset.
  276. endian::write32le(Out.data(), BucketOffset);
  277. }
  278. };
  279. } // namespace serialization
  280. } // namespace clang
  281. #endif // LLVM_CLANG_LIB_SERIALIZATION_MULTIONDISKHASHTABLE_H