OmniSciDB  72180abbfe
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
TargetExprBuilder.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2019 OmniSci, 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 
23 #include "TargetExprBuilder.h"
24 
25 #include "CodeGenerator.h"
26 #include "Execute.h"
27 #include "GroupByAndAggregate.h"
28 #include "MaxwellCodegenPatch.h"
30 #include "Shared/Logger.h"
31 
32 #define LL_CONTEXT executor->cgen_state_->context_
33 #define LL_BUILDER executor->cgen_state_->ir_builder_
34 #define LL_BOOL(v) executor->ll_bool(v)
35 #define LL_INT(v) executor->cgen_state_->llInt(v)
36 #define LL_FP(v) executor->cgen_state_->llFp(v)
37 #define ROW_FUNC executor->cgen_state_->row_func_
38 
39 namespace {
40 
41 std::vector<std::string> agg_fn_base_names(const TargetInfo& target_info) {
42  const auto& chosen_type = get_compact_type(target_info);
43  if (!target_info.is_agg || target_info.agg_kind == kSAMPLE) {
44  if (chosen_type.is_geometry()) {
45  return std::vector<std::string>(2 * chosen_type.get_physical_coord_cols(),
46  "agg_id");
47  }
48  if (chosen_type.is_varlen()) {
49  return {"agg_id", "agg_id"};
50  }
51  return {"agg_id"};
52  }
53  switch (target_info.agg_kind) {
54  case kAVG:
55  return {"agg_sum", "agg_count"};
56  case kCOUNT:
57  return {target_info.is_distinct ? "agg_count_distinct" : "agg_count"};
58  case kMAX:
59  return {"agg_max"};
60  case kMIN:
61  return {"agg_min"};
62  case kSUM:
63  return {"agg_sum"};
65  return {"agg_approximate_count_distinct"};
66  case kSINGLE_VALUE:
67  return {"checked_single_agg_id"};
68  case kSAMPLE:
69  return {"agg_id"};
70  default:
71  UNREACHABLE() << "Unrecognized agg kind: " << std::to_string(target_info.agg_kind);
72  }
73  return {};
74 }
75 
77  return query_mem_desc.getQueryDescriptionType() == QueryDescriptionType::Projection &&
78  query_mem_desc.didOutputColumnar();
79 }
80 
81 bool is_simple_count(const TargetInfo& target_info) {
82  return target_info.is_agg && target_info.agg_kind == kCOUNT && !target_info.is_distinct;
83 }
84 
85 bool target_has_geo(const TargetInfo& target_info) {
86  return target_info.is_agg ? target_info.agg_arg_type.is_geometry()
87  : target_info.sql_type.is_geometry();
88 }
89 
90 } // namespace
91 
93  GroupByAndAggregate* group_by_and_agg,
94  Executor* executor,
96  const CompilationOptions& co,
97  const GpuSharedMemoryContext& gpu_smem_context,
98  const std::tuple<llvm::Value*, llvm::Value*>& agg_out_ptr_w_idx_in,
99  const std::vector<llvm::Value*>& agg_out_vec,
100  llvm::Value* output_buffer_byte_stream,
101  llvm::Value* out_row_idx,
102  GroupByAndAggregate::DiamondCodegen& diamond_codegen,
103  GroupByAndAggregate::DiamondCodegen* sample_cfg) const {
104  CHECK(group_by_and_agg);
105  CHECK(executor);
106 
107  auto agg_out_ptr_w_idx = agg_out_ptr_w_idx_in;
108  const auto arg_expr = agg_arg(target_expr);
109 
110  const auto agg_fn_names = agg_fn_base_names(target_info);
111  const auto window_func = dynamic_cast<const Analyzer::WindowFunction*>(target_expr);
113  auto target_lvs =
114  window_func
115  ? std::vector<llvm::Value*>{executor->codegenWindowFunction(target_idx, co)}
116  : group_by_and_agg->codegenAggArg(target_expr, co);
117  const auto window_row_ptr = window_func
118  ? group_by_and_agg->codegenWindowRowPointer(
119  window_func, query_mem_desc, co, diamond_codegen)
120  : nullptr;
121  if (window_row_ptr) {
122  agg_out_ptr_w_idx =
123  std::make_tuple(window_row_ptr, std::get<1>(agg_out_ptr_w_idx_in));
124  if (window_function_is_aggregate(window_func->getKind())) {
125  out_row_idx = window_row_ptr;
126  }
127  }
128 
129  llvm::Value* str_target_lv{nullptr};
130  if (target_lvs.size() == 3 && !target_has_geo(target_info)) {
131  // none encoding string, pop the packed pointer + length since
132  // it's only useful for IS NULL checks and assumed to be only
133  // two components (pointer and length) for the purpose of projection
134  str_target_lv = target_lvs.front();
135  target_lvs.erase(target_lvs.begin());
136  }
138  // Geo cols are expanded to the physical coord cols. Each physical coord col is an
139  // array. Ensure that the target values generated match the number of agg
140  // functions before continuing
141  if (target_lvs.size() < agg_fn_names.size()) {
142  CHECK_EQ(target_lvs.size(), agg_fn_names.size() / 2);
143  std::vector<llvm::Value*> new_target_lvs;
144  new_target_lvs.reserve(agg_fn_names.size());
145  for (const auto& target_lv : target_lvs) {
146  new_target_lvs.push_back(target_lv);
147  new_target_lvs.push_back(target_lv);
148  }
149  target_lvs = new_target_lvs;
150  }
151  }
152  if (target_lvs.size() < agg_fn_names.size()) {
153  CHECK_EQ(size_t(1), target_lvs.size());
154  CHECK_EQ(size_t(2), agg_fn_names.size());
155  for (size_t i = 1; i < agg_fn_names.size(); ++i) {
156  target_lvs.push_back(target_lvs.front());
157  }
158  } else {
160  if (!target_info.is_agg) {
161  CHECK_EQ(static_cast<size_t>(2 * target_info.sql_type.get_physical_coord_cols()),
162  target_lvs.size());
163  CHECK_EQ(agg_fn_names.size(), target_lvs.size());
164  }
165  } else {
166  CHECK(str_target_lv || (agg_fn_names.size() == target_lvs.size()));
167  CHECK(target_lvs.size() == 1 || target_lvs.size() == 2);
168  }
169  }
170 
171  int32_t slot_index = base_slot_index;
172  CHECK_GE(slot_index, 0);
173  CHECK(is_group_by || static_cast<size_t>(slot_index) < agg_out_vec.size());
174 
175  uint32_t col_off{0};
176  if (co.device_type == ExecutorDeviceType::GPU && query_mem_desc.threadsShareMemory() &&
178  (!arg_expr || arg_expr->get_type_info().get_notnull())) {
179  CHECK_EQ(size_t(1), agg_fn_names.size());
180  const auto chosen_bytes = query_mem_desc.getPaddedSlotWidthBytes(slot_index);
181  llvm::Value* agg_col_ptr{nullptr};
182  if (is_group_by) {
183  if (query_mem_desc.didOutputColumnar()) {
184  col_off = query_mem_desc.getColOffInBytes(slot_index);
185  CHECK_EQ(size_t(0), col_off % chosen_bytes);
186  col_off /= chosen_bytes;
187  CHECK(std::get<1>(agg_out_ptr_w_idx));
188  auto offset =
189  LL_BUILDER.CreateAdd(std::get<1>(agg_out_ptr_w_idx), LL_INT(col_off));
190  agg_col_ptr = LL_BUILDER.CreateGEP(
191  LL_BUILDER.CreateBitCast(
192  std::get<0>(agg_out_ptr_w_idx),
193  llvm::PointerType::get(get_int_type((chosen_bytes << 3), LL_CONTEXT), 0)),
194  offset);
195  } else {
196  col_off = query_mem_desc.getColOnlyOffInBytes(slot_index);
197  CHECK_EQ(size_t(0), col_off % chosen_bytes);
198  col_off /= chosen_bytes;
199  agg_col_ptr = LL_BUILDER.CreateGEP(
200  LL_BUILDER.CreateBitCast(
201  std::get<0>(agg_out_ptr_w_idx),
202  llvm::PointerType::get(get_int_type((chosen_bytes << 3), LL_CONTEXT), 0)),
203  LL_INT(col_off));
204  }
205  }
206 
207  if (chosen_bytes != sizeof(int32_t)) {
208  CHECK_EQ(8, chosen_bytes);
209  if (g_bigint_count) {
210  const auto acc_i64 = LL_BUILDER.CreateBitCast(
211  is_group_by ? agg_col_ptr : agg_out_vec[slot_index],
212  llvm::PointerType::get(get_int_type(64, LL_CONTEXT), 0));
213  if (gpu_smem_context.isSharedMemoryUsed()) {
214  group_by_and_agg->emitCall(
215  "agg_count_shared", std::vector<llvm::Value*>{acc_i64, LL_INT(int64_t(1))});
216  } else {
217  LL_BUILDER.CreateAtomicRMW(llvm::AtomicRMWInst::Add,
218  acc_i64,
219  LL_INT(int64_t(1)),
220  llvm::AtomicOrdering::Monotonic);
221  }
222  } else {
223  auto acc_i32 = LL_BUILDER.CreateBitCast(
224  is_group_by ? agg_col_ptr : agg_out_vec[slot_index],
225  llvm::PointerType::get(get_int_type(32, LL_CONTEXT), 0));
226  if (gpu_smem_context.isSharedMemoryUsed()) {
227  acc_i32 = LL_BUILDER.CreatePointerCast(
228  acc_i32, llvm::Type::getInt32PtrTy(LL_CONTEXT, 3));
229  }
230  LL_BUILDER.CreateAtomicRMW(llvm::AtomicRMWInst::Add,
231  acc_i32,
232  LL_INT(1),
233  llvm::AtomicOrdering::Monotonic);
234  }
235  } else {
236  const auto acc_i32 = (is_group_by ? agg_col_ptr : agg_out_vec[slot_index]);
237  if (gpu_smem_context.isSharedMemoryUsed()) {
238  // Atomic operation on address space level 3 (Shared):
239  const auto shared_acc_i32 = LL_BUILDER.CreatePointerCast(
240  acc_i32, llvm::Type::getInt32PtrTy(LL_CONTEXT, 3));
241  LL_BUILDER.CreateAtomicRMW(llvm::AtomicRMWInst::Add,
242  shared_acc_i32,
243  LL_INT(1),
244  llvm::AtomicOrdering::Monotonic);
245  } else {
246  LL_BUILDER.CreateAtomicRMW(llvm::AtomicRMWInst::Add,
247  acc_i32,
248  LL_INT(1),
249  llvm::AtomicOrdering::Monotonic);
250  }
251  }
252  return;
253  }
254 
255  codegenAggregate(group_by_and_agg,
256  executor,
257  query_mem_desc,
258  co,
259  target_lvs,
260  agg_out_ptr_w_idx,
261  agg_out_vec,
262  output_buffer_byte_stream,
263  out_row_idx,
264  slot_index);
265 }
266 
268  GroupByAndAggregate* group_by_and_agg,
269  Executor* executor,
271  const CompilationOptions& co,
272  const std::vector<llvm::Value*>& target_lvs,
273  const std::tuple<llvm::Value*, llvm::Value*>& agg_out_ptr_w_idx,
274  const std::vector<llvm::Value*>& agg_out_vec,
275  llvm::Value* output_buffer_byte_stream,
276  llvm::Value* out_row_idx,
277  int32_t slot_index) const {
278  size_t target_lv_idx = 0;
279  const bool lazy_fetched{executor->plan_state_->isLazyFetchColumn(target_expr)};
280 
281  CodeGenerator code_generator(executor);
282 
283  const auto agg_fn_names = agg_fn_base_names(target_info);
284  auto arg_expr = agg_arg(target_expr);
285 
286  for (const auto& agg_base_name : agg_fn_names) {
287  if (target_info.is_distinct && arg_expr->get_type_info().is_array()) {
288  CHECK_EQ(static_cast<size_t>(query_mem_desc.getLogicalSlotWidthBytes(slot_index)),
289  sizeof(int64_t));
290  // TODO(miyu): check if buffer may be columnar here
291  CHECK(!query_mem_desc.didOutputColumnar());
292  const auto& elem_ti = arg_expr->get_type_info().get_elem_type();
293  uint32_t col_off{0};
294  if (is_group_by) {
295  const auto col_off_in_bytes = query_mem_desc.getColOnlyOffInBytes(slot_index);
296  CHECK_EQ(size_t(0), col_off_in_bytes % sizeof(int64_t));
297  col_off /= sizeof(int64_t);
298  }
299  executor->cgen_state_->emitExternalCall(
300  "agg_count_distinct_array_" + numeric_type_name(elem_ti),
301  llvm::Type::getVoidTy(LL_CONTEXT),
302  {is_group_by
303  ? LL_BUILDER.CreateGEP(std::get<0>(agg_out_ptr_w_idx), LL_INT(col_off))
304  : agg_out_vec[slot_index],
305  target_lvs[target_lv_idx],
306  code_generator.posArg(arg_expr),
307  elem_ti.is_fp()
308  ? static_cast<llvm::Value*>(executor->cgen_state_->inlineFpNull(elem_ti))
309  : static_cast<llvm::Value*>(
310  executor->cgen_state_->inlineIntNull(elem_ti))});
311  ++slot_index;
312  ++target_lv_idx;
313  continue;
314  }
315 
316  llvm::Value* agg_col_ptr{nullptr};
317  const auto chosen_bytes =
318  static_cast<size_t>(query_mem_desc.getPaddedSlotWidthBytes(slot_index));
319  const auto& chosen_type = get_compact_type(target_info);
320  const auto& arg_type =
321  ((arg_expr && arg_expr->get_type_info().get_type() != kNULLT) &&
325  const bool is_fp_arg =
326  !lazy_fetched && arg_type.get_type() != kNULLT && arg_type.is_fp();
327  if (is_group_by) {
328  agg_col_ptr = group_by_and_agg->codegenAggColumnPtr(output_buffer_byte_stream,
329  out_row_idx,
330  agg_out_ptr_w_idx,
331  query_mem_desc,
332  chosen_bytes,
333  slot_index,
334  target_idx);
335  CHECK(agg_col_ptr);
336  agg_col_ptr->setName("agg_col_ptr");
337  }
338 
339  const bool float_argument_input = takes_float_argument(target_info);
340  const bool is_count_in_avg = target_info.agg_kind == kAVG && target_lv_idx == 1;
341  // The count component of an average should never be compacted.
342  const auto agg_chosen_bytes =
343  float_argument_input && !is_count_in_avg ? sizeof(float) : chosen_bytes;
344  if (float_argument_input) {
345  CHECK_GE(chosen_bytes, sizeof(float));
346  }
347 
348  auto target_lv = target_lvs[target_lv_idx];
349  const auto needs_unnest_double_patch = group_by_and_agg->needsUnnestDoublePatch(
350  target_lv, agg_base_name, query_mem_desc.threadsShareMemory(), co);
351  const auto need_skip_null = !needs_unnest_double_patch && target_info.skip_null_val;
352  if (!needs_unnest_double_patch) {
353  if (need_skip_null && !is_agg_domain_range_equivalent(target_info.agg_kind)) {
354  target_lv = group_by_and_agg->convertNullIfAny(arg_type, target_info, target_lv);
355  } else if (is_fp_arg) {
356  target_lv = executor->castToFP(target_lv);
357  }
358  if (!dynamic_cast<const Analyzer::AggExpr*>(target_expr) || arg_expr) {
359  target_lv =
360  executor->cgen_state_->castToTypeIn(target_lv, (agg_chosen_bytes << 3));
361  }
362  }
363 
364  const bool is_simple_count_target = is_simple_count(target_info);
365  llvm::Value* str_target_lv{nullptr};
366  if (target_lvs.size() == 3 && !target_has_geo(target_info)) {
367  // none encoding string
368  str_target_lv = target_lvs.front();
369  }
370  std::vector<llvm::Value*> agg_args{
371  executor->castToIntPtrTyIn((is_group_by ? agg_col_ptr : agg_out_vec[slot_index]),
372  (agg_chosen_bytes << 3)),
373  (is_simple_count_target && !arg_expr)
374  ? (agg_chosen_bytes == sizeof(int32_t) ? LL_INT(int32_t(0))
375  : LL_INT(int64_t(0)))
376  : (is_simple_count_target && arg_expr && str_target_lv ? str_target_lv
377  : target_lv)};
378  if (query_mem_desc.isLogicalSizedColumnsAllowed()) {
379  if (is_simple_count_target && arg_expr && str_target_lv) {
380  agg_args[1] =
381  agg_chosen_bytes == sizeof(int32_t) ? LL_INT(int32_t(0)) : LL_INT(int64_t(0));
382  }
383  }
384  std::string agg_fname{agg_base_name};
385  if (is_fp_arg) {
386  if (!lazy_fetched) {
387  if (agg_chosen_bytes == sizeof(float)) {
388  CHECK_EQ(arg_type.get_type(), kFLOAT);
389  agg_fname += "_float";
390  } else {
391  CHECK_EQ(agg_chosen_bytes, sizeof(double));
392  agg_fname += "_double";
393  }
394  }
395  } else if (agg_chosen_bytes == sizeof(int32_t)) {
396  agg_fname += "_int32";
397  } else if (agg_chosen_bytes == sizeof(int16_t) &&
398  query_mem_desc.didOutputColumnar()) {
399  agg_fname += "_int16";
400  } else if (agg_chosen_bytes == sizeof(int8_t) && query_mem_desc.didOutputColumnar()) {
401  agg_fname += "_int8";
402  }
403 
405  CHECK_EQ(agg_chosen_bytes, sizeof(int64_t));
406  CHECK(!chosen_type.is_fp());
407  group_by_and_agg->codegenCountDistinct(
408  target_idx, target_expr, agg_args, query_mem_desc, co.device_type);
409  } else {
410  const auto& arg_ti = target_info.agg_arg_type;
411  if (need_skip_null && !arg_ti.is_geometry()) {
412  agg_fname += "_skip_val";
413  }
414 
416  (need_skip_null && !arg_ti.is_geometry())) {
417  llvm::Value* null_in_lv{nullptr};
418  if (arg_ti.is_fp()) {
419  null_in_lv =
420  static_cast<llvm::Value*>(executor->cgen_state_->inlineFpNull(arg_ti));
421  } else {
422  null_in_lv = static_cast<llvm::Value*>(executor->cgen_state_->inlineIntNull(
424  ? arg_ti
425  : target_info.sql_type));
426  }
427  CHECK(null_in_lv);
428  auto null_lv =
429  executor->cgen_state_->castToTypeIn(null_in_lv, (agg_chosen_bytes << 3));
430  agg_args.push_back(null_lv);
431  }
432  if (!target_info.is_distinct) {
434  query_mem_desc.threadsShareMemory()) {
435  agg_fname += "_shared";
436  if (needs_unnest_double_patch) {
437  agg_fname = patch_agg_fname(agg_fname);
438  }
439  }
440  auto agg_fname_call_ret_lv = group_by_and_agg->emitCall(agg_fname, agg_args);
441 
442  if (agg_fname.find("checked") != std::string::npos) {
443  group_by_and_agg->checkErrorCode(agg_fname_call_ret_lv);
444  }
445  }
446  }
447  const auto window_func = dynamic_cast<const Analyzer::WindowFunction*>(target_expr);
448  if (window_func && window_function_requires_peer_handling(window_func)) {
449  const auto window_func_context =
451  const auto pending_outputs =
452  LL_INT(window_func_context->aggregateStatePendingOutputs());
453  executor->cgen_state_->emitExternalCall("add_window_pending_output",
454  llvm::Type::getVoidTy(LL_CONTEXT),
455  {agg_args.front(), pending_outputs});
456  const auto& window_func_ti = window_func->get_type_info();
457  std::string apply_window_pending_outputs_name = "apply_window_pending_outputs";
458  switch (window_func_ti.get_type()) {
459  case kFLOAT: {
460  apply_window_pending_outputs_name += "_float";
461  if (query_mem_desc.didOutputColumnar()) {
462  apply_window_pending_outputs_name += "_columnar";
463  }
464  break;
465  }
466  case kDOUBLE: {
467  apply_window_pending_outputs_name += "_double";
468  break;
469  }
470  default: {
471  apply_window_pending_outputs_name += "_int";
472  if (query_mem_desc.didOutputColumnar()) {
473  apply_window_pending_outputs_name +=
474  std::to_string(window_func_ti.get_size() * 8);
475  } else {
476  apply_window_pending_outputs_name += "64";
477  }
478  break;
479  }
480  }
481  const auto partition_end =
482  LL_INT(reinterpret_cast<int64_t>(window_func_context->partitionEnd()));
483  executor->cgen_state_->emitExternalCall(apply_window_pending_outputs_name,
484  llvm::Type::getVoidTy(LL_CONTEXT),
485  {pending_outputs,
486  target_lvs.front(),
487  partition_end,
488  code_generator.posArg(nullptr)});
489  }
490 
491  ++slot_index;
492  ++target_lv_idx;
493  }
494 }
495 
497  const Executor* executor,
498  const CompilationOptions& co) {
499  if (query_mem_desc.getPaddedSlotWidthBytes(slot_index_counter) == 0) {
500  CHECK(!dynamic_cast<const Analyzer::AggExpr*>(target_expr));
501  ++slot_index_counter;
502  ++target_index_counter;
503  return;
504  }
505  if (dynamic_cast<const Analyzer::UOper*>(target_expr) &&
506  static_cast<const Analyzer::UOper*>(target_expr)->get_optype() == kUNNEST) {
507  throw std::runtime_error("UNNEST not supported in the projection list yet.");
508  }
509  if ((executor->plan_state_->isLazyFetchColumn(target_expr) || !is_group_by) &&
510  (static_cast<size_t>(query_mem_desc.getPaddedSlotWidthBytes(slot_index_counter)) <
511  sizeof(int64_t)) &&
512  !is_columnar_projection(query_mem_desc)) {
513  // TODO(miyu): enable different byte width in the layout w/o padding
515  }
516 
517  auto target_info = get_target_info(target_expr, g_bigint_count);
518  auto arg_expr = agg_arg(target_expr);
519  if (arg_expr) {
521  target_info.skip_null_val = false;
522  } else if (query_mem_desc.getQueryDescriptionType() ==
524  !arg_expr->get_type_info().is_varlen()) {
525  // TODO: COUNT is currently not null-aware for varlen types. Need to add proper code
526  // generation for handling varlen nulls.
527  target_info.skip_null_val = true;
528  } else if (constrained_not_null(arg_expr, ra_exe_unit.quals)) {
529  target_info.skip_null_val = false;
530  }
531  }
532 
533  if (!(query_mem_desc.getQueryDescriptionType() ==
537  sample_exprs_to_codegen.emplace_back(target_expr,
538  target_info,
539  slot_index_counter,
540  target_index_counter++,
541  is_group_by);
542  } else {
543  target_exprs_to_codegen.emplace_back(target_expr,
544  target_info,
545  slot_index_counter,
546  target_index_counter++,
547  is_group_by);
548  }
549 
550  const auto agg_fn_names = agg_fn_base_names(target_info);
551  slot_index_counter += agg_fn_names.size();
552 }
553 
554 namespace {
555 
557  const QueryMemoryDescriptor& query_mem_desc) {
558  const bool is_group_by{query_mem_desc.isGroupBy()};
559  if (target_info.agg_kind == kSAMPLE && target_info.sql_type.is_string() &&
560  target_info.sql_type.get_compression() != kENCODING_NONE) {
561  return get_agg_initial_val(target_info.agg_kind,
562  target_info.sql_type,
563  is_group_by,
564  query_mem_desc.getCompactByteWidth());
565  }
566  return 0;
567 }
568 
569 } // namespace
570 
572  GroupByAndAggregate* group_by_and_agg,
573  Executor* executor,
574  const QueryMemoryDescriptor& query_mem_desc,
575  const CompilationOptions& co,
576  const GpuSharedMemoryContext& gpu_smem_context,
577  const std::tuple<llvm::Value*, llvm::Value*>& agg_out_ptr_w_idx,
578  const std::vector<llvm::Value*>& agg_out_vec,
579  llvm::Value* output_buffer_byte_stream,
580  llvm::Value* out_row_idx,
581  GroupByAndAggregate::DiamondCodegen& diamond_codegen) const {
582  CHECK(group_by_and_agg);
583  CHECK(executor);
584 
585  for (const auto& target_expr_codegen : target_exprs_to_codegen) {
586  target_expr_codegen.codegen(group_by_and_agg,
587  executor,
588  query_mem_desc,
589  co,
590  gpu_smem_context,
591  agg_out_ptr_w_idx,
592  agg_out_vec,
593  output_buffer_byte_stream,
594  out_row_idx,
595  diamond_codegen);
596  }
597  if (!sample_exprs_to_codegen.empty()) {
598  codegenSampleExpressions(group_by_and_agg,
599  executor,
600  query_mem_desc,
601  co,
602  agg_out_ptr_w_idx,
603  agg_out_vec,
604  output_buffer_byte_stream,
605  out_row_idx,
606  diamond_codegen);
607  }
608 }
609 
611  GroupByAndAggregate* group_by_and_agg,
612  Executor* executor,
613  const QueryMemoryDescriptor& query_mem_desc,
614  const CompilationOptions& co,
615  const std::tuple<llvm::Value*, llvm::Value*>& agg_out_ptr_w_idx,
616  const std::vector<llvm::Value*>& agg_out_vec,
617  llvm::Value* output_buffer_byte_stream,
618  llvm::Value* out_row_idx,
619  GroupByAndAggregate::DiamondCodegen& diamond_codegen) const {
620  CHECK(!sample_exprs_to_codegen.empty());
622  if (sample_exprs_to_codegen.size() == 1 &&
623  !sample_exprs_to_codegen.front().target_info.sql_type.is_varlen()) {
624  codegenSingleSlotSampleExpression(group_by_and_agg,
625  executor,
626  query_mem_desc,
627  co,
628  agg_out_ptr_w_idx,
629  agg_out_vec,
630  output_buffer_byte_stream,
631  out_row_idx,
632  diamond_codegen);
633  } else {
634  codegenMultiSlotSampleExpressions(group_by_and_agg,
635  executor,
636  query_mem_desc,
637  co,
638  agg_out_ptr_w_idx,
639  agg_out_vec,
640  output_buffer_byte_stream,
641  out_row_idx,
642  diamond_codegen);
643  }
644 }
645 
647  GroupByAndAggregate* group_by_and_agg,
648  Executor* executor,
649  const QueryMemoryDescriptor& query_mem_desc,
650  const CompilationOptions& co,
651  const std::tuple<llvm::Value*, llvm::Value*>& agg_out_ptr_w_idx,
652  const std::vector<llvm::Value*>& agg_out_vec,
653  llvm::Value* output_buffer_byte_stream,
654  llvm::Value* out_row_idx,
655  GroupByAndAggregate::DiamondCodegen& diamond_codegen) const {
656  CHECK_EQ(size_t(1), sample_exprs_to_codegen.size());
657  CHECK(!sample_exprs_to_codegen.front().target_info.sql_type.is_varlen());
659  // no need for the atomic if we only have one SAMPLE target
660  sample_exprs_to_codegen.front().codegen(group_by_and_agg,
661  executor,
662  query_mem_desc,
663  co,
664  {},
665  agg_out_ptr_w_idx,
666  agg_out_vec,
667  output_buffer_byte_stream,
668  out_row_idx,
669  diamond_codegen);
670 }
671 
673  GroupByAndAggregate* group_by_and_agg,
674  Executor* executor,
675  const QueryMemoryDescriptor& query_mem_desc,
676  const CompilationOptions& co,
677  const std::tuple<llvm::Value*, llvm::Value*>& agg_out_ptr_w_idx,
678  const std::vector<llvm::Value*>& agg_out_vec,
679  llvm::Value* output_buffer_byte_stream,
680  llvm::Value* out_row_idx,
681  GroupByAndAggregate::DiamondCodegen& diamond_codegen) const {
682  CHECK(sample_exprs_to_codegen.size() > 1 ||
683  sample_exprs_to_codegen.front().target_info.sql_type.is_varlen());
685  const auto& first_sample_expr = sample_exprs_to_codegen.front();
686  auto target_lvs = group_by_and_agg->codegenAggArg(first_sample_expr.target_expr, co);
687  CHECK_GE(target_lvs.size(), size_t(1));
688 
689  const auto init_val =
690  get_initial_agg_val(first_sample_expr.target_info, query_mem_desc);
691 
692  llvm::Value* agg_col_ptr{nullptr};
693  if (is_group_by) {
694  const auto agg_column_size_bytes =
695  query_mem_desc.isLogicalSizedColumnsAllowed() &&
696  !first_sample_expr.target_info.sql_type.is_varlen()
697  ? first_sample_expr.target_info.sql_type.get_size()
698  : sizeof(int64_t);
699  agg_col_ptr = group_by_and_agg->codegenAggColumnPtr(output_buffer_byte_stream,
700  out_row_idx,
701  agg_out_ptr_w_idx,
702  query_mem_desc,
703  agg_column_size_bytes,
704  first_sample_expr.base_slot_index,
705  first_sample_expr.target_idx);
706  } else {
707  CHECK_LT(static_cast<size_t>(first_sample_expr.base_slot_index), agg_out_vec.size());
708  agg_col_ptr =
709  executor->castToIntPtrTyIn(agg_out_vec[first_sample_expr.base_slot_index], 64);
710  }
711 
712  auto sample_cas_lv = codegenSlotEmptyKey(agg_col_ptr, target_lvs, executor, init_val);
713 
715  sample_cas_lv, executor, false, "sample_valcheck", &diamond_codegen, false);
716 
717  for (const auto& target_expr_codegen : sample_exprs_to_codegen) {
718  target_expr_codegen.codegen(group_by_and_agg,
719  executor,
720  query_mem_desc,
721  co,
722  {},
723  agg_out_ptr_w_idx,
724  agg_out_vec,
725  output_buffer_byte_stream,
726  out_row_idx,
727  diamond_codegen,
728  &sample_cfg);
729  }
730 }
731 
733  llvm::Value* agg_col_ptr,
734  std::vector<llvm::Value*>& target_lvs,
735  Executor* executor,
736  const int64_t init_val) const {
737  const auto& first_sample_expr = sample_exprs_to_codegen.front();
738  const auto first_sample_slot_bytes =
739  first_sample_expr.target_info.sql_type.is_varlen()
740  ? sizeof(int64_t)
741  : first_sample_expr.target_info.sql_type.get_size();
742  llvm::Value* target_lv_casted{nullptr};
743  // deciding whether proper casting is required for the first sample's slot:
744  if (first_sample_expr.target_info.sql_type.is_varlen()) {
745  target_lv_casted =
746  LL_BUILDER.CreatePtrToInt(target_lvs.front(), llvm::Type::getInt64Ty(LL_CONTEXT));
747  } else if (first_sample_expr.target_info.sql_type.is_fp()) {
748  // Initialization value for SAMPLE on a float column should be 0
749  CHECK_EQ(init_val, 0);
750  if (query_mem_desc.isLogicalSizedColumnsAllowed()) {
751  target_lv_casted = executor->cgen_state_->ir_builder_.CreateFPToSI(
752  target_lvs.front(),
753  first_sample_slot_bytes == sizeof(float) ? llvm::Type::getInt32Ty(LL_CONTEXT)
754  : llvm::Type::getInt64Ty(LL_CONTEXT));
755  } else {
756  target_lv_casted = executor->cgen_state_->ir_builder_.CreateFPToSI(
757  target_lvs.front(), llvm::Type::getInt64Ty(LL_CONTEXT));
758  }
759  } else if (first_sample_slot_bytes != sizeof(int64_t) &&
760  !query_mem_desc.isLogicalSizedColumnsAllowed()) {
761  target_lv_casted =
762  executor->cgen_state_->ir_builder_.CreateCast(llvm::Instruction::CastOps::SExt,
763  target_lvs.front(),
764  llvm::Type::getInt64Ty(LL_CONTEXT));
765  } else {
766  target_lv_casted = target_lvs.front();
767  }
768 
769  std::string slot_empty_cas_func_name("slotEmptyKeyCAS");
770  llvm::Value* init_val_lv{LL_INT(init_val)};
771  if (query_mem_desc.isLogicalSizedColumnsAllowed() &&
772  !first_sample_expr.target_info.sql_type.is_varlen()) {
773  // add proper suffix to the function name:
774  switch (first_sample_slot_bytes) {
775  case 1:
776  slot_empty_cas_func_name += "_int8";
777  break;
778  case 2:
779  slot_empty_cas_func_name += "_int16";
780  break;
781  case 4:
782  slot_empty_cas_func_name += "_int32";
783  break;
784  case 8:
785  break;
786  default:
787  UNREACHABLE() << "Invalid slot size for slotEmptyKeyCAS function.";
788  break;
789  }
790  if (first_sample_slot_bytes != sizeof(int64_t)) {
791  init_val_lv = llvm::ConstantInt::get(
792  get_int_type(first_sample_slot_bytes * 8, LL_CONTEXT), init_val);
793  }
794  }
795 
796  auto sample_cas_lv = executor->cgen_state_->emitExternalCall(
797  slot_empty_cas_func_name,
798  llvm::Type::getInt1Ty(executor->cgen_state_->context_),
799  {agg_col_ptr, target_lv_casted, init_val_lv});
800  return sample_cas_lv;
801 }
#define LL_BUILDER
const Analyzer::Expr * agg_arg(const Analyzer::Expr *expr)
#define CHECK_EQ(x, y)
Definition: Logger.h:205
bool target_has_geo(const TargetInfo &target_info)
bool constrained_not_null(const Analyzer::Expr *expr, const std::list< std::shared_ptr< Analyzer::Expr >> &quals)
void codegenAggregate(GroupByAndAggregate *group_by_and_agg, Executor *executor, const QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const std::vector< llvm::Value * > &target_lvs, const std::tuple< llvm::Value *, llvm::Value * > &agg_out_ptr_w_idx, const std::vector< llvm::Value * > &agg_out_vec, llvm::Value *output_buffer_byte_stream, llvm::Value *out_row_idx, int32_t slot_index) const
std::vector< std::string > agg_fn_base_names(const TargetInfo &target_info)
llvm::Value * codegenAggColumnPtr(llvm::Value *output_buffer_byte_stream, llvm::Value *out_row_idx, const std::tuple< llvm::Value *, llvm::Value * > &agg_out_ptr_w_idx, const QueryMemoryDescriptor &query_mem_desc, const size_t chosen_bytes, const size_t agg_out_off, const size_t target_idx)
: returns the pointer to where the aggregation should be stored.
void codegenSampleExpressions(GroupByAndAggregate *group_by_and_agg, Executor *executor, const QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const std::tuple< llvm::Value *, llvm::Value * > &agg_out_ptr_w_idx, const std::vector< llvm::Value * > &agg_out_vec, llvm::Value *output_buffer_byte_stream, llvm::Value *out_row_idx, GroupByAndAggregate::DiamondCodegen &diamond_codegen) const
bool isLogicalSizedColumnsAllowed() const
SQLTypeInfo sql_type
Definition: TargetInfo.h:42
TargetInfo get_target_info(const PointerType target_expr, const bool bigint_count)
Definition: TargetInfo.h:66
void codegen(GroupByAndAggregate *group_by_and_agg, Executor *executor, const QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const GpuSharedMemoryContext &gpu_smem_context, const std::tuple< llvm::Value *, llvm::Value * > &agg_out_ptr_w_idx, const std::vector< llvm::Value * > &agg_out_vec, llvm::Value *output_buffer_byte_stream, llvm::Value *out_row_idx, GroupByAndAggregate::DiamondCodegen &diamond_codegen, GroupByAndAggregate::DiamondCodegen *sample_cfg=nullptr) const
void codegen(GroupByAndAggregate *group_by_and_agg, Executor *executor, const QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const GpuSharedMemoryContext &gpu_smem_context, const std::tuple< llvm::Value *, llvm::Value * > &agg_out_ptr_w_idx, const std::vector< llvm::Value * > &agg_out_vec, llvm::Value *output_buffer_byte_stream, llvm::Value *out_row_idx, GroupByAndAggregate::DiamondCodegen &diamond_codegen) const
llvm::Value * posArg(const Analyzer::Expr *) const
Definition: ColumnIR.cpp:507
#define UNREACHABLE()
Definition: Logger.h:241
#define CHECK_GE(x, y)
Definition: Logger.h:210
llvm::Value * emitCall(const std::string &fname, const std::vector< llvm::Value * > &args)
int64_t get_agg_initial_val(const SQLAgg agg, const SQLTypeInfo &ti, const bool enable_compaction, const unsigned min_byte_width_to_compact)
void checkErrorCode(llvm::Value *retCode)
bool needsUnnestDoublePatch(llvm::Value *val_ptr, const std::string &agg_base_name, const bool threads_share_memory, const CompilationOptions &co) const
bool takes_float_argument(const TargetInfo &target_info)
Definition: TargetInfo.h:121
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:257
bool skip_null_val
Definition: TargetInfo.h:44
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
static WindowFunctionContext * getActiveWindowFunctionContext(Executor *executor)
std::string to_string(char const *&&v)
SQLTypeInfo agg_arg_type
Definition: TargetInfo.h:43
llvm::Value * codegenSlotEmptyKey(llvm::Value *agg_col_ptr, std::vector< llvm::Value * > &target_lvs, Executor *executor, const int64_t init_val) const
std::string patch_agg_fname(const std::string &agg_name)
Helpers for codegen of target expressions.
void codegenSingleSlotSampleExpression(GroupByAndAggregate *group_by_and_agg, Executor *executor, const QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const std::tuple< llvm::Value *, llvm::Value * > &agg_out_ptr_w_idx, const std::vector< llvm::Value * > &agg_out_vec, llvm::Value *output_buffer_byte_stream, llvm::Value *out_row_idx, GroupByAndAggregate::DiamondCodegen &diamond_codegen) const
size_t getColOnlyOffInBytes(const size_t col_idx) const
Definition: sqldefs.h:73
const SQLTypeInfo get_compact_type(const TargetInfo &target)
bool is_agg
Definition: TargetInfo.h:40
CHECK(cgen_state)
#define LL_INT(v)
llvm::Value * convertNullIfAny(const SQLTypeInfo &arg_type, const TargetInfo &agg_info, llvm::Value *target)
bool g_bigint_count
Definition: sqldefs.h:75
#define LL_CONTEXT
bool is_distinct_target(const TargetInfo &target_info)
Definition: TargetInfo.h:117
void codegenCountDistinct(const size_t target_idx, const Analyzer::Expr *target_expr, std::vector< llvm::Value * > &agg_args, const QueryMemoryDescriptor &, const ExecutorDeviceType)
const int8_t getPaddedSlotWidthBytes(const size_t slot_idx) const
SQLAgg agg_kind
Definition: TargetInfo.h:41
QueryDescriptionType getQueryDescriptionType() const
ExecutorDeviceType device_type
bool window_function_is_aggregate(const SqlWindowFunctionKind kind)
Definition: WindowContext.h:42
#define CHECK_LT(x, y)
Definition: Logger.h:207
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:265
const Analyzer::Expr * target_expr
Definition: sqldefs.h:76
std::vector< llvm::Value * > codegenAggArg(const Analyzer::Expr *target_expr, const CompilationOptions &co)
llvm::Value * codegenWindowRowPointer(const Analyzer::WindowFunction *window_func, const QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, DiamondCodegen &diamond_codegen)
bool window_function_requires_peer_handling(const Analyzer::WindowFunction *window_func)
void codegenMultiSlotSampleExpressions(GroupByAndAggregate *group_by_and_agg, Executor *executor, const QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const std::tuple< llvm::Value *, llvm::Value * > &agg_out_ptr_w_idx, const std::vector< llvm::Value * > &agg_out_vec, llvm::Value *output_buffer_byte_stream, llvm::Value *out_row_idx, GroupByAndAggregate::DiamondCodegen &diamond_codegen) const
bool is_simple_count(const TargetInfo &target_info)
bool is_geometry() const
Definition: sqltypes.h:420
static void resetWindowFunctionContext(Executor *executor)
int64_t get_initial_agg_val(const TargetInfo &target_info, const QueryMemoryDescriptor &query_mem_desc)
std::string numeric_type_name(const SQLTypeInfo &ti)
Definition: Execute.h:137
bool is_string() const
Definition: sqltypes.h:408
bool is_distinct
Definition: TargetInfo.h:45
void operator()(const Analyzer::Expr *target_expr, const Executor *executor, const CompilationOptions &co)
Definition: sqldefs.h:74
const int8_t getLogicalSlotWidthBytes(const size_t slot_idx) const
int get_physical_coord_cols() const
Definition: sqltypes.h:293
Definition: sqldefs.h:72
size_t getColOffInBytes(const size_t col_idx) const
bool is_columnar_projection(const QueryMemoryDescriptor &query_mem_desc)
bool is_agg_domain_range_equivalent(const SQLAgg &agg_kind)
Definition: TargetInfo.h:52