This repository was archived by the owner on May 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathExecute.cpp
4128 lines (3853 loc) · 165 KB
/
Execute.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2021 OmniSci, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "QueryEngine/Execute.h"
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#ifdef HAVE_CUDA
#include <cuda.h>
#endif // HAVE_CUDA
#include <chrono>
#include <ctime>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <numeric>
#include <thread>
#include "CudaMgr/CudaMgr.h"
#include "DataMgr/BufferMgr/BufferMgr.h"
#include "DataProvider/DictDescriptor.h"
#include "OSDependent/omnisci_path.h"
#include "QueryEngine/AggregateUtils.h"
#include "QueryEngine/AggregatedColRange.h"
#include "QueryEngine/CodeGenerator.h"
#include "QueryEngine/ColumnFetcher.h"
#include "QueryEngine/CostModel/DummyCostModel.h"
#include "QueryEngine/Descriptors/QueryCompilationDescriptor.h"
#include "QueryEngine/Descriptors/QueryFragmentDescriptor.h"
#include "QueryEngine/Dispatchers/DefaultExecutionPolicy.h"
#include "QueryEngine/Dispatchers/ProportionBasedExecutionPolicy.h"
#include "QueryEngine/Dispatchers/RRExecutionPolicy.h"
#include "QueryEngine/DynamicWatchdog.h"
#include "QueryEngine/EquiJoinCondition.h"
#include "QueryEngine/ErrorHandling.h"
#include "QueryEngine/ExecutionKernel.h"
#include "QueryEngine/ExpressionRewrite.h"
#include "QueryEngine/ExternalCacheInvalidators.h"
#include "QueryEngine/GpuMemUtils.h"
#include "QueryEngine/InPlaceSort.h"
#include "QueryEngine/JoinHashTable/BaselineJoinHashTable.h"
#include "QueryEngine/JsonAccessors.h"
#include "QueryEngine/OutputBufferInitialization.h"
#include "QueryEngine/QueryRewrite.h"
#include "QueryEngine/QueryTemplateGenerator.h"
#include "QueryEngine/ResultSetReductionJIT.h"
#include "QueryEngine/RuntimeFunctions.h"
#include "QueryEngine/SpeculativeTopN.h"
#include "QueryEngine/StringDictionaryGenerations.h"
#include "QueryEngine/TableFunctions/TableFunctionCompilationContext.h"
#include "QueryEngine/TableFunctions/TableFunctionExecutionContext.h"
#include "QueryEngine/Visitors/TransientStringLiteralsVisitor.h"
#include "Shared/SystemParameters.h"
#include "Shared/checked_alloc.h"
#include "Shared/measure.h"
#include "Shared/misc.h"
#include "Shared/scope.h"
#include "Shared/threading.h"
#include "ThirdParty/robin_hood.h"
using namespace std::string_literals;
extern std::unique_ptr<llvm::Module> udf_gpu_module;
extern std::unique_ptr<llvm::Module> udf_cpu_module;
bool g_enable_table_functions{false};
unsigned g_pending_query_interrupt_freq{1000};
bool g_is_test_env{false}; // operating under a unit test environment. Currently only
// limits the allocation for the output buffer arena
// and data recycler test
size_t g_approx_quantile_buffer{1000};
size_t g_approx_quantile_centroids{300};
size_t g_max_log_length{500};
extern bool g_cache_string_hash;
int const Executor::max_gpu_count;
const int32_t Executor::ERR_SINGLE_VALUE_FOUND_MULTIPLE_VALUES;
std::map<ExtModuleKinds, std::string> Executor::extension_module_sources;
extern std::unique_ptr<llvm::Module> read_llvm_module_from_bc_file(
const std::string& udf_ir_filename,
llvm::LLVMContext& ctx);
extern std::unique_ptr<llvm::Module> read_llvm_module_from_ir_file(
const std::string& udf_ir_filename,
llvm::LLVMContext& ctx,
bool is_gpu = false);
extern std::unique_ptr<llvm::Module> read_llvm_module_from_ir_string(
const std::string& udf_ir_string,
llvm::LLVMContext& ctx,
bool is_gpu = false);
std::unique_ptr<CodeCacheAccessor<CpuCompilationContext>> Executor::s_stubs_accessor;
std::unique_ptr<CodeCacheAccessor<CpuCompilationContext>> Executor::s_code_accessor;
std::unique_ptr<CodeCacheAccessor<CpuCompilationContext>> Executor::cpu_code_accessor;
std::unique_ptr<CodeCacheAccessor<CompilationContext>> Executor::gpu_code_accessor;
size_t Executor::code_cache_size;
namespace {
void init_code_caches() {
Executor::s_stubs_accessor = std::make_unique<CodeCacheAccessor<CpuCompilationContext>>(
Executor::code_cache_size, "s_stubs_cache");
Executor::s_code_accessor = std::make_unique<CodeCacheAccessor<CpuCompilationContext>>(
Executor::code_cache_size, "s_code_cache");
Executor::cpu_code_accessor =
std::make_unique<CodeCacheAccessor<CpuCompilationContext>>(
Executor::code_cache_size, "cpu_code_cache");
Executor::gpu_code_accessor = std::make_unique<CodeCacheAccessor<CompilationContext>>(
Executor::code_cache_size, "gpu_code_cache");
}
} // namespace
/**
* Flushes and re-initializes the code caches. Any cached references will be dropped. The
* re-initialized code caches will be empty, allowing for higher-level buffer mgrs to be
* torn down. If code caches are used, this must be called before the DataMgr global is
* destroyed at exit.
*/
void Executor::resetCodeCache() {
s_stubs_accessor.reset();
s_code_accessor.reset();
cpu_code_accessor.reset();
gpu_code_accessor.reset();
init_code_caches();
}
Executor::Executor(const ExecutorId executor_id,
Data_Namespace::DataMgr* data_mgr,
BufferProvider* buffer_provider,
ConfigPtr config,
const size_t max_gpu_slab_size,
const std::string& debug_dir,
const std::string& debug_file)
: executor_id_(executor_id)
, context_(new llvm::LLVMContext())
, config_(config)
, block_size_x_(config->exec.override_gpu_block_size)
, grid_size_x_(config->exec.override_gpu_grid_size)
, max_gpu_slab_size_(max_gpu_slab_size)
, debug_dir_(debug_dir)
, debug_file_(debug_file)
, data_mgr_(data_mgr)
, buffer_provider_(buffer_provider)
, temporary_tables_(nullptr)
, input_table_info_cache_(this)
, thread_id_(logger::thread_id()) {
if (executor_id_ > INVALID_EXECUTOR_ID - 1) {
throw std::runtime_error("Too many executors!");
}
extension_module_context_ = std::make_unique<ExtensionModuleContext>();
cgen_state_ = std::make_unique<CgenState>(
0, false, false, extension_module_context_.get(), getContext());
std::call_once(first_init_flag_, [this]() {
query_plan_dag_cache_ =
std::make_unique<QueryPlanDagCache>(config_->cache.dag_cache_size);
code_cache_size = config_->cache.code_cache_size;
init_code_caches();
});
Executor::initialize_extension_module_sources();
update_extension_modules();
}
void Executor::initialize_extension_module_sources() {
if (Executor::extension_module_sources.find(ExtModuleKinds::template_module) ==
Executor::extension_module_sources.end()) {
auto root_path = omnisci::get_root_abs_path();
auto template_path = root_path + "/QueryEngine/RuntimeFunctions.bc";
CHECK(boost::filesystem::exists(template_path)) << template_path;
Executor::extension_module_sources[ExtModuleKinds::template_module] = template_path;
#ifdef HAVE_CUDA
auto rt_libdevice_path = get_cuda_home() + "/nvvm/libdevice/libdevice.10.bc";
if (boost::filesystem::exists(rt_libdevice_path)) {
Executor::extension_module_sources[ExtModuleKinds::rt_libdevice_module] =
rt_libdevice_path;
} else {
LOG(WARNING) << "File " << rt_libdevice_path
<< " does not exist; support for some UDF "
"functions might not be available.";
}
#endif
#ifdef HAVE_L0
auto l0_template_path = root_path + "/QueryEngine/RuntimeFunctionsL0.bc";
CHECK(boost::filesystem::exists(l0_template_path));
Executor::extension_module_sources[ExtModuleKinds::l0_template_module] =
l0_template_path;
auto genx_path = root_path + "/QueryEngine/genx.bc";
CHECK(boost::filesystem::exists(genx_path));
Executor::extension_module_sources[ExtModuleKinds::spirv_helper_funcs_module] =
genx_path;
#endif
}
}
void Executor::reset(const bool discard_runtime_modules_only) {
// TODO: keep cached results that do not depend on runtime UDF/UDTFs
s_code_accessor->clear();
s_stubs_accessor->clear();
cpu_code_accessor->clear();
gpu_code_accessor->clear();
CHECK(extension_module_context_);
extension_module_context_->clear(discard_runtime_modules_only);
if (discard_runtime_modules_only) {
cgen_state_->module_ = nullptr;
} else {
cgen_state_.reset();
context_.reset(new llvm::LLVMContext());
cgen_state_.reset(
new CgenState({}, false, false, getExtensionModuleContext(), getContext()));
}
}
void Executor::update_extension_modules(bool update_runtime_modules_only) {
auto read_module = [&](ExtModuleKinds module_kind, const std::string& source) {
/*
source can be either a filename of a LLVM IR
or LLVM BC source, or a string containing
LLVM IR code.
*/
CHECK(!source.empty());
switch (module_kind) {
case ExtModuleKinds::template_module:
case ExtModuleKinds::l0_template_module:
case ExtModuleKinds::spirv_helper_funcs_module:
case ExtModuleKinds::rt_libdevice_module: {
return read_llvm_module_from_bc_file(source, getContext());
}
case ExtModuleKinds::udf_cpu_module: {
return read_llvm_module_from_ir_file(source, getContext(), /**is_gpu=*/false);
}
case ExtModuleKinds::udf_gpu_module: {
return read_llvm_module_from_ir_file(source, getContext(), /**is_gpu=*/true);
}
case ExtModuleKinds::rt_udf_cpu_module: {
return read_llvm_module_from_ir_string(source, getContext(), /**is_gpu=*/false);
}
case ExtModuleKinds::rt_udf_gpu_module: {
return read_llvm_module_from_ir_string(source, getContext(), /**is_gpu=*/true);
}
default: {
UNREACHABLE();
return std::unique_ptr<llvm::Module>();
}
}
};
auto update_module = [&](ExtModuleKinds module_kind, bool erase_not_found = false) {
CHECK(extension_module_context_);
auto& extension_modules = extension_module_context_->getExtensionModules();
auto it = Executor::extension_module_sources.find(module_kind);
if (it != Executor::extension_module_sources.end()) {
auto llvm_module = read_module(module_kind, it->second);
if (llvm_module) {
extension_modules[module_kind] = std::move(llvm_module);
} else if (erase_not_found) {
extension_modules.erase(module_kind);
} else {
if (extension_modules.find(module_kind) == extension_modules.end()) {
LOG(WARNING) << "Failed to update " << ::toString(module_kind)
<< " LLVM module. The module will be unavailable.";
} else {
LOG(WARNING) << "Failed to update " << ::toString(module_kind)
<< " LLVM module. Using the existing module.";
}
}
} else {
if (erase_not_found) {
extension_modules.erase(module_kind);
} else {
if (extension_modules.find(module_kind) == extension_modules.end()) {
LOG(WARNING) << "Source of " << ::toString(module_kind)
<< " LLVM module is unavailable. The module will be unavailable.";
} else {
LOG(WARNING) << "Source of " << ::toString(module_kind)
<< " LLVM module is unavailable. Using the existing module.";
}
}
}
};
if (!update_runtime_modules_only) {
// required compile-time modules, their requirements are enforced
// by Executor::initialize_extension_module_sources():
update_module(ExtModuleKinds::template_module);
// load-time modules, these are optional:
update_module(ExtModuleKinds::udf_cpu_module, true);
#ifdef HAVE_CUDA
update_module(ExtModuleKinds::udf_gpu_module, true);
update_module(ExtModuleKinds::rt_libdevice_module);
#endif
#ifdef HAVE_L0
update_module(ExtModuleKinds::l0_template_module);
update_module(ExtModuleKinds::spirv_helper_funcs_module);
#endif
}
// run-time modules, these are optional and erasable:
update_module(ExtModuleKinds::rt_udf_cpu_module, true);
#ifdef HAVE_CUDA
update_module(ExtModuleKinds::rt_udf_gpu_module, true);
#endif
}
// Used by StubGenerator::generateStub
Executor::CgenStateManager::CgenStateManager(Executor& executor)
: executor_(executor)
, lock_queue_clock_(timer_start())
, lock_(executor_.compilation_mutex_)
, cgen_state_(std::move(executor_.cgen_state_)) // store old CgenState instance
{
executor_.compilation_queue_time_ms_ += timer_stop(lock_queue_clock_);
executor_.cgen_state_.reset(
new CgenState(0,
false,
executor.getConfig().debug.enable_automatic_ir_metadata,
executor.getExtensionModuleContext(),
executor.getContext()));
}
Executor::CgenStateManager::CgenStateManager(
Executor& executor,
const bool allow_lazy_fetch,
const std::vector<InputTableInfo>& query_infos,
const RelAlgExecutionUnit* ra_exe_unit)
: executor_(executor)
, lock_queue_clock_(timer_start())
, lock_(executor_.compilation_mutex_)
, cgen_state_(std::move(executor_.cgen_state_)) // store old CgenState instance
{
executor_.compilation_queue_time_ms_ += timer_stop(lock_queue_clock_);
// nukeOldState creates new CgenState and PlanState instances for
// the subsequent code generation. It also resets
// kernel_queue_time_ms_ and compilation_queue_time_ms_ that we do
// not currently restore.. should we accumulate these timings?
executor_.nukeOldState(allow_lazy_fetch, query_infos, ra_exe_unit);
}
Executor::CgenStateManager::~CgenStateManager() {
// prevent memory leak from hoisted literals
for (auto& p : executor_.cgen_state_->row_func_hoisted_literals_) {
auto inst = llvm::dyn_cast<llvm::LoadInst>(p.first);
if (inst && inst->getNumUses() == 0 && inst->getParent() == nullptr) {
// The llvm::Value instance stored in p.first is created by the
// CodeGenerator::codegenHoistedConstantsPlaceholders method.
p.first->deleteValue();
}
}
executor_.cgen_state_->row_func_hoisted_literals_.clear();
// move generated StringDictionaryTranslationMgrs and InValueBitmaps
// to the old CgenState instance as the execution of the generated
// code uses these bitmaps
for (auto& str_dict_translation_mgr :
executor_.cgen_state_->str_dict_translation_mgrs_) {
cgen_state_->moveStringDictionaryTranslationMgr(std::move(str_dict_translation_mgr));
}
executor_.cgen_state_->str_dict_translation_mgrs_.clear();
for (auto& bm : executor_.cgen_state_->in_values_bitmaps_) {
cgen_state_->moveInValuesBitmap(bm);
}
executor_.cgen_state_->in_values_bitmaps_.clear();
// restore the old CgenState instance
executor_.cgen_state_.reset(cgen_state_.release());
}
std::shared_ptr<Executor> Executor::getExecutor(
Data_Namespace::DataMgr* data_mgr,
BufferProvider* buffer_provider,
ConfigPtr config,
const std::string& debug_dir,
const std::string& debug_file,
const SystemParameters& system_parameters) {
INJECT_TIMER(getExecutor);
if (!config) {
config = std::make_shared<Config>();
}
return std::make_shared<Executor>(executor_id_ctr_++,
data_mgr,
buffer_provider,
config,
system_parameters.max_gpu_slab_size,
debug_dir,
debug_file);
}
void Executor::clearMemory(const Data_Namespace::MemoryLevel memory_level,
Data_Namespace::DataMgr* data_mgr) {
switch (memory_level) {
case Data_Namespace::MemoryLevel::CPU_LEVEL:
case Data_Namespace::MemoryLevel::GPU_LEVEL: {
mapd_unique_lock<mapd_shared_mutex> flush_lock(
execute_mutex_); // Don't flush memory while queries are running
CHECK(data_mgr);
data_mgr->clearMemory(memory_level);
if (memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
// The hash table cache uses CPU memory not managed by the buffer manager. In the
// future, we should manage these allocations with the buffer manager directly.
// For now, assume the user wants to purge the hash table cache when they clear
// CPU memory (currently used in ExecuteTest to lower memory pressure)
JoinHashTableCacheInvalidator::invalidateCaches();
}
break;
}
default: {
throw std::runtime_error(
"Clearing memory levels other than the CPU level or GPU level is not "
"supported.");
}
}
}
size_t Executor::getArenaBlockSize() {
return g_is_test_env ? 100000000 : (1UL << 32) + kArenaBlockOverhead;
}
StringDictionaryProxy* Executor::getStringDictionaryProxy(
const int dict_id_in,
std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
const bool with_generation) const {
CHECK(row_set_mem_owner);
std::lock_guard<std::mutex> lock(
str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
return row_set_mem_owner->getOrAddStringDictProxy(dict_id_in, with_generation);
}
StringDictionaryProxy* RowSetMemoryOwner::getOrAddStringDictProxy(
const int dict_id_in,
const bool with_generation) {
const int dict_id{dict_id_in < 0 ? REGULAR_DICT(dict_id_in) : dict_id_in};
CHECK(data_provider_);
const auto dd = data_provider_->getDictMetadata(dict_id);
if (dd) {
CHECK(dd->stringDict);
CHECK_LE(dd->dictNBits, 32);
const int64_t generation =
with_generation ? string_dictionary_generations_.getGeneration(dict_id) : -1;
return addStringDict(dd->stringDict, dict_id, generation);
}
CHECK_EQ(dict_id, DictRef::literalsDictId);
if (!lit_str_dict_proxy_) {
DictRef literal_dict_ref(DictRef::invalidDbId, DictRef::literalsDictId);
std::shared_ptr<StringDictionary> tsd = std::make_shared<StringDictionary>(
literal_dict_ref, "", false, true, g_cache_string_hash);
lit_str_dict_proxy_ =
std::make_shared<StringDictionaryProxy>(tsd, literal_dict_ref.dictId, 0);
}
return lit_str_dict_proxy_.get();
}
const StringDictionaryProxy::IdMap* Executor::getStringProxyTranslationMap(
const int source_dict_id,
const int dest_dict_id,
const RowSetMemoryOwner::StringTranslationType translation_type,
std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
const bool with_generation) const {
CHECK(row_set_mem_owner);
std::lock_guard<std::mutex> lock(
str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
return row_set_mem_owner->getOrAddStringProxyTranslationMap(
source_dict_id, dest_dict_id, with_generation, translation_type);
}
const StringDictionaryProxy::IdMap* Executor::getIntersectionStringProxyTranslationMap(
const StringDictionaryProxy* source_proxy,
const StringDictionaryProxy* dest_proxy,
std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner) const {
CHECK(row_set_mem_owner);
std::lock_guard<std::mutex> lock(
str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
return row_set_mem_owner->addStringProxyIntersectionTranslationMap(source_proxy,
dest_proxy);
}
const StringDictionaryProxy::IdMap* RowSetMemoryOwner::getOrAddStringProxyTranslationMap(
const int source_dict_id_in,
const int dest_dict_id_in,
const bool with_generation,
const RowSetMemoryOwner::StringTranslationType translation_type) {
const auto source_proxy = getOrAddStringDictProxy(source_dict_id_in, with_generation);
auto dest_proxy = getOrAddStringDictProxy(dest_dict_id_in, with_generation);
if (translation_type == RowSetMemoryOwner::StringTranslationType::SOURCE_INTERSECTION) {
return addStringProxyIntersectionTranslationMap(source_proxy, dest_proxy);
} else {
return addStringProxyUnionTranslationMap(source_proxy, dest_proxy);
}
}
quantile::TDigest* RowSetMemoryOwner::nullTDigest(double const q) {
std::lock_guard<std::mutex> lock(state_mutex_);
return t_digests_
.emplace_back(std::make_unique<quantile::TDigest>(
q, this, g_approx_quantile_buffer, g_approx_quantile_centroids))
.get();
}
bool Executor::isCPUOnly() const {
CHECK(data_mgr_);
return !data_mgr_->getCudaMgr();
}
const std::shared_ptr<RowSetMemoryOwner> Executor::getRowSetMemoryOwner() const {
return row_set_mem_owner_;
}
const TemporaryTables* Executor::getTemporaryTables() const {
return temporary_tables_;
}
TableFragmentsInfo Executor::getTableInfo(const int db_id, const int table_id) const {
return input_table_info_cache_.getTableInfo(db_id, table_id);
}
const TableGeneration& Executor::getTableGeneration(const int table_id) const {
return table_generations_.getGeneration(table_id);
}
ExpressionRange Executor::getColRange(const PhysicalInput& phys_input) const {
return agg_col_range_cache_.getColRange(phys_input);
}
size_t Executor::getNumBytesForFetchedRow(const std::set<int>& table_ids_to_fetch) const {
size_t num_bytes = 0;
if (!plan_state_) {
return 0;
}
for (const auto& fetched_col : plan_state_->columns_to_fetch_) {
int table_id = fetched_col.getTableId();
if (table_ids_to_fetch.count(table_id) == 0) {
continue;
}
if (table_id < 0) {
num_bytes += 8;
} else {
const auto sz = fetched_col.type()->size();
if (sz < 0) {
// for varlen types, only account for the pointer/size for each row, for now
num_bytes += 16;
} else {
num_bytes += sz;
}
}
}
return num_bytes;
}
bool Executor::hasLazyFetchColumns(
const std::vector<const hdk::ir::Expr*>& target_exprs) const {
CHECK(plan_state_);
for (const auto target_expr : target_exprs) {
if (plan_state_->isLazyFetchColumn(target_expr)) {
return true;
}
}
return false;
}
std::vector<ColumnLazyFetchInfo> Executor::getColLazyFetchInfo(
const std::vector<const hdk::ir::Expr*>& target_exprs) const {
CHECK(plan_state_);
std::vector<ColumnLazyFetchInfo> col_lazy_fetch_info;
for (const auto target_expr : target_exprs) {
if (!plan_state_->isLazyFetchColumn(target_expr)) {
col_lazy_fetch_info.emplace_back(ColumnLazyFetchInfo{false, -1, nullptr});
} else {
const auto col_var = dynamic_cast<const hdk::ir::ColumnVar*>(target_expr);
CHECK(col_var);
auto local_col_id = plan_state_->getLocalColumnId(col_var, false);
auto col_type = col_var->type();
col_lazy_fetch_info.emplace_back(ColumnLazyFetchInfo{true, local_col_id, col_type});
}
}
return col_lazy_fetch_info;
}
void Executor::clearMetaInfoCache() {
input_table_info_cache_.clear();
agg_col_range_cache_.clear();
table_generations_.clear();
}
std::vector<int8_t> Executor::serializeLiterals(
const std::unordered_map<int, CgenState::LiteralValues>& literals,
const int device_id) {
if (literals.empty()) {
return {};
}
const auto dev_literals_it = literals.find(device_id);
CHECK(dev_literals_it != literals.end());
const auto& dev_literals = dev_literals_it->second;
size_t lit_buf_size{0};
std::vector<std::string> real_strings;
std::vector<std::vector<double>> double_array_literals;
std::vector<std::vector<int8_t>> align64_int8_array_literals;
std::vector<std::vector<int32_t>> int32_array_literals;
std::vector<std::vector<int8_t>> align32_int8_array_literals;
std::vector<std::vector<int8_t>> int8_array_literals;
for (const auto& lit : dev_literals) {
lit_buf_size = CgenState::addAligned(lit_buf_size, CgenState::literalBytes(lit));
if (lit.which() == 7) {
const auto p = boost::get<std::string>(&lit);
CHECK(p);
real_strings.push_back(*p);
} else if (lit.which() == 8) {
const auto p = boost::get<std::vector<double>>(&lit);
CHECK(p);
double_array_literals.push_back(*p);
} else if (lit.which() == 9) {
const auto p = boost::get<std::vector<int32_t>>(&lit);
CHECK(p);
int32_array_literals.push_back(*p);
} else if (lit.which() == 10) {
const auto p = boost::get<std::vector<int8_t>>(&lit);
CHECK(p);
int8_array_literals.push_back(*p);
} else if (lit.which() == 11) {
const auto p = boost::get<std::pair<std::vector<int8_t>, int>>(&lit);
CHECK(p);
if (p->second == 64) {
align64_int8_array_literals.push_back(p->first);
} else if (p->second == 32) {
align32_int8_array_literals.push_back(p->first);
} else {
CHECK(false);
}
}
}
if (lit_buf_size > static_cast<size_t>(std::numeric_limits<int16_t>::max())) {
throw TooManyLiterals();
}
int16_t crt_real_str_off = lit_buf_size;
for (const auto& real_str : real_strings) {
CHECK_LE(real_str.size(), static_cast<size_t>(std::numeric_limits<int16_t>::max()));
lit_buf_size += real_str.size();
}
if (double_array_literals.size() > 0) {
lit_buf_size = align(lit_buf_size, sizeof(double));
}
int16_t crt_double_arr_lit_off = lit_buf_size;
for (const auto& double_array_literal : double_array_literals) {
CHECK_LE(double_array_literal.size(),
static_cast<size_t>(std::numeric_limits<int16_t>::max()));
lit_buf_size += double_array_literal.size() * sizeof(double);
}
if (align64_int8_array_literals.size() > 0) {
lit_buf_size = align(lit_buf_size, sizeof(uint64_t));
}
int16_t crt_align64_int8_arr_lit_off = lit_buf_size;
for (const auto& align64_int8_array_literal : align64_int8_array_literals) {
CHECK_LE(align64_int8_array_literals.size(),
static_cast<size_t>(std::numeric_limits<int16_t>::max()));
lit_buf_size += align64_int8_array_literal.size();
}
if (int32_array_literals.size() > 0) {
lit_buf_size = align(lit_buf_size, sizeof(int32_t));
}
int16_t crt_int32_arr_lit_off = lit_buf_size;
for (const auto& int32_array_literal : int32_array_literals) {
CHECK_LE(int32_array_literal.size(),
static_cast<size_t>(std::numeric_limits<int16_t>::max()));
lit_buf_size += int32_array_literal.size() * sizeof(int32_t);
}
if (align32_int8_array_literals.size() > 0) {
lit_buf_size = align(lit_buf_size, sizeof(int32_t));
}
int16_t crt_align32_int8_arr_lit_off = lit_buf_size;
for (const auto& align32_int8_array_literal : align32_int8_array_literals) {
CHECK_LE(align32_int8_array_literals.size(),
static_cast<size_t>(std::numeric_limits<int16_t>::max()));
lit_buf_size += align32_int8_array_literal.size();
}
int16_t crt_int8_arr_lit_off = lit_buf_size;
for (const auto& int8_array_literal : int8_array_literals) {
CHECK_LE(int8_array_literal.size(),
static_cast<size_t>(std::numeric_limits<int16_t>::max()));
lit_buf_size += int8_array_literal.size();
}
unsigned crt_real_str_idx = 0;
unsigned crt_double_arr_lit_idx = 0;
unsigned crt_align64_int8_arr_lit_idx = 0;
unsigned crt_int32_arr_lit_idx = 0;
unsigned crt_align32_int8_arr_lit_idx = 0;
unsigned crt_int8_arr_lit_idx = 0;
std::vector<int8_t> serialized(lit_buf_size);
size_t off{0};
for (const auto& lit : dev_literals) {
const auto lit_bytes = CgenState::literalBytes(lit);
off = CgenState::addAligned(off, lit_bytes);
switch (lit.which()) {
case 0: {
const auto p = boost::get<int8_t>(&lit);
CHECK(p);
serialized[off - lit_bytes] = *p;
break;
}
case 1: {
const auto p = boost::get<int16_t>(&lit);
CHECK(p);
memcpy(&serialized[off - lit_bytes], p, lit_bytes);
break;
}
case 2: {
const auto p = boost::get<int32_t>(&lit);
CHECK(p);
memcpy(&serialized[off - lit_bytes], p, lit_bytes);
break;
}
case 3: {
const auto p = boost::get<int64_t>(&lit);
CHECK(p);
memcpy(&serialized[off - lit_bytes], p, lit_bytes);
break;
}
case 4: {
const auto p = boost::get<float>(&lit);
CHECK(p);
memcpy(&serialized[off - lit_bytes], p, lit_bytes);
break;
}
case 5: {
const auto p = boost::get<double>(&lit);
CHECK(p);
memcpy(&serialized[off - lit_bytes], p, lit_bytes);
break;
}
case 6: {
const auto p = boost::get<std::pair<std::string, int>>(&lit);
CHECK(p);
const auto str_id =
(config_->exec.enable_experimental_string_functions ||
// With WorkUnitBuilder we might produce complex expressions where encoded
// literals are decoded back to plain strings. In this case, we cannot use
// INVALID_STR_ID and should add the literal to the dictionary.
config_->exec.use_legacy_work_unit_builder)
? getStringDictionaryProxy(p->second, row_set_mem_owner_, true)
->getIdOfString(p->first)
: getStringDictionaryProxy(p->second, row_set_mem_owner_, true)
->getOrAddTransient(p->first);
memcpy(&serialized[off - lit_bytes], &str_id, lit_bytes);
break;
}
case 7: {
const auto p = boost::get<std::string>(&lit);
CHECK(p);
int32_t off_and_len = crt_real_str_off << 16;
const auto& crt_real_str = real_strings[crt_real_str_idx];
off_and_len |= static_cast<int16_t>(crt_real_str.size());
memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
memcpy(&serialized[crt_real_str_off], crt_real_str.data(), crt_real_str.size());
++crt_real_str_idx;
crt_real_str_off += crt_real_str.size();
break;
}
case 8: {
const auto p = boost::get<std::vector<double>>(&lit);
CHECK(p);
int32_t off_and_len = crt_double_arr_lit_off << 16;
const auto& crt_double_arr_lit = double_array_literals[crt_double_arr_lit_idx];
int32_t len = crt_double_arr_lit.size();
CHECK_EQ((len >> 16), 0);
off_and_len |= static_cast<int16_t>(len);
int32_t double_array_bytesize = len * sizeof(double);
memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
memcpy(&serialized[crt_double_arr_lit_off],
crt_double_arr_lit.data(),
double_array_bytesize);
++crt_double_arr_lit_idx;
crt_double_arr_lit_off += double_array_bytesize;
break;
}
case 9: {
const auto p = boost::get<std::vector<int32_t>>(&lit);
CHECK(p);
int32_t off_and_len = crt_int32_arr_lit_off << 16;
const auto& crt_int32_arr_lit = int32_array_literals[crt_int32_arr_lit_idx];
int32_t len = crt_int32_arr_lit.size();
CHECK_EQ((len >> 16), 0);
off_and_len |= static_cast<int16_t>(len);
int32_t int32_array_bytesize = len * sizeof(int32_t);
memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
memcpy(&serialized[crt_int32_arr_lit_off],
crt_int32_arr_lit.data(),
int32_array_bytesize);
++crt_int32_arr_lit_idx;
crt_int32_arr_lit_off += int32_array_bytesize;
break;
}
case 10: {
const auto p = boost::get<std::vector<int8_t>>(&lit);
CHECK(p);
int32_t off_and_len = crt_int8_arr_lit_off << 16;
const auto& crt_int8_arr_lit = int8_array_literals[crt_int8_arr_lit_idx];
int32_t len = crt_int8_arr_lit.size();
CHECK_EQ((len >> 16), 0);
off_and_len |= static_cast<int16_t>(len);
int32_t int8_array_bytesize = len;
memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
memcpy(&serialized[crt_int8_arr_lit_off],
crt_int8_arr_lit.data(),
int8_array_bytesize);
++crt_int8_arr_lit_idx;
crt_int8_arr_lit_off += int8_array_bytesize;
break;
}
case 11: {
const auto p = boost::get<std::pair<std::vector<int8_t>, int>>(&lit);
CHECK(p);
if (p->second == 64) {
int32_t off_and_len = crt_align64_int8_arr_lit_off << 16;
const auto& crt_align64_int8_arr_lit =
align64_int8_array_literals[crt_align64_int8_arr_lit_idx];
int32_t len = crt_align64_int8_arr_lit.size();
CHECK_EQ((len >> 16), 0);
off_and_len |= static_cast<int16_t>(len);
int32_t align64_int8_array_bytesize = len;
memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
memcpy(&serialized[crt_align64_int8_arr_lit_off],
crt_align64_int8_arr_lit.data(),
align64_int8_array_bytesize);
++crt_align64_int8_arr_lit_idx;
crt_align64_int8_arr_lit_off += align64_int8_array_bytesize;
} else if (p->second == 32) {
int32_t off_and_len = crt_align32_int8_arr_lit_off << 16;
const auto& crt_align32_int8_arr_lit =
align32_int8_array_literals[crt_align32_int8_arr_lit_idx];
int32_t len = crt_align32_int8_arr_lit.size();
CHECK_EQ((len >> 16), 0);
off_and_len |= static_cast<int16_t>(len);
int32_t align32_int8_array_bytesize = len;
memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
memcpy(&serialized[crt_align32_int8_arr_lit_off],
crt_align32_int8_arr_lit.data(),
align32_int8_array_bytesize);
++crt_align32_int8_arr_lit_idx;
crt_align32_int8_arr_lit_off += align32_int8_array_bytesize;
} else {
CHECK(false);
}
break;
}
default:
CHECK(false);
}
}
return serialized;
}
int Executor::deviceCount(const ExecutorDeviceType device_type) const {
if (device_type == ExecutorDeviceType::GPU) {
return gpuMgr()->getDeviceCount();
} else {
return 1;
}
}
int Executor::deviceCountForMemoryLevel(
const Data_Namespace::MemoryLevel memory_level) const {
return memory_level == GPU_LEVEL ? deviceCount(ExecutorDeviceType::GPU)
: deviceCount(ExecutorDeviceType::CPU);
}
// TODO(alex): remove or split
std::pair<int64_t, int32_t> Executor::reduceResults(hdk::ir::AggType agg,
const hdk::ir::Type* type,
const int64_t agg_init_val,
const int8_t out_byte_width,
const int64_t* out_vec,
const size_t out_vec_sz,
const bool is_group_by,
const bool float_argument_input) {
switch (agg) {
case hdk::ir::AggType::kAvg:
case hdk::ir::AggType::kSum:
if (0 != agg_init_val) {
if (type->isInteger() || type->isDecimal() || type->isDateTime() ||
type->isBoolean()) {
int64_t agg_result = agg_init_val;
for (size_t i = 0; i < out_vec_sz; ++i) {
agg_sum_skip_val(&agg_result, out_vec[i], agg_init_val);
}
return {agg_result, 0};
} else {
CHECK(type->isFloatingPoint());
switch (out_byte_width) {
case 4: {
int agg_result = static_cast<int32_t>(agg_init_val);
for (size_t i = 0; i < out_vec_sz; ++i) {
agg_sum_float_skip_val(
&agg_result,
*reinterpret_cast<const float*>(may_alias_ptr(&out_vec[i])),
*reinterpret_cast<const float*>(may_alias_ptr(&agg_init_val)));
}
const int64_t converted_bin =
float_argument_input
? static_cast<int64_t>(agg_result)
: float_to_double_bin(static_cast<int32_t>(agg_result), true);
return {converted_bin, 0};
break;
}
case 8: {
int64_t agg_result = agg_init_val;
for (size_t i = 0; i < out_vec_sz; ++i) {
agg_sum_double_skip_val(
&agg_result,
*reinterpret_cast<const double*>(may_alias_ptr(&out_vec[i])),
*reinterpret_cast<const double*>(may_alias_ptr(&agg_init_val)));
}
return {agg_result, 0};
break;
}
default:
CHECK(false);
}
}
}
if (type->isInteger() || type->isDecimal() || type->isDateTime()) {
int64_t agg_result = 0;
for (size_t i = 0; i < out_vec_sz; ++i) {
agg_result += out_vec[i];
}
return {agg_result, 0};
} else {
CHECK(type->isFloatingPoint());
switch (out_byte_width) {
case 4: {
float r = 0.;
for (size_t i = 0; i < out_vec_sz; ++i) {
r += *reinterpret_cast<const float*>(may_alias_ptr(&out_vec[i]));
}
const auto float_bin = *reinterpret_cast<const int32_t*>(may_alias_ptr(&r));
const int64_t converted_bin =
float_argument_input ? float_bin : float_to_double_bin(float_bin, true);
return {converted_bin, 0};
}
case 8: {
double r = 0.;
for (size_t i = 0; i < out_vec_sz; ++i) {
r += *reinterpret_cast<const double*>(may_alias_ptr(&out_vec[i]));
}
return {*reinterpret_cast<const int64_t*>(may_alias_ptr(&r)), 0};
}
default:
CHECK(false);
}
}
break;
case hdk::ir::AggType::kCount: {
uint64_t agg_result = 0;
for (size_t i = 0; i < out_vec_sz; ++i) {
const uint64_t out = static_cast<uint64_t>(out_vec[i]);
agg_result += out;
}
return {static_cast<int64_t>(agg_result), 0};
}
case hdk::ir::AggType::kMin: {
if (type->isInteger() || type->isDecimal() || type->isDateTime() ||
type->isBoolean()) {
int64_t agg_result = agg_init_val;
for (size_t i = 0; i < out_vec_sz; ++i) {
agg_min_skip_val(&agg_result, out_vec[i], agg_init_val);
}
return {agg_result, 0};
} else {
switch (out_byte_width) {
case 4: {
int32_t agg_result = static_cast<int32_t>(agg_init_val);
for (size_t i = 0; i < out_vec_sz; ++i) {
agg_min_float_skip_val(
&agg_result,
*reinterpret_cast<const float*>(may_alias_ptr(&out_vec[i])),
*reinterpret_cast<const float*>(may_alias_ptr(&agg_init_val)));
}