OmniSciDB  eb3a3d0a03
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BaselineJoinHashTable.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, 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 
18 
19 #include <future>
20 
24 #include "QueryEngine/Execute.h"
31 
32 std::unique_ptr<
36 
38 std::shared_ptr<BaselineJoinHashTable> BaselineJoinHashTable::getInstance(
39  const std::shared_ptr<Analyzer::BinOper> condition,
40  const std::vector<InputTableInfo>& query_infos,
41  const Data_Namespace::MemoryLevel memory_level,
42  const JoinType join_type,
43  const HashType preferred_hash_type,
44  const int device_count,
45  ColumnCacheMap& column_cache,
46  Executor* executor) {
47  decltype(std::chrono::steady_clock::now()) ts1, ts2;
48 
49  if (VLOGGING(1)) {
50  VLOG(1) << "Building keyed hash table " << getHashTypeString(preferred_hash_type)
51  << " for qual: " << condition->toString();
52  ts1 = std::chrono::steady_clock::now();
53  }
54  auto inner_outer_pairs = HashJoin::normalizeColumnPairs(
55  condition.get(), *executor->getCatalog(), executor->getTemporaryTables());
56 
57  auto join_hash_table =
58  std::shared_ptr<BaselineJoinHashTable>(new BaselineJoinHashTable(condition,
59  join_type,
60  query_infos,
61  memory_level,
62  column_cache,
63  executor,
64  inner_outer_pairs,
65  device_count));
66  try {
67  join_hash_table->reify(preferred_hash_type);
68  } catch (const TableMustBeReplicated& e) {
69  // Throw a runtime error to abort the query
70  join_hash_table->freeHashBufferMemory();
71  throw std::runtime_error(e.what());
72  } catch (const HashJoinFail& e) {
73  // HashJoinFail exceptions log an error and trigger a retry with a join loop (if
74  // possible)
75  join_hash_table->freeHashBufferMemory();
76  throw HashJoinFail(std::string("Could not build a 1-to-1 correspondence for columns "
77  "involved in equijoin | ") +
78  e.what());
79  } catch (const ColumnarConversionNotSupported& e) {
80  throw HashJoinFail(std::string("Could not build hash tables for equijoin | ") +
81  e.what());
82  } catch (const OutOfMemory& e) {
83  throw HashJoinFail(
84  std::string("Ran out of memory while building hash tables for equijoin | ") +
85  e.what());
86  } catch (const std::exception& e) {
87  throw std::runtime_error(
88  std::string("Fatal error while attempting to build hash tables for join: ") +
89  e.what());
90  }
91  if (VLOGGING(1)) {
92  ts2 = std::chrono::steady_clock::now();
93  VLOG(1) << "Built keyed hash table "
94  << getHashTypeString(join_hash_table->getHashType()) << " in "
95  << std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1).count()
96  << " ms";
97  }
98  return join_hash_table;
99 }
100 
102  const std::shared_ptr<Analyzer::BinOper> condition,
103  const JoinType join_type,
104  const std::vector<InputTableInfo>& query_infos,
105  const Data_Namespace::MemoryLevel memory_level,
106  ColumnCacheMap& column_cache,
107  Executor* executor,
108  const std::vector<InnerOuter>& inner_outer_pairs,
109  const int device_count)
110  : condition_(condition)
111  , join_type_(join_type)
112  , query_infos_(query_infos)
113  , memory_level_(memory_level)
114  , executor_(executor)
115  , column_cache_(column_cache)
116  , inner_outer_pairs_(inner_outer_pairs)
117  , catalog_(executor->getCatalog())
118  , device_count_(device_count) {
120  hash_tables_for_device_.resize(std::max(device_count_, 1));
121 }
122 
124  const Analyzer::BinOper* condition,
125  const Executor* executor,
126  const std::vector<InnerOuter>& inner_outer_pairs) {
127  for (const auto& inner_outer_pair : inner_outer_pairs) {
128  const auto pair_shard_count = get_shard_count(inner_outer_pair, executor);
129  if (pair_shard_count) {
130  return pair_shard_count;
131  }
132  }
133  return 0;
134 }
135 
137  const int device_id,
138  bool raw) const {
139  auto buffer = getJoinHashBuffer(device_type, device_id);
140  CHECK_LT(device_id, hash_tables_for_device_.size());
141  auto hash_table = hash_tables_for_device_[device_id];
142  CHECK(hash_table);
143  auto buffer_size = hash_table->getHashTableBufferSize(device_type);
144 #ifdef HAVE_CUDA
145  std::unique_ptr<int8_t[]> buffer_copy;
146  if (device_type == ExecutorDeviceType::GPU) {
147  buffer_copy = std::make_unique<int8_t[]>(buffer_size);
148 
150  buffer_copy.get(),
151  reinterpret_cast<CUdeviceptr>(reinterpret_cast<int8_t*>(buffer)),
152  buffer_size,
153  device_id);
154  }
155  auto ptr1 = buffer_copy ? buffer_copy.get() : reinterpret_cast<const int8_t*>(buffer);
156 #else
157  auto ptr1 = reinterpret_cast<const int8_t*>(buffer);
158 #endif // HAVE_CUDA
159  auto ptr2 = ptr1 + offsetBufferOff();
160  auto ptr3 = ptr1 + countBufferOff();
161  auto ptr4 = ptr1 + payloadBufferOff();
162  CHECK(hash_table);
163  const auto layout = getHashType();
164  return HashTable::toString(
165  "keyed",
166  getHashTypeString(layout),
167  getKeyComponentCount() + (layout == HashType::OneToOne ? 1 : 0),
169  hash_table->getEntryCount(),
170  ptr1,
171  ptr2,
172  ptr3,
173  ptr4,
174  buffer_size,
175  raw);
176 }
177 
178 std::set<DecodedJoinHashBufferEntry> BaselineJoinHashTable::toSet(
179  const ExecutorDeviceType device_type,
180  const int device_id) const {
181  auto buffer = getJoinHashBuffer(device_type, device_id);
182  auto hash_table = getHashTableForDevice(device_id);
183  CHECK(hash_table);
184  auto buffer_size = hash_table->getHashTableBufferSize(device_type);
185 #ifdef HAVE_CUDA
186  std::unique_ptr<int8_t[]> buffer_copy;
187  if (device_type == ExecutorDeviceType::GPU) {
188  buffer_copy = std::make_unique<int8_t[]>(buffer_size);
189 
191  buffer_copy.get(),
192  reinterpret_cast<CUdeviceptr>(reinterpret_cast<int8_t*>(buffer)),
193  buffer_size,
194  device_id);
195  }
196  auto ptr1 = buffer_copy ? buffer_copy.get() : reinterpret_cast<const int8_t*>(buffer);
197 #else
198  auto ptr1 = reinterpret_cast<const int8_t*>(buffer);
199 #endif // HAVE_CUDA
200  auto ptr2 = ptr1 + offsetBufferOff();
201  auto ptr3 = ptr1 + countBufferOff();
202  auto ptr4 = ptr1 + payloadBufferOff();
203  const auto layout = hash_table->getLayout();
204  return HashTable::toSet(getKeyComponentCount() + (layout == HashType::OneToOne ? 1 : 0),
206  hash_table->getEntryCount(),
207  ptr1,
208  ptr2,
209  ptr3,
210  ptr4,
211  buffer_size);
212 }
213 
214 void BaselineJoinHashTable::reify(const HashType preferred_layout) {
215  auto timer = DEBUG_TIMER(__func__);
217  const auto composite_key_info =
219  const auto type_and_found = HashTypeCache::get(composite_key_info.cache_key_chunks);
220  const auto layout = type_and_found.second ? type_and_found.first : preferred_layout;
221 
226  executor_);
227 
228  if (condition_->is_overlaps_oper()) {
229  CHECK_EQ(inner_outer_pairs_.size(), size_t(1));
230  HashType layout;
231 
232  if (inner_outer_pairs_[0].second->get_type_info().is_array()) {
233  layout = HashType::ManyToMany;
234  } else {
235  layout = HashType::OneToMany;
236  }
237  try {
238  reifyWithLayout(layout);
239  return;
240  } catch (const std::exception& e) {
241  VLOG(1) << "Caught exception while building overlaps baseline hash table: "
242  << e.what();
243  throw;
244  }
245  }
246 
247  try {
248  reifyWithLayout(layout);
249  } catch (const std::exception& e) {
250  VLOG(1) << "Caught exception while building baseline hash table: " << e.what();
252  HashTypeCache::set(composite_key_info.cache_key_chunks, HashType::OneToMany);
254  }
255 }
256 
258  const auto& query_info = get_inner_query_info(getInnerTableId(), query_infos_).info;
259  if (query_info.fragments.empty()) {
260  return;
261  }
262 
263  const auto total_entries = 2 * query_info.getNumTuplesUpperBound();
264  if (total_entries > static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
265  throw TooManyHashEntries();
266  }
267 
268  auto data_mgr = executor_->getDataMgr();
269  std::vector<std::unique_ptr<CudaAllocator>> dev_buff_owners;
271  for (int device_id = 0; device_id < device_count_; ++device_id) {
272  dev_buff_owners.emplace_back(std::make_unique<CudaAllocator>(data_mgr, device_id));
273  }
274  }
275  std::vector<ColumnsForDevice> columns_per_device;
276  const auto shard_count = shardCount();
277  auto entries_per_device =
278  get_entries_per_device(total_entries, shard_count, device_count_, memory_level_);
279 
280  for (int device_id = 0; device_id < device_count_; ++device_id) {
281  const auto fragments =
282  shard_count
283  ? only_shards_for_device(query_info.fragments, device_id, device_count_)
284  : query_info.fragments;
285  const auto columns_for_device =
286  fetchColumnsForDevice(fragments,
287  device_id,
289  ? dev_buff_owners[device_id].get()
290  : nullptr);
291  columns_per_device.push_back(columns_for_device);
292  }
293  size_t emitted_keys_count = 0;
294  if (layout == HashType::OneToMany) {
295  CHECK(!columns_per_device.front().join_columns.empty());
296  emitted_keys_count = columns_per_device.front().join_columns.front().num_elems;
297  size_t tuple_count;
298  std::tie(tuple_count, std::ignore) = approximateTupleCount(columns_per_device);
299  const auto entry_count = 2 * std::max(tuple_count, size_t(1));
300 
301  // reset entries per device with one to many info
302  entries_per_device =
303  get_entries_per_device(entry_count, shard_count, device_count_, memory_level_);
304  }
305  std::vector<std::future<void>> init_threads;
306  for (int device_id = 0; device_id < device_count_; ++device_id) {
307  const auto fragments =
308  shard_count
309  ? only_shards_for_device(query_info.fragments, device_id, device_count_)
310  : query_info.fragments;
311  init_threads.push_back(std::async(std::launch::async,
313  this,
314  columns_per_device[device_id],
315  layout,
316  device_id,
317  entries_per_device,
318  emitted_keys_count,
319  logger::thread_id()));
320  }
321  for (auto& init_thread : init_threads) {
322  init_thread.wait();
323  }
324  for (auto& init_thread : init_threads) {
325  init_thread.get();
326  }
327 }
328 
330  const std::vector<ColumnsForDevice>& columns_per_device) const {
331  const auto effective_memory_level = getEffectiveMemoryLevel(inner_outer_pairs_);
332  CountDistinctDescriptor count_distinct_desc{
334  0,
335  11,
336  true,
337  effective_memory_level == Data_Namespace::MemoryLevel::GPU_LEVEL
340  1};
341  const auto padded_size_bytes = count_distinct_desc.bitmapPaddedSizeBytes();
342 
343  CHECK(!columns_per_device.empty() && !columns_per_device.front().join_columns.empty());
344 
345  if (effective_memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
346  const auto composite_key_info =
348  HashTableCacheKey cache_key{columns_per_device.front().join_columns.front().num_elems,
349  composite_key_info.cache_key_chunks,
350  condition_->get_optype(),
351  join_type_};
352  const auto cached_count_info = getApproximateTupleCountFromCache(cache_key);
353  if (cached_count_info.first) {
354  VLOG(1) << "Using a cached tuple count: " << *cached_count_info.first
355  << ", emitted keys count: " << cached_count_info.second;
356  return std::make_pair(*cached_count_info.first, cached_count_info.second);
357  }
358  int thread_count = cpu_threads();
359  std::vector<uint8_t> hll_buffer_all_cpus(thread_count * padded_size_bytes);
360  auto hll_result = &hll_buffer_all_cpus[0];
361 
362  approximate_distinct_tuples(hll_result,
363  count_distinct_desc.bitmap_sz_bits,
364  padded_size_bytes,
365  columns_per_device.front().join_columns,
366  columns_per_device.front().join_column_types,
367  thread_count);
368  for (int i = 1; i < thread_count; ++i) {
369  hll_unify(hll_result,
370  hll_result + i * padded_size_bytes,
371  1 << count_distinct_desc.bitmap_sz_bits);
372  }
373  return std::make_pair(hll_size(hll_result, count_distinct_desc.bitmap_sz_bits), 0);
374  }
375 #ifdef HAVE_CUDA
376  auto data_mgr = executor_->getDataMgr();
377  std::vector<std::vector<uint8_t>> host_hll_buffers(device_count_);
378  for (auto& host_hll_buffer : host_hll_buffers) {
379  host_hll_buffer.resize(count_distinct_desc.bitmapPaddedSizeBytes());
380  }
381  std::vector<std::future<void>> approximate_distinct_device_threads;
382  for (int device_id = 0; device_id < device_count_; ++device_id) {
383  approximate_distinct_device_threads.emplace_back(std::async(
385  [device_id,
386  &columns_per_device,
387  &count_distinct_desc,
388  data_mgr,
389  &host_hll_buffers] {
390  CudaAllocator allocator(data_mgr, device_id);
391  auto device_hll_buffer =
392  allocator.alloc(count_distinct_desc.bitmapPaddedSizeBytes());
393  data_mgr->getCudaMgr()->zeroDeviceMem(
394  device_hll_buffer, count_distinct_desc.bitmapPaddedSizeBytes(), device_id);
395  const auto& columns_for_device = columns_per_device[device_id];
396  auto join_columns_gpu = transfer_vector_of_flat_objects_to_gpu(
397  columns_for_device.join_columns, allocator);
398  auto join_column_types_gpu = transfer_vector_of_flat_objects_to_gpu(
399  columns_for_device.join_column_types, allocator);
400  const auto key_handler =
401  GenericKeyHandler(columns_for_device.join_columns.size(),
402  true,
403  join_columns_gpu,
404  join_column_types_gpu,
405  nullptr,
406  nullptr);
407  const auto key_handler_gpu =
408  transfer_flat_object_to_gpu(key_handler, allocator);
410  reinterpret_cast<uint8_t*>(device_hll_buffer),
411  count_distinct_desc.bitmap_sz_bits,
412  key_handler_gpu,
413  columns_for_device.join_columns[0].num_elems);
414 
415  auto& host_hll_buffer = host_hll_buffers[device_id];
416  copy_from_gpu(data_mgr,
417  &host_hll_buffer[0],
418  reinterpret_cast<CUdeviceptr>(device_hll_buffer),
419  count_distinct_desc.bitmapPaddedSizeBytes(),
420  device_id);
421  }));
422  }
423  for (auto& child : approximate_distinct_device_threads) {
424  child.get();
425  }
426  CHECK_EQ(Data_Namespace::MemoryLevel::GPU_LEVEL, effective_memory_level);
427  auto& result_hll_buffer = host_hll_buffers.front();
428  auto hll_result = reinterpret_cast<int32_t*>(&result_hll_buffer[0]);
429  for (int device_id = 1; device_id < device_count_; ++device_id) {
430  auto& host_hll_buffer = host_hll_buffers[device_id];
431  hll_unify(hll_result,
432  reinterpret_cast<int32_t*>(&host_hll_buffer[0]),
433  1 << count_distinct_desc.bitmap_sz_bits);
434  }
435  return std::make_pair(hll_size(hll_result, count_distinct_desc.bitmap_sz_bits), 0);
436 #else
437  UNREACHABLE();
438  return {0, 0};
439 #endif // HAVE_CUDA
440 }
441 
443  const std::vector<Fragmenter_Namespace::FragmentInfo>& fragments,
444  const int device_id,
445  DeviceAllocator* dev_buff_owner) {
446  const auto effective_memory_level = getEffectiveMemoryLevel(inner_outer_pairs_);
447 
448  std::vector<JoinColumn> join_columns;
449  std::vector<std::shared_ptr<Chunk_NS::Chunk>> chunks_owner;
450  std::vector<JoinColumnTypeInfo> join_column_types;
451  std::vector<JoinBucketInfo> join_bucket_info;
452  std::vector<std::shared_ptr<void>> malloc_owner;
453  for (const auto& inner_outer_pair : inner_outer_pairs_) {
454  const auto inner_col = inner_outer_pair.first;
455  const auto inner_cd = get_column_descriptor_maybe(
456  inner_col->get_column_id(), inner_col->get_table_id(), *catalog_);
457  if (inner_cd && inner_cd->isVirtualCol) {
459  }
460  join_columns.emplace_back(fetchJoinColumn(inner_col,
461  fragments,
462  effective_memory_level,
463  device_id,
464  chunks_owner,
465  dev_buff_owner,
466  malloc_owner,
467  executor_,
468  &column_cache_));
469  const auto& ti = inner_col->get_type_info();
470  join_column_types.emplace_back(JoinColumnTypeInfo{static_cast<size_t>(ti.get_size()),
471  0,
472  0,
474  isBitwiseEq(),
475  0,
477  }
478  return {join_columns, join_column_types, chunks_owner, join_bucket_info, malloc_owner};
479 }
480 
482  const HashType layout,
483  const int device_id,
484  const size_t entry_count,
485  const size_t emitted_keys_count,
486  const logger::ThreadId parent_thread_id) {
487  DEBUG_TIMER_NEW_THREAD(parent_thread_id);
488  const auto effective_memory_level = getEffectiveMemoryLevel(inner_outer_pairs_);
489  const auto err = initHashTableForDevice(columns_for_device.join_columns,
490  columns_for_device.join_column_types,
491  columns_for_device.join_buckets,
492  layout,
493  effective_memory_level,
494  entry_count,
495  emitted_keys_count,
496  device_id);
497  if (err) {
498  throw HashJoinFail(
499  std::string("Unrecognized error when initializing baseline hash table (") +
500  std::to_string(err) + std::string(")"));
501  }
502 }
503 
506  return 0;
507  }
510 }
511 
513  for (const auto& inner_outer_pair : inner_outer_pairs_) {
514  const auto inner_col = inner_outer_pair.first;
515  const auto& inner_col_ti = inner_col->get_type_info();
516  if (inner_col_ti.get_logical_size() > 4) {
517  CHECK_EQ(8, inner_col_ti.get_logical_size());
518  return 8;
519  }
520  }
521  return 4;
522 }
523 
525  return inner_outer_pairs_.size();
526 }
527 
529  const std::vector<InnerOuter>& inner_outer_pairs) const {
530  for (const auto& inner_outer_pair : inner_outer_pairs) {
532  inner_outer_pair.first, inner_outer_pair.second, executor_)) {
534  }
535  }
536  return memory_level_;
537 }
538 
540  const std::vector<JoinColumn>& join_columns,
541  const std::vector<JoinColumnTypeInfo>& join_column_types,
542  const std::vector<JoinBucketInfo>& join_bucket_info,
543  const HashType layout,
544  const Data_Namespace::MemoryLevel effective_memory_level,
545  const size_t entry_count,
546  const size_t emitted_keys_count,
547  const int device_id) {
548  auto timer = DEBUG_TIMER(__func__);
549  const auto key_component_count = getKeyComponentCount();
550  int err = 0;
551 
552  if (effective_memory_level == Data_Namespace::CPU_LEVEL) {
553  std::lock_guard<std::mutex> cpu_hash_table_buff_lock(cpu_hash_table_buff_mutex_);
554 
555  const auto composite_key_info =
557 
558  CHECK(!join_columns.empty());
559  HashTableCacheKey cache_key{join_columns.front().num_elems,
560  composite_key_info.cache_key_chunks,
561  condition_->get_optype(),
562  join_type_};
563 
565  CHECK_EQ(device_id, size_t(0));
566  }
567  CHECK_LT(static_cast<size_t>(device_id), hash_tables_for_device_.size());
568 
569  auto hash_table = initHashTableOnCpuFromCache(cache_key);
570  if (hash_table) {
571  hash_tables_for_device_[device_id] = hash_table;
572  } else {
574 
575  const auto key_handler =
576  GenericKeyHandler(key_component_count,
577  true,
578  &join_columns[0],
579  &join_column_types[0],
580  &composite_key_info.sd_inner_proxy_per_key[0],
581  &composite_key_info.sd_outer_proxy_per_key[0]);
582  err = builder.initHashTableOnCpu(&key_handler,
583  composite_key_info,
584  join_columns,
585  join_column_types,
586  join_bucket_info,
587  entry_count,
588  join_columns.front().num_elems,
589  layout,
590  join_type_,
593  hash_tables_for_device_[device_id] = builder.getHashTable();
594 
595  if (!err) {
596  if (getInnerTableId() > 0) {
597  putHashTableOnCpuToCache(cache_key, hash_tables_for_device_[device_id]);
598  }
599  }
600  }
601  // Transfer the hash table on the GPU if we've only built it on CPU
602  // but the query runs on GPU (join on dictionary encoded columns).
603  // Don't transfer the buffer if there was an error since we'll bail anyway.
604  if (memory_level_ == Data_Namespace::GPU_LEVEL && !err) {
605 #ifdef HAVE_CUDA
607 
608  builder.allocateDeviceMemory(layout,
611  entry_count,
612  emitted_keys_count,
613  device_id,
614  executor_);
615 
616  CHECK_LT(size_t(device_id), hash_tables_for_device_.size());
617  auto cpu_source_hash_table = hash_tables_for_device_[device_id];
618  CHECK(cpu_source_hash_table);
619  auto gpu_target_hash_table = builder.getHashTable();
620  CHECK(gpu_target_hash_table);
621 
622  const auto gpu_buff = gpu_target_hash_table->getGpuBuffer();
623  CHECK(gpu_buff);
624  auto data_mgr = executor_->getDataMgr();
625  copy_to_gpu(data_mgr,
626  reinterpret_cast<CUdeviceptr>(gpu_buff),
627  cpu_source_hash_table->getCpuBuffer(),
628  cpu_source_hash_table->getHashTableBufferSize(ExecutorDeviceType::CPU),
629  device_id);
630  hash_tables_for_device_[device_id] = std::move(gpu_target_hash_table);
631 #else
632  CHECK(false);
633 #endif
634  }
635  } else {
636 #ifdef HAVE_CUDA
638 
639  auto data_mgr = executor_->getDataMgr();
640  CudaAllocator allocator(data_mgr, device_id);
641  auto join_column_types_gpu =
642  transfer_vector_of_flat_objects_to_gpu(join_column_types, allocator);
643  auto join_columns_gpu =
644  transfer_vector_of_flat_objects_to_gpu(join_columns, allocator);
645  const auto key_handler = GenericKeyHandler(key_component_count,
646  true,
647  join_columns_gpu,
648  join_column_types_gpu,
649  nullptr,
650  nullptr);
651 
652  err = builder.initHashTableOnGpu(&key_handler,
653  join_columns,
654  layout,
655  join_type_,
658  entry_count,
659  emitted_keys_count,
660  device_id,
661  executor_);
662  CHECK_LT(size_t(device_id), hash_tables_for_device_.size());
663  hash_tables_for_device_[device_id] = builder.getHashTable();
664 #else
665  UNREACHABLE();
666 #endif
667  }
668  return err;
669 }
670 
671 #define LL_CONTEXT executor_->cgen_state_->context_
672 #define LL_BUILDER executor_->cgen_state_->ir_builder_
673 #define LL_INT(v) executor_->cgen_state_->llInt(v)
674 #define LL_FP(v) executor_->cgen_state_->llFp(v)
675 #define ROW_FUNC executor_->cgen_state_->row_func_
676 
678  const size_t index) {
679  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
681  const auto key_component_width = getKeyComponentWidth();
682  CHECK(key_component_width == 4 || key_component_width == 8);
683  auto key_buff_lv = codegenKey(co);
684  const auto hash_ptr = hashPtr(index);
685  const auto key_ptr_lv =
686  LL_BUILDER.CreatePointerCast(key_buff_lv, llvm::Type::getInt8PtrTy(LL_CONTEXT));
687  const auto key_size_lv = LL_INT(getKeyComponentCount() * key_component_width);
688  const auto hash_table = getHashTableForDevice(size_t(0));
689  return executor_->cgen_state_->emitExternalCall(
690  "baseline_hash_join_idx_" + std::to_string(key_component_width * 8),
692  {hash_ptr, key_ptr_lv, key_size_lv, LL_INT(hash_table->getEntryCount())});
693 }
694 
696  const CompilationOptions& co,
697  const size_t index) {
698  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
699  const auto hash_table = getHashTableForDevice(size_t(0));
700  CHECK(hash_table);
701  const auto key_component_width = getKeyComponentWidth();
702  CHECK(key_component_width == 4 || key_component_width == 8);
703  auto key_buff_lv = codegenKey(co);
705  auto hash_ptr = HashJoin::codegenHashTableLoad(index, executor_);
706  const auto composite_dict_ptr_type =
707  llvm::Type::getIntNPtrTy(LL_CONTEXT, key_component_width * 8);
708  const auto composite_key_dict =
709  hash_ptr->getType()->isPointerTy()
710  ? LL_BUILDER.CreatePointerCast(hash_ptr, composite_dict_ptr_type)
711  : LL_BUILDER.CreateIntToPtr(hash_ptr, composite_dict_ptr_type);
712  const auto key_component_count = getKeyComponentCount();
713  const auto key = executor_->cgen_state_->emitExternalCall(
714  "get_composite_key_index_" + std::to_string(key_component_width * 8),
716  {key_buff_lv,
717  LL_INT(key_component_count),
718  composite_key_dict,
719  LL_INT(hash_table->getEntryCount())});
720  auto one_to_many_ptr = hash_ptr;
721  if (one_to_many_ptr->getType()->isPointerTy()) {
722  one_to_many_ptr =
723  LL_BUILDER.CreatePtrToInt(hash_ptr, llvm::Type::getInt64Ty(LL_CONTEXT));
724  } else {
725  CHECK(one_to_many_ptr->getType()->isIntegerTy(64));
726  }
727  const auto composite_key_dict_size = offsetBufferOff();
728  one_to_many_ptr =
729  LL_BUILDER.CreateAdd(one_to_many_ptr, LL_INT(composite_key_dict_size));
731  {one_to_many_ptr, key, LL_INT(int64_t(0)), LL_INT(hash_table->getEntryCount() - 1)},
732  false,
733  false,
734  false,
736  executor_);
737 }
738 
740  return getKeyBufferSize();
741 }
742 
746  } else {
747  return getKeyBufferSize();
748  }
749 }
750 
754  } else {
755  return getKeyBufferSize();
756  }
757 }
758 
760  const auto key_component_width = getKeyComponentWidth();
761  CHECK(key_component_width == 4 || key_component_width == 8);
762  const auto key_component_count = getKeyComponentCount();
763  auto hash_table = getHashTableForDevice(size_t(0));
764  CHECK(hash_table);
765  if (layoutRequiresAdditionalBuffers(hash_table->getLayout())) {
766  return hash_table->getEntryCount() * key_component_count * key_component_width;
767  } else {
768  return hash_table->getEntryCount() * (key_component_count + 1) * key_component_width;
769  }
770 }
771 
773  const auto hash_table = getHashTableForDevice(size_t(0));
774  return hash_table->getEntryCount() * sizeof(int32_t);
775 }
776 
778  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
779  const auto key_component_width = getKeyComponentWidth();
780  CHECK(key_component_width == 4 || key_component_width == 8);
781  const auto key_size_lv = LL_INT(getKeyComponentCount() * key_component_width);
782  llvm::Value* key_buff_lv{nullptr};
783  switch (key_component_width) {
784  case 4:
785  key_buff_lv =
786  LL_BUILDER.CreateAlloca(llvm::Type::getInt32Ty(LL_CONTEXT), key_size_lv);
787  break;
788  case 8:
789  key_buff_lv =
790  LL_BUILDER.CreateAlloca(llvm::Type::getInt64Ty(LL_CONTEXT), key_size_lv);
791  break;
792  default:
793  CHECK(false);
794  }
795 
796  CodeGenerator code_generator(executor_);
797  for (size_t i = 0; i < getKeyComponentCount(); ++i) {
798  const auto key_comp_dest_lv = LL_BUILDER.CreateGEP(key_buff_lv, LL_INT(i));
799  const auto& inner_outer_pair = inner_outer_pairs_[i];
800  const auto outer_col = inner_outer_pair.second;
801  const auto key_col_var = dynamic_cast<const Analyzer::ColumnVar*>(outer_col);
802  const auto val_col_var =
803  dynamic_cast<const Analyzer::ColumnVar*>(inner_outer_pair.first);
804  if (key_col_var && val_col_var &&
806  key_col_var,
807  val_col_var,
808  get_max_rte_scan_table(executor_->cgen_state_->scan_idx_to_hash_pos_))) {
809  throw std::runtime_error(
810  "Query execution fails because the query contains not supported self-join "
811  "pattern. We suspect the query requires multiple left-deep join tree due to "
812  "the join condition of the self-join and is not supported for now. Please "
813  "consider rewriting table order in "
814  "FROM clause.");
815  }
816  const auto col_lvs = code_generator.codegen(outer_col, true, co);
817  CHECK_EQ(size_t(1), col_lvs.size());
818  const auto col_lv = LL_BUILDER.CreateSExt(
819  col_lvs.front(), get_int_type(key_component_width * 8, LL_CONTEXT));
820  LL_BUILDER.CreateStore(col_lv, key_comp_dest_lv);
821  }
822  return key_buff_lv;
823 }
824 
825 llvm::Value* BaselineJoinHashTable::hashPtr(const size_t index) {
826  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
827  auto hash_ptr = HashJoin::codegenHashTableLoad(index, executor_);
828  const auto pi8_type = llvm::Type::getInt8PtrTy(LL_CONTEXT);
829  return hash_ptr->getType()->isPointerTy()
830  ? LL_BUILDER.CreatePointerCast(hash_ptr, pi8_type)
831  : LL_BUILDER.CreateIntToPtr(hash_ptr, pi8_type);
832 }
833 
834 #undef ROW_FUNC
835 #undef LL_INT
836 #undef LL_BUILDER
837 #undef LL_CONTEXT
838 
840  try {
842  } catch (...) {
843  CHECK(false);
844  }
845  return 0;
846 }
847 
849  CHECK(!inner_outer_pairs_.empty());
850  const auto first_inner_col = inner_outer_pairs_.front().first;
851  return first_inner_col->get_rte_idx();
852 }
853 
855  auto hash_table = getHashTableForDevice(size_t(0));
856  CHECK(hash_table);
857  if (layout_override_) {
858  return *layout_override_;
859  } else {
860  return hash_table->getLayout();
861  }
862 }
863 
865  const std::vector<InnerOuter>& inner_outer_pairs) {
866  CHECK(!inner_outer_pairs.empty());
867  const auto first_inner_col = inner_outer_pairs.front().first;
868  return first_inner_col->get_table_id();
869 }
870 
872  const HashTableCacheKey& key) {
873  auto timer = DEBUG_TIMER(__func__);
874  VLOG(1) << "Checking CPU hash table cache.";
876  auto hash_table_opt = (hash_table_cache_->get(key));
877  return hash_table_opt ? *hash_table_opt : nullptr;
878 }
879 
881  const HashTableCacheKey& key,
882  std::shared_ptr<HashTable>& hash_table) {
883  for (auto chunk_key : key.chunk_keys) {
884  CHECK_GE(chunk_key.size(), size_t(2));
885  if (chunk_key[1] < 0) {
886  return;
887  }
888  }
890  hash_table_cache_->insert(key, hash_table);
891 }
892 
893 std::pair<std::optional<size_t>, size_t>
895  const HashTableCacheKey& key) const {
896  for (auto chunk_key : key.chunk_keys) {
897  CHECK_GE(chunk_key.size(), size_t(2));
898  if (chunk_key[1] < 0) {
899  return std::make_pair(std::nullopt, 0);
900  ;
901  }
902  }
903 
905  auto hash_table_opt = hash_table_cache_->get(key);
906  if (hash_table_opt) {
907  auto hash_table = *hash_table_opt;
908  return std::make_pair(hash_table->getEntryCount() / 2,
909  hash_table->getEmittedKeysCount());
910  }
911  return std::make_pair(std::nullopt, 0);
912 }
913 
915  return condition_->get_optype() == kBW_EQ;
916 }
917 
918 std::map<std::vector<ChunkKey>, HashType> HashTypeCache::hash_type_cache_;
920 
921 void HashTypeCache::set(const std::vector<ChunkKey>& key, const HashType hash_type) {
922  for (auto chunk_key : key) {
923  CHECK_GE(chunk_key.size(), size_t(2));
924  if (chunk_key[1] < 0) {
925  return;
926  }
927  }
928  std::lock_guard<std::mutex> hash_type_cache_lock(hash_type_cache_mutex_);
929  hash_type_cache_[key] = hash_type;
930 }
931 
932 std::pair<HashType, bool> HashTypeCache::get(const std::vector<ChunkKey>& key) {
933  std::lock_guard<std::mutex> hash_type_cache_lock(hash_type_cache_mutex_);
934  const auto it = hash_type_cache_.find(key);
935  if (it == hash_type_cache_.end()) {
936  return {HashType::OneToOne, false};
937  }
938  return {it->second, true};
939 }
940 
942  std::lock_guard<std::mutex> hash_type_cache_lock(hash_type_cache_mutex_);
943  hash_type_cache_.clear();
944 }
size_t offsetBufferOff() const noexceptoverride
catalog_(nullptr)
std::set< DecodedJoinHashBufferEntry > toSet(const ExecutorDeviceType device_type, const int device_id) const override
void putHashTableOnCpuToCache(const HashTableCacheKey &, std::shared_ptr< HashTable > &hash_table)
#define CHECK_EQ(x, y)
Definition: Logger.h:217
static std::unique_ptr< HashTableCache< HashTableCacheKey, HashTableCacheValue > > hash_table_cache_
virtual HashJoinMatchingSet codegenMatchingSet(const CompilationOptions &, const size_t)=0
int64_t getJoinHashBuffer(const ExecutorDeviceType device_type, const int device_id) const
Definition: HashJoin.h:256
JoinType
Definition: sqldefs.h:108
Fragmenter_Namespace::TableInfo info
Definition: InputMetadata.h:35
std::string toString(const ExecutorDeviceType device_type, const int device_id=0, bool raw=false) const override
static llvm::Value * codegenHashTableLoad(const size_t table_idx, Executor *executor)
Definition: HashJoin.cpp:215
bool self_join_not_covered_by_left_deep_tree(const Analyzer::ColumnVar *key_side, const Analyzer::ColumnVar *val_side, const int max_rte_covered)
Data_Namespace::MemoryLevel getEffectiveMemoryLevel(const std::vector< InnerOuter > &inner_outer_pairs) const
static std::mutex hash_type_cache_mutex_
ExecutorDeviceType
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:223
#define const
static std::map< std::vector< ChunkKey >, HashType > hash_type_cache_
HashJoinMatchingSet codegenMatchingSet(const CompilationOptions &, const size_t) override
void hll_unify(T1 *lhs, T2 *rhs, const size_t m)
Definition: HyperLogLog.h:109
JoinColumn fetchJoinColumn(const Analyzer::ColumnVar *hash_col, const std::vector< Fragmenter_Namespace::FragmentInfo > &fragment_info, const Data_Namespace::MemoryLevel effective_memory_level, const int device_id, std::vector< std::shared_ptr< Chunk_NS::Chunk >> &chunks_owner, DeviceAllocator *dev_buff_owner, std::vector< std::shared_ptr< void >> &malloc_owner, Executor *executor, ColumnCacheMap *column_cache)
Definition: HashJoin.cpp:54
unsigned long long CUdeviceptr
Definition: nocuda.h:27
std::vector< std::shared_ptr< HashTable > > hash_tables_for_device_
Definition: HashJoin.h:292
#define UNREACHABLE()
Definition: Logger.h:253
#define CHECK_GE(x, y)
Definition: Logger.h:222
size_t getKeyBufferSize() const noexcept
#define DEBUG_TIMER_NEW_THREAD(parent_thread_id)
Definition: Logger.h:357
bool needs_dictionary_translation(const Analyzer::ColumnVar *inner_col, const Analyzer::Expr *outer_col_expr, const Executor *executor)
size_t getComponentBufferSize() const noexceptoverride
void freeHashBufferMemory()
Definition: HashJoin.h:279
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
size_t hll_size(const T *M, const size_t bitmap_sz_bits)
Definition: HyperLogLog.h:90
#define CHECK_GT(x, y)
Definition: Logger.h:221
const int get_max_rte_scan_table(std::unordered_map< int, llvm::Value * > &scan_idx_to_hash_pos)
int getInnerTableRteIdx() const noexceptoverride
static std::pair< HashType, bool > get(const std::vector< ChunkKey > &key)
std::string to_string(char const *&&v)
virtual void reifyForDevice(const ColumnsForDevice &columns_for_device, const HashType layout, const int device_id, const size_t entry_count, const size_t emitted_keys_count, const logger::ThreadId parent_thread_id)
virtual ColumnsForDevice fetchColumnsForDevice(const std::vector< Fragmenter_Namespace::FragmentInfo > &fragments, const int device_id, DeviceAllocator *dev_buff_owner)
const std::vector< InputTableInfo > & query_infos_
std::pair< std::optional< size_t >, size_t > getApproximateTupleCountFromCache(const HashTableCacheKey &) const
virtual llvm::Value * codegenKey(const CompilationOptions &)
static std::shared_ptr< BaselineJoinHashTable > getInstance(const std::shared_ptr< Analyzer::BinOper > condition, const std::vector< InputTableInfo > &query_infos, const Data_Namespace::MemoryLevel memory_level, const JoinType join_type, const HashType preferred_hash_type, const int device_count, ColumnCacheMap &column_cache, Executor *executor)
Make hash table from an in-flight SQL query&#39;s parse tree etc.
size_t payloadBufferOff() const noexceptoverride
std::vector< InnerOuter > inner_outer_pairs_
const std::vector< JoinColumnTypeInfo > join_column_types
Definition: HashJoin.h:81
void reify(const HashType preferred_layout)
void approximate_distinct_tuples(uint8_t *hll_buffer_all_cpus, const uint32_t b, const size_t padded_size_bytes, const std::vector< JoinColumn > &join_column_per_key, const std::vector< JoinColumnTypeInfo > &type_info_per_key, const int thread_count)
future< Result > async(Fn &&fn, Args &&...args)
HashType getHashType() const noexceptoverride
void copy_to_gpu(Data_Namespace::DataMgr *data_mgr, CUdeviceptr dst, const void *src, const size_t num_bytes, const int device_id)
Definition: GpuMemUtils.cpp:30
const ColumnDescriptor * get_column_descriptor_maybe(const int col_id, const int table_id, const Catalog_Namespace::Catalog &cat)
Definition: Execute.h:218
ColumnCacheMap & column_cache_
#define LL_INT(v)
void copy_from_gpu(Data_Namespace::DataMgr *data_mgr, void *dst, const CUdeviceptr src, const size_t num_bytes, const int device_id)
T * transfer_flat_object_to_gpu(const T &object, CudaAllocator &allocator)
std::vector< Fragmenter_Namespace::FragmentInfo > only_shards_for_device(const std::vector< Fragmenter_Namespace::FragmentInfo > &fragments, const int device_id, const int device_count)
virtual std::pair< size_t, size_t > approximateTupleCount(const std::vector< ColumnsForDevice > &) const
int initHashTableOnGpu(KEY_HANDLER *key_handler, const std::vector< JoinColumn > &join_columns, const HashType layout, const JoinType join_type, const size_t key_component_width, const size_t key_component_count, const size_t keyspace_entry_count, const size_t emitted_keys_count, const int device_id, const Executor *executor)
#define LL_CONTEXT
#define AUTOMATIC_IR_METADATA(CGENSTATE)
static void checkHashJoinReplicationConstraint(const int table_id, const size_t shard_count, const Executor *executor)
Definition: HashJoin.cpp:571
virtual void reifyWithLayout(const HashType layout)
std::unordered_map< int, std::unordered_map< int, std::shared_ptr< const ColumnarResults >>> ColumnCacheMap
HashTable * getHashTableForDevice(const size_t device_id) const
Definition: HashJoin.h:237
#define VLOGGING(n)
Definition: Logger.h:207
const InputTableInfo & get_inner_query_info(const int inner_table_id, const std::vector< InputTableInfo > &query_infos)
std::vector< llvm::Value * > codegen(const Analyzer::Expr *, const bool fetch_columns, const CompilationOptions &)
Definition: IRCodegen.cpp:30
static CompositeKeyInfo getCompositeKeyInfo(const std::vector< InnerOuter > &inner_outer_pairs, const Executor *executor)
Definition: HashJoin.cpp:324
#define CHECK_LT(x, y)
Definition: Logger.h:219
int getInnerTableId() const noexceptoverride
int8_t * alloc(const size_t num_bytes) override
#define LL_BUILDER
std::unique_ptr< BaselineHashTable > getHashTable()
static std::string getHashTypeString(HashType ht) noexcept
Definition: HashJoin.h:134
std::optional< HashType > layout_override_
static std::string toString(const std::string &type, const std::string &layout_type, size_t key_component_count, size_t key_component_width, size_t entry_count, const int8_t *ptr1, const int8_t *ptr2, const int8_t *ptr3, const int8_t *ptr4, size_t buffer_size, bool raw=false)
Decode hash table into a human-readable string.
Definition: HashTable.cpp:226
size_t get_entries_per_device(const size_t total_entries, const size_t shard_count, const size_t device_count, const Data_Namespace::MemoryLevel memory_level)
const Catalog_Namespace::Catalog * catalog_
std::shared_ptr< HashTable > initHashTableOnCpuFromCache(const HashTableCacheKey &)
uint64_t ThreadId
Definition: Logger.h:345
const Data_Namespace::MemoryLevel memory_level_
llvm::Value * hashPtr(const size_t index)
ThreadId thread_id()
Definition: Logger.cpp:791
void allocateDeviceMemory(const HashType layout, const size_t key_component_width, const size_t key_component_count, const size_t keyspace_entry_count, const size_t emitted_keys_count, const int device_id, const Executor *executor)
virtual int initHashTableForDevice(const std::vector< JoinColumn > &join_columns, const std::vector< JoinColumnTypeInfo > &join_column_types, const std::vector< JoinBucketInfo > &join_buckets, const HashType layout, const Data_Namespace::MemoryLevel effective_memory_level, const size_t entry_count, const size_t emitted_keys_count, const int device_id)
void approximate_distinct_tuples_on_device(uint8_t *hll_buffer, const uint32_t b, const GenericKeyHandler *key_handler, const int64_t num_elems)
static std::vector< InnerOuter > normalizeColumnPairs(const Analyzer::BinOper *condition, const Catalog_Namespace::Catalog &cat, const TemporaryTables *temporary_tables)
Definition: HashJoin.cpp:728
ColumnType get_join_column_type_kind(const SQLTypeInfo &ti)
llvm::Value * codegenSlot(const CompilationOptions &, const size_t) override
#define CHECK(condition)
Definition: Logger.h:209
T * transfer_vector_of_flat_objects_to_gpu(const std::vector< T > &vec, CudaAllocator &allocator)
#define DEBUG_TIMER(name)
Definition: Logger.h:352
Definition: sqldefs.h:31
BaselineJoinHashTable(const std::shared_ptr< Analyzer::BinOper > condition, const JoinType join_type, const std::vector< InputTableInfo > &query_infos, const Data_Namespace::MemoryLevel memory_level, ColumnCacheMap &column_cache, Executor *executor, const std::vector< InnerOuter > &inner_outer_pairs, const int device_count)
virtual size_t getKeyComponentCount() const
int64_t inline_fixed_encoding_null_val(const SQL_TYPE_INFO &ti)
virtual size_t getKeyComponentWidth() const
static DecodedJoinHashBufferSet toSet(size_t key_component_count, size_t key_component_width, size_t entry_count, const int8_t *ptr1, const int8_t *ptr2, const int8_t *ptr3, const int8_t *ptr4, size_t buffer_size)
Decode hash table into a std::set for easy inspection and validation.
Definition: HashTable.cpp:139
Allocate GPU memory using GpuBuffers via DataMgr.
static size_t getShardCountForCondition(const Analyzer::BinOper *condition, const Executor *executor, const std::vector< InnerOuter > &inner_outer_pairs)
static void set(const std::vector< ChunkKey > &key, const HashType hash_type)
std::vector< JoinBucketInfo > join_buckets
Definition: HashJoin.h:83
int cpu_threads()
Definition: thread_count.h:24
size_t get_shard_count(const Analyzer::BinOper *join_condition, const Executor *executor)
Definition: HashJoin.cpp:774
HashType
Definition: HashTable.h:19
const std::vector< JoinColumn > join_columns
Definition: HashJoin.h:80
#define VLOG(n)
Definition: Logger.h:303
static bool layoutRequiresAdditionalBuffers(HashType layout) noexcept
Definition: HashJoin.h:130
const std::shared_ptr< Analyzer::BinOper > condition_
int initHashTableOnCpu(KEY_HANDLER *key_handler, const CompositeKeyInfo &composite_key_info, const std::vector< JoinColumn > &join_columns, const std::vector< JoinColumnTypeInfo > &join_column_types, const std::vector< JoinBucketInfo > &join_bucket_info, const size_t keyspace_entry_count, const size_t keys_for_all_rows, const HashType layout, const JoinType join_type, const size_t key_component_width, const size_t key_component_count)
size_t countBufferOff() const noexceptoverride
const std::vector< ChunkKey > chunk_keys