OmniSciDB  72c90bc290
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
IRCodegen.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, 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 
17 #include "../Parser/ParserNode.h"
18 #include "CodeGenerator.h"
19 #include "Execute.h"
20 #include "ExternalExecutor.h"
21 #include "MaxwellCodegenPatch.h"
22 #include "RelAlgTranslator.h"
23 
25 
26 // Driver methods for the IR generation.
27 
29 
30 std::vector<llvm::Value*> CodeGenerator::codegen(const Analyzer::Expr* expr,
31  const bool fetch_columns,
32  const CompilationOptions& co) {
34  if (!expr) {
35  return {posArg(expr)};
36  }
37  auto bin_oper = dynamic_cast<const Analyzer::BinOper*>(expr);
38  if (bin_oper) {
39  return {codegen(bin_oper, co)};
40  }
41  auto u_oper = dynamic_cast<const Analyzer::UOper*>(expr);
42  if (u_oper) {
43  return {codegen(u_oper, co)};
44  }
45  auto geo_col_var = dynamic_cast<const Analyzer::GeoColumnVar*>(expr);
46  if (geo_col_var) {
47  // inherits from ColumnVar, so it is important we check this first
48  return codegenGeoColumnVar(geo_col_var, fetch_columns, co);
49  }
50  auto col_var = dynamic_cast<const Analyzer::ColumnVar*>(expr);
51  if (col_var) {
52  return codegenColumn(col_var, fetch_columns, co);
53  }
54  auto constant = dynamic_cast<const Analyzer::Constant*>(expr);
55  if (constant) {
56  const auto& ti = constant->get_type_info();
57  if (ti.get_type() == kNULLT) {
58  throw std::runtime_error(
59  "NULL type literals are not currently supported in this context.");
60  }
61  if (constant->get_is_null()) {
62  const auto i8p_ty =
63  llvm::PointerType::get(get_int_type(8, executor_->cgen_state_->context_), 0);
64  if (ti.is_string() && ti.get_compression() == kENCODING_NONE) {
65  std::vector<llvm::Value*> null_target_lvs;
66  llvm::StructType* str_view_ty = createStringViewStructType();
67  auto null_str_view_struct_lv = cgen_state_->ir_builder_.CreateAlloca(str_view_ty);
68  // we do not need to fill the values of the string_view struct representing null
69  // string
70  null_target_lvs.push_back(
71  cgen_state_->ir_builder_.CreateLoad(str_view_ty, null_str_view_struct_lv));
72  null_target_lvs.push_back(llvm::ConstantPointerNull::get(
73  llvm::PointerType::get(llvm::IntegerType::get(cgen_state_->context_, 8), 0)));
74  null_target_lvs.push_back(cgen_state_->llInt((int32_t)0));
75  return null_target_lvs;
76  } else if (ti.is_geometry()) {
77  std::vector<llvm::Value*> ret_lvs;
78  // we classify whether the geo col value is null from the rhs of the left-join
79  // qual i.e., table S in the qual: R left join S on R.v = S.v by checking 1)
80  // nulled chunk_iter and 2) its col buffer w/ the size 0 for instance, we consider
81  // the size of col buffer for point as 16 and for other types we use `array_size`
82  // function to determine it, and they all assume valid geos have their buf size >
83  // 0 thus, by returning all bufs' ptr as nullptr we can return 0 as the length of
84  // the nulled geos' col val, and remaining logic can exploit this to finally
85  // return "null" as the col value of the corresponding row in the resultset
86  switch (ti.get_type()) {
87  // outer join's phi node in the generated code expects the # returned lvs'
88  // is the same as `col_ti.get_physical_coord_cols()`
89  // now we have necessary logic to deal with these nullptr and can conclude
90  // it as nulled geo val, i.e., see ResultSetIteration::991
91  case kPOINT:
92  case kMULTIPOINT:
93  case kLINESTRING:
94  return {llvm::ConstantPointerNull::get(i8p_ty)};
95  case kMULTILINESTRING:
96  case kPOLYGON:
97  return {llvm::ConstantPointerNull::get(i8p_ty),
98  llvm::ConstantPointerNull::get(i8p_ty)};
99  case kMULTIPOLYGON:
100  return {llvm::ConstantPointerNull::get(i8p_ty),
101  llvm::ConstantPointerNull::get(i8p_ty),
102  llvm::ConstantPointerNull::get(i8p_ty)};
103  default:
104  CHECK(false);
105  return {nullptr};
106  }
107  } else if (ti.is_array()) {
108  // similar to above nulled geo case, we can use this `nullptr` to guide
109  // `array_buff` and `array_size` functions representing nulled array value
110  return {llvm::ConstantPointerNull::get(i8p_ty)};
111  }
112  return {ti.is_fp()
113  ? static_cast<llvm::Value*>(executor_->cgen_state_->inlineFpNull(ti))
114  : static_cast<llvm::Value*>(executor_->cgen_state_->inlineIntNull(ti))};
115  }
116  if (ti.get_compression() == kENCODING_DICT) {
117  // The dictionary encoding case should be handled by the parent expression
118  // (cast, for now), here is too late to know the dictionary id if not already set
119  CHECK_NE(ti.getStringDictKey().dict_id, 0);
120  return {codegen(constant, ti.get_compression(), ti.getStringDictKey(), co)};
121  }
122  return {codegen(constant, ti.get_compression(), {}, co)};
123  }
124  auto case_expr = dynamic_cast<const Analyzer::CaseExpr*>(expr);
125  if (case_expr) {
126  return {codegen(case_expr, co)};
127  }
128  auto extract_expr = dynamic_cast<const Analyzer::ExtractExpr*>(expr);
129  if (extract_expr) {
130  return {codegen(extract_expr, co)};
131  }
132  auto dateadd_expr = dynamic_cast<const Analyzer::DateaddExpr*>(expr);
133  if (dateadd_expr) {
134  return {codegen(dateadd_expr, co)};
135  }
136  auto datediff_expr = dynamic_cast<const Analyzer::DatediffExpr*>(expr);
137  if (datediff_expr) {
138  return {codegen(datediff_expr, co)};
139  }
140  auto datetrunc_expr = dynamic_cast<const Analyzer::DatetruncExpr*>(expr);
141  if (datetrunc_expr) {
142  return {codegen(datetrunc_expr, co)};
143  }
144  auto charlength_expr = dynamic_cast<const Analyzer::CharLengthExpr*>(expr);
145  if (charlength_expr) {
146  return {codegen(charlength_expr, co)};
147  }
148  auto keyforstring_expr = dynamic_cast<const Analyzer::KeyForStringExpr*>(expr);
149  if (keyforstring_expr) {
150  return {codegen(keyforstring_expr, co)};
151  }
152  auto sample_ratio_expr = dynamic_cast<const Analyzer::SampleRatioExpr*>(expr);
153  if (sample_ratio_expr) {
154  return {codegen(sample_ratio_expr, co)};
155  }
156  auto string_oper_expr = dynamic_cast<const Analyzer::StringOper*>(expr);
157  if (string_oper_expr) {
158  return {codegen(string_oper_expr, co)};
159  }
160  auto cardinality_expr = dynamic_cast<const Analyzer::CardinalityExpr*>(expr);
161  if (cardinality_expr) {
162  return {codegen(cardinality_expr, co)};
163  }
164  auto like_expr = dynamic_cast<const Analyzer::LikeExpr*>(expr);
165  if (like_expr) {
166  return {codegen(like_expr, co)};
167  }
168  auto regexp_expr = dynamic_cast<const Analyzer::RegexpExpr*>(expr);
169  if (regexp_expr) {
170  return {codegen(regexp_expr, co)};
171  }
172  auto width_bucket_expr = dynamic_cast<const Analyzer::WidthBucketExpr*>(expr);
173  if (width_bucket_expr) {
174  return {codegen(width_bucket_expr, co)};
175  }
176 
177  auto ml_predict_expr = dynamic_cast<const Analyzer::MLPredictExpr*>(expr);
178  if (ml_predict_expr) {
179  return {codegen(ml_predict_expr, co)};
180  }
181 
182  auto pca_project_expr = dynamic_cast<const Analyzer::PCAProjectExpr*>(expr);
183  if (pca_project_expr) {
184  return {codegen(pca_project_expr, co)};
185  }
186 
187  auto likelihood_expr = dynamic_cast<const Analyzer::LikelihoodExpr*>(expr);
188  if (likelihood_expr) {
189  return {codegen(likelihood_expr->get_arg(), fetch_columns, co)};
190  }
191  auto in_expr = dynamic_cast<const Analyzer::InValues*>(expr);
192  if (in_expr) {
193  return {codegen(in_expr, co)};
194  }
195  auto in_integer_set_expr = dynamic_cast<const Analyzer::InIntegerSet*>(expr);
196  if (in_integer_set_expr) {
197  return {codegen(in_integer_set_expr, co)};
198  }
199  auto function_oper_with_custom_type_handling_expr =
200  dynamic_cast<const Analyzer::FunctionOperWithCustomTypeHandling*>(expr);
201  if (function_oper_with_custom_type_handling_expr) {
203  function_oper_with_custom_type_handling_expr, co)};
204  }
205  auto array_oper_expr = dynamic_cast<const Analyzer::ArrayExpr*>(expr);
206  if (array_oper_expr) {
207  return {codegenArrayExpr(array_oper_expr, co)};
208  }
209  auto geo_uop = dynamic_cast<const Analyzer::GeoUOper*>(expr);
210  if (geo_uop) {
211  return {codegenGeoUOper(geo_uop, co)};
212  }
213  auto geo_binop = dynamic_cast<const Analyzer::GeoBinOper*>(expr);
214  if (geo_binop) {
215  return {codegenGeoBinOper(geo_binop, co)};
216  }
217  auto function_oper_expr = dynamic_cast<const Analyzer::FunctionOper*>(expr);
218  if (function_oper_expr) {
219  return {codegenFunctionOper(function_oper_expr, co)};
220  }
221  auto geo_expr = dynamic_cast<const Analyzer::GeoExpr*>(expr);
222  if (geo_expr) {
223  return codegenGeoExpr(geo_expr, co);
224  }
225  if (dynamic_cast<const Analyzer::OffsetInFragment*>(expr)) {
226  return {posArg(nullptr)};
227  }
228  if (dynamic_cast<const Analyzer::WindowFunction*>(expr)) {
229  throw NativeExecutionError("Window expression not supported in this context");
230  }
231  abort();
232 }
233 
234 llvm::Value* CodeGenerator::codegen(const Analyzer::BinOper* bin_oper,
235  const CompilationOptions& co) {
237  const auto optype = bin_oper->get_optype();
238  if (IS_ARITHMETIC(optype)) {
239  return codegenArith(bin_oper, co);
240  }
241  if (IS_COMPARISON(optype)) {
242  return codegenCmp(bin_oper, co);
243  }
244  if (IS_LOGIC(optype)) {
245  return codegenLogical(bin_oper, co);
246  }
247  if (optype == kARRAY_AT) {
248  return codegenArrayAt(bin_oper, co);
249  }
250  abort();
251 }
252 
253 llvm::Value* CodeGenerator::codegen(const Analyzer::UOper* u_oper,
254  const CompilationOptions& co) {
256  const auto optype = u_oper->get_optype();
257  switch (optype) {
258  case kNOT: {
259  return codegenLogical(u_oper, co);
260  }
261  case kCAST: {
262  return codegenCast(u_oper, co);
263  }
264  case kUMINUS: {
265  return codegenUMinus(u_oper, co);
266  }
267  case kISNULL: {
268  return codegenIsNull(u_oper, co);
269  }
270  case kUNNEST:
271  return codegenUnnest(u_oper, co);
272  default:
273  UNREACHABLE();
274  }
275  return nullptr;
276 }
277 
279  const CompilationOptions& co) {
281  auto input_expr = expr->get_arg();
282  CHECK(input_expr);
283 
284  auto double_lv = codegen(input_expr, true, co);
285  CHECK_EQ(size_t(1), double_lv.size());
286 
287  std::unique_ptr<CodeGenerator::NullCheckCodegen> nullcheck_codegen;
288  const bool is_nullable = !input_expr->get_type_info().get_notnull();
289  if (is_nullable) {
290  nullcheck_codegen = std::make_unique<NullCheckCodegen>(cgen_state_,
291  executor(),
292  double_lv.front(),
293  input_expr->get_type_info(),
294  "sample_ratio_nullcheck");
295  }
296  CHECK_EQ(input_expr->get_type_info().get_type(), kDOUBLE);
297  std::vector<llvm::Value*> args{double_lv[0], posArg(nullptr)};
298  auto ret = cgen_state_->emitCall("sample_ratio", args);
299  if (nullcheck_codegen) {
300  ret = nullcheck_codegen->finalize(ll_bool(false, cgen_state_->context_), ret);
301  }
302  return ret;
303 }
304 
306  const CompilationOptions& co) {
308  auto target_value_expr = expr->get_target_value();
309  auto lower_bound_expr = expr->get_lower_bound();
310  auto upper_bound_expr = expr->get_upper_bound();
311  auto partition_count_expr = expr->get_partition_count();
312  CHECK(target_value_expr);
313  CHECK(lower_bound_expr);
314  CHECK(upper_bound_expr);
315  CHECK(partition_count_expr);
316 
317  auto is_constant_expr = [](const Analyzer::Expr* expr) {
318  auto target_expr = expr;
319  if (auto cast_expr = dynamic_cast<const Analyzer::UOper*>(expr)) {
320  if (cast_expr->get_optype() == SQLOps::kCAST) {
321  target_expr = cast_expr->get_operand();
322  }
323  }
324  // there are more complex constant expr like 1+2, 1/2*3, and so on
325  // but when considering a typical usage of width_bucket function
326  // it is sufficient to consider a singleton constant expr
327  auto constant_expr = dynamic_cast<const Analyzer::Constant*>(target_expr);
328  if (constant_expr) {
329  return true;
330  }
331  return false;
332  };
333  if (is_constant_expr(lower_bound_expr) && is_constant_expr(upper_bound_expr) &&
334  is_constant_expr(partition_count_expr)) {
335  expr->set_constant_expr();
336  }
337  // compute width_bucket's expresn range and check the possibility of avoiding oob check
338  auto col_range =
339  getExpressionRange(expr,
341  executor_,
342  boost::make_optional(plan_state_->getSimpleQuals()));
343  // check whether target_expr is valid
344  if (col_range.getType() == ExpressionRangeType::Integer &&
345  !expr->can_skip_out_of_bound_check() && col_range.getIntMin() > 0 &&
346  col_range.getIntMax() <= expr->get_partition_count_val()) {
347  // check whether target_col is not-nullable or has filter expr on it
348  if (!col_range.hasNulls()) {
349  // Even if the target_expr has its filter expression, target_col_range may exactly
350  // the same with the col_range of the target_expr's operand col,
351  // i.e., SELECT WIDTH_BUCKET(v1, 1, 10, 10) FROM T WHERE v1 != 1;
352  // In that query, col_range of v1 with/without considering the filter expression
353  // v1 != 1 have exactly the same col ranges, so we cannot recognize the existence
354  // of the filter expression based on them. Also, is (not) null is located in
355  // FilterNode, so we cannot trace it in here.
356  // todo (yoonmin): relax this to allow skipping oob check more cases
357  expr->skip_out_of_bound_check();
358  }
359  }
360  return expr->is_constant_expr() ? codegenConstantWidthBucketExpr(expr, co)
361  : codegenWidthBucketExpr(expr, co);
362 }
363 
365  const Analyzer::WidthBucketExpr* expr,
366  const CompilationOptions& co) {
367  auto target_value_expr = expr->get_target_value();
368  auto lower_bound_expr = expr->get_lower_bound();
369  auto upper_bound_expr = expr->get_upper_bound();
370  auto partition_count_expr = expr->get_partition_count();
371 
372  auto num_partitions = expr->get_partition_count_val();
373  if (num_partitions < 1 || num_partitions > INT32_MAX) {
374  throw std::runtime_error(
375  "PARTITION_COUNT expression of width_bucket function should be in a valid "
376  "range: 0 < PARTITION_COUNT <= 2147483647");
377  }
378  double lower = expr->get_bound_val(lower_bound_expr);
379  double upper = expr->get_bound_val(upper_bound_expr);
380  if (lower == upper) {
381  throw std::runtime_error(
382  "LOWER_BOUND and UPPER_BOUND expressions of width_bucket function cannot have "
383  "the same constant value");
384  }
385  if (lower == NULL_DOUBLE || upper == NULL_DOUBLE) {
386  throw std::runtime_error(
387  "Both LOWER_BOUND and UPPER_BOUND of width_bucket function should be finite "
388  "numeric constants.");
389  }
390 
391  bool const reversed = lower > upper;
392  double const scale_factor = num_partitions / (reversed ? lower - upper : upper - lower);
393  std::string func_name = reversed ? "width_bucket_reversed" : "width_bucket";
394 
395  auto get_double_constant_lvs = [this, &co](double const_val) {
396  Datum d;
397  d.doubleval = const_val;
398  auto double_const_expr =
399  makeExpr<Analyzer::Constant>(SQLTypeInfo(kDOUBLE, false), false, d);
400  return codegen(double_const_expr.get(), false, co);
401  };
402 
403  auto target_value_ti = target_value_expr->get_type_info();
404  auto target_value_expr_lvs = codegen(target_value_expr, true, co);
405  CHECK_EQ(size_t(1), target_value_expr_lvs.size());
406  auto lower_expr_lvs = codegen(lower_bound_expr, true, co);
407  CHECK_EQ(size_t(1), lower_expr_lvs.size());
408  auto scale_factor_lvs = get_double_constant_lvs(scale_factor);
409  CHECK_EQ(size_t(1), scale_factor_lvs.size());
410 
411  std::vector<llvm::Value*> width_bucket_args{target_value_expr_lvs[0],
412  lower_expr_lvs[0]};
413  if (expr->can_skip_out_of_bound_check()) {
414  func_name += "_no_oob_check";
415  width_bucket_args.push_back(scale_factor_lvs[0]);
416  } else {
417  auto upper_expr_lvs = codegen(upper_bound_expr, true, co);
418  CHECK_EQ(size_t(1), upper_expr_lvs.size());
419  auto partition_count_expr_lvs = codegen(partition_count_expr, true, co);
420  CHECK_EQ(size_t(1), partition_count_expr_lvs.size());
421  width_bucket_args.push_back(upper_expr_lvs[0]);
422  width_bucket_args.push_back(scale_factor_lvs[0]);
423  width_bucket_args.push_back(partition_count_expr_lvs[0]);
424  if (!target_value_ti.get_notnull()) {
425  func_name += "_nullable";
426  auto translated_null_value = target_value_ti.is_fp()
427  ? inline_fp_null_val(target_value_ti)
428  : inline_int_null_val(target_value_ti);
429  auto null_value_lvs = get_double_constant_lvs(translated_null_value);
430  CHECK_EQ(size_t(1), null_value_lvs.size());
431  width_bucket_args.push_back(null_value_lvs[0]);
432  }
433  }
434  return cgen_state_->emitCall(func_name, width_bucket_args);
435 }
436 
438  const CompilationOptions& co) {
439  auto target_value_expr = expr->get_target_value();
440  auto lower_bound_expr = expr->get_lower_bound();
441  auto upper_bound_expr = expr->get_upper_bound();
442  auto partition_count_expr = expr->get_partition_count();
443 
444  std::string func_name = "width_bucket_expr";
445  bool nullable_expr = false;
446  if (expr->can_skip_out_of_bound_check()) {
447  func_name += "_no_oob_check";
448  } else if (!target_value_expr->get_type_info().get_notnull()) {
449  func_name += "_nullable";
450  nullable_expr = true;
451  }
452 
453  auto target_value_expr_lvs = codegen(target_value_expr, true, co);
454  CHECK_EQ(size_t(1), target_value_expr_lvs.size());
455  auto lower_bound_expr_lvs = codegen(lower_bound_expr, true, co);
456  CHECK_EQ(size_t(1), lower_bound_expr_lvs.size());
457  auto upper_bound_expr_lvs = codegen(upper_bound_expr, true, co);
458  CHECK_EQ(size_t(1), upper_bound_expr_lvs.size());
459  auto partition_count_expr_lvs = codegen(partition_count_expr, true, co);
460  CHECK_EQ(size_t(1), partition_count_expr_lvs.size());
461  auto target_value_ti = target_value_expr->get_type_info();
462  auto null_value_lv = cgen_state_->inlineFpNull(target_value_ti);
463 
464  // check partition count : 1 ~ INT32_MAX
465  // INT32_MAX will be checked during casting by OVERFLOW checking step
466  auto partition_count_ti = partition_count_expr->get_type_info();
467  CHECK(partition_count_ti.is_integer());
468  auto int32_ti = SQLTypeInfo(kINT, partition_count_ti.get_notnull());
469  auto partition_count_expr_lv =
470  codegenCastBetweenIntTypes(partition_count_expr_lvs[0],
471  partition_count_ti,
472  int32_ti,
473  partition_count_ti.get_size() < int32_ti.get_size());
474  llvm::Value* chosen_min = cgen_state_->llInt(static_cast<int32_t>(0));
475  llvm::Value* partition_count_min =
476  cgen_state_->ir_builder_.CreateICmpSLE(partition_count_expr_lv, chosen_min);
477  llvm::BasicBlock* width_bucket_partition_count_ok_bb =
478  llvm::BasicBlock::Create(cgen_state_->context_,
479  "width_bucket_partition_count_ok_bb",
481  llvm::BasicBlock* width_bucket_argument_check_fail_bb =
482  llvm::BasicBlock::Create(cgen_state_->context_,
483  "width_bucket_argument_check_fail_bb",
485  cgen_state_->ir_builder_.CreateCondBr(partition_count_min,
486  width_bucket_argument_check_fail_bb,
487  width_bucket_partition_count_ok_bb);
488  cgen_state_->ir_builder_.SetInsertPoint(width_bucket_argument_check_fail_bb);
489  cgen_state_->ir_builder_.CreateRet(
491  cgen_state_->ir_builder_.SetInsertPoint(width_bucket_partition_count_ok_bb);
492 
493  llvm::BasicBlock* width_bucket_bound_check_ok_bb =
494  llvm::BasicBlock::Create(cgen_state_->context_,
495  "width_bucket_bound_check_ok_bb",
497  llvm::Value* bound_check{nullptr};
498  if (lower_bound_expr->get_type_info().get_notnull() &&
499  upper_bound_expr->get_type_info().get_notnull()) {
500  bound_check = cgen_state_->ir_builder_.CreateFCmpOEQ(
501  lower_bound_expr_lvs[0], upper_bound_expr_lvs[0], "bound_check");
502  } else {
503  std::vector<llvm::Value*> bound_check_args{
504  lower_bound_expr_lvs[0],
505  upper_bound_expr_lvs[0],
506  null_value_lv,
507  cgen_state_->llInt(static_cast<int8_t>(1))};
508  bound_check = toBool(cgen_state_->emitCall("eq_double_nullable", bound_check_args));
509  }
510  cgen_state_->ir_builder_.CreateCondBr(
511  bound_check, width_bucket_argument_check_fail_bb, width_bucket_bound_check_ok_bb);
512  cgen_state_->ir_builder_.SetInsertPoint(width_bucket_bound_check_ok_bb);
514  auto reversed_expr = toBool(codegenCmp(SQLOps::kGT,
515  kONE,
516  lower_bound_expr_lvs,
517  lower_bound_expr->get_type_info(),
518  upper_bound_expr,
519  co));
520  auto lower_bound_expr_lv = lower_bound_expr_lvs[0];
521  auto upper_bound_expr_lv = upper_bound_expr_lvs[0];
522  std::vector<llvm::Value*> width_bucket_args{target_value_expr_lvs[0],
523  reversed_expr,
524  lower_bound_expr_lv,
525  upper_bound_expr_lv,
526  partition_count_expr_lv};
527  if (nullable_expr) {
528  width_bucket_args.push_back(null_value_lv);
529  }
530  return cgen_state_->emitCall(func_name, width_bucket_args);
531 }
532 
533 namespace {
534 
536  const std::shared_ptr<Analyzer::Expr>& qual) {
537  const auto qual_cf = qual_to_conjunctive_form(qual);
538  ra_exe_unit.simple_quals.insert(ra_exe_unit.simple_quals.end(),
539  qual_cf.simple_quals.begin(),
540  qual_cf.simple_quals.end());
541  ra_exe_unit.quals.insert(
542  ra_exe_unit.quals.end(), qual_cf.quals.begin(), qual_cf.quals.end());
543 }
544 
546  const ExecutionOptions& eo,
547  const std::vector<InputTableInfo>& query_infos,
548  const size_t level_idx,
549  const std::string& fail_reason) {
550  if (ra_exe_unit.input_descs.size() < 2) {
551  // We only support loop join at the end of folded joins
552  // where ra_exe_unit.input_descs.size() > 2 for now.
553  throw std::runtime_error("Hash join failed, reason(s): " + fail_reason +
554  " | Incorrect # tables for executing loop join");
555  }
556  const auto loop_join_size = get_loop_join_size(query_infos, ra_exe_unit);
557  const bool has_loop_size_hint =
559  const size_t loop_join_size_threshold =
560  has_loop_size_hint ? ra_exe_unit.query_hint.loop_join_inner_table_max_num_rows
562  if (eo.allow_loop_joins) {
563  if (has_loop_size_hint && loop_join_size_threshold < loop_join_size) {
564  throw std::runtime_error(
565  "Hash join failed, reason(s): " + fail_reason +
566  " | Cannot fall back to loop join for non-trivial inner table size");
567  }
568  return;
569  }
570  if (level_idx + 1 != ra_exe_unit.join_quals.size()) {
571  throw std::runtime_error(
572  "Hash join failed, reason(s): " + fail_reason +
573  " | Cannot fall back to loop join for intermediate join quals");
574  }
575  if (loop_join_size_threshold < loop_join_size) {
576  throw std::runtime_error(
577  "Hash join failed, reason(s): " + fail_reason +
578  " | Cannot fall back to loop join for non-trivial inner table size");
579  }
580  if (ra_exe_unit.query_hint.isHintRegistered(kDisableLoopJoin)) {
581  throw std::runtime_error("Hash join failed, reason(s): " + fail_reason +
582  " | Loop join is disabled by user");
583  }
584 }
585 
586 void check_valid_join_qual(std::shared_ptr<Analyzer::BinOper>& bin_oper) {
587  // check whether a join qual is valid before entering the hashtable build and codegen
588 
589  auto lhs_cv = dynamic_cast<const Analyzer::ColumnVar*>(bin_oper->get_left_operand());
590  auto rhs_cv = dynamic_cast<const Analyzer::ColumnVar*>(bin_oper->get_right_operand());
591  if (lhs_cv && rhs_cv && !bin_oper->is_bbox_intersect_oper()) {
592  auto lhs_type = lhs_cv->get_type_info().get_type();
593  auto rhs_type = rhs_cv->get_type_info().get_type();
594  // check #1. avoid a join btw full array columns
595  if (lhs_type == SQLTypes::kARRAY && rhs_type == SQLTypes::kARRAY) {
596  throw std::runtime_error(
597  "Join operation between full array columns (i.e., R.arr = S.arr) instead of "
598  "indexed array columns (i.e., R.arr[1] = S.arr[2]) is not supported yet.");
599  }
600  }
601  auto const lhs_et =
602  dynamic_cast<const Analyzer::ExpressionTuple*>(bin_oper->get_left_operand());
603  if (lhs_et) {
604  CHECK_LE(lhs_et->getTuple().size(), g_maximum_conditions_to_coalesce);
605  }
606 }
607 
608 } // namespace
609 
610 std::vector<JoinLoop> Executor::buildJoinLoops(
611  RelAlgExecutionUnit& ra_exe_unit,
612  const CompilationOptions& co,
613  const ExecutionOptions& eo,
614  const std::vector<InputTableInfo>& query_infos,
615  ColumnCacheMap& column_cache) {
616  INJECT_TIMER(buildJoinLoops);
618  std::vector<JoinLoop> join_loops;
619  for (size_t level_idx = 0, current_hash_table_idx = 0;
620  level_idx < ra_exe_unit.join_quals.size();
621  ++level_idx) {
622  const auto& current_level_join_conditions = ra_exe_unit.join_quals[level_idx];
623  std::vector<std::string> fail_reasons;
624  const auto current_level_hash_table =
625  buildCurrentLevelHashTable(current_level_join_conditions,
626  level_idx,
627  ra_exe_unit,
628  co,
629  query_infos,
630  column_cache,
631  fail_reasons);
632  const auto found_outer_join_matches_cb =
633  [this, level_idx](llvm::Value* found_outer_join_matches) {
637  found_outer_join_matches;
638  };
639  const auto is_deleted_cb = buildIsDeletedCb(ra_exe_unit, level_idx, co);
640  auto rem_left_join_quals_it =
642  bool has_remaining_left_join_quals =
643  rem_left_join_quals_it != plan_state_->left_join_non_hashtable_quals_.end() &&
644  !rem_left_join_quals_it->second.empty();
645  const auto outer_join_condition_remaining_quals_cb =
646  [this, level_idx, &co](const std::vector<llvm::Value*>& prev_iters) {
647  // when we have multiple quals for the left join in the current join level
648  // we first try to build a hashtable by using one of the possible qual,
649  // and deal with remaining quals as extra join conditions
650  FetchCacheAnchor anchor(cgen_state_.get());
651  addJoinLoopIterator(prev_iters, level_idx + 1);
652  llvm::Value* left_join_cond = cgen_state_->llBool(true);
653  CodeGenerator code_generator(this);
654  auto it = plan_state_->left_join_non_hashtable_quals_.find(level_idx);
655  if (it != plan_state_->left_join_non_hashtable_quals_.end()) {
656  for (auto expr : it->second) {
657  left_join_cond = cgen_state_->ir_builder_.CreateAnd(
658  left_join_cond,
659  code_generator.toBool(
660  code_generator.codegen(expr.get(), true, co).front()));
661  }
662  }
663  return left_join_cond;
664  };
665  if (current_level_hash_table) {
666  const auto hoisted_filters_cb = buildHoistLeftHandSideFiltersCb(
667  ra_exe_unit, level_idx, current_level_hash_table->getInnerTableId(), co);
668  if (current_level_hash_table->getHashType() == HashType::OneToOne) {
669  join_loops.emplace_back(
670  /*kind=*/JoinLoopKind::Singleton,
671  /*type=*/current_level_join_conditions.type,
672  /*iteration_domain_codegen=*/
673  [this, current_hash_table_idx, level_idx, current_level_hash_table, &co](
674  const std::vector<llvm::Value*>& prev_iters) {
675  addJoinLoopIterator(prev_iters, level_idx);
676  JoinLoopDomain domain{{0}};
677  domain.slot_lookup_result =
678  current_level_hash_table->codegenSlot(co, current_hash_table_idx);
679  return domain;
680  },
681  /*outer_condition_match=*/
682  current_level_join_conditions.type == JoinType::LEFT &&
683  has_remaining_left_join_quals
684  ? std::function<llvm::Value*(const std::vector<llvm::Value*>&)>(
685  outer_join_condition_remaining_quals_cb)
686  : nullptr,
687  /*found_outer_matches=*/current_level_join_conditions.type == JoinType::LEFT
688  ? std::function<void(llvm::Value*)>(found_outer_join_matches_cb)
689  : nullptr,
690  /*hoisted_filters=*/hoisted_filters_cb,
691  /*is_deleted=*/is_deleted_cb,
692  /*nested_loop_join=*/false);
693  } else if (auto range_join_table =
694  dynamic_cast<RangeJoinHashTable*>(current_level_hash_table.get())) {
695  join_loops.emplace_back(
696  /* kind= */ JoinLoopKind::MultiSet,
697  /* type= */ current_level_join_conditions.type,
698  /* iteration_domain_codegen= */
699  [this,
700  range_join_table,
701  current_hash_table_idx,
702  level_idx,
703  current_level_hash_table,
704  &co](const std::vector<llvm::Value*>& prev_iters) {
705  addJoinLoopIterator(prev_iters, level_idx);
706  JoinLoopDomain domain{{0}};
707  CHECK(!prev_iters.empty());
708  const auto matching_set = range_join_table->codegenMatchingSetWithOffset(
709  co, current_hash_table_idx, prev_iters.back());
710  domain.values_buffer = matching_set.elements;
711  domain.element_count = matching_set.count;
712  return domain;
713  },
714  /* outer_condition_match= */
715  current_level_join_conditions.type == JoinType::LEFT
716  ? std::function<llvm::Value*(const std::vector<llvm::Value*>&)>(
717  outer_join_condition_remaining_quals_cb)
718  : nullptr,
719  /* found_outer_matches= */
720  current_level_join_conditions.type == JoinType::LEFT
721  ? std::function<void(llvm::Value*)>(found_outer_join_matches_cb)
722  : nullptr,
723  /* hoisted_filters= */ nullptr, // <<! TODO
724  /* is_deleted= */ is_deleted_cb,
725  /*nested_loop_join=*/false);
726  } else {
727  join_loops.emplace_back(
728  /*kind=*/JoinLoopKind::Set,
729  /*type=*/current_level_join_conditions.type,
730  /*iteration_domain_codegen=*/
731  [this, current_hash_table_idx, level_idx, current_level_hash_table, &co](
732  const std::vector<llvm::Value*>& prev_iters) {
733  addJoinLoopIterator(prev_iters, level_idx);
734  JoinLoopDomain domain{{0}};
735  const auto matching_set = current_level_hash_table->codegenMatchingSet(
736  co, current_hash_table_idx);
737  domain.values_buffer = matching_set.elements;
738  domain.element_count = matching_set.count;
739  return domain;
740  },
741  /*outer_condition_match=*/
742  current_level_join_conditions.type == JoinType::LEFT
743  ? std::function<llvm::Value*(const std::vector<llvm::Value*>&)>(
744  outer_join_condition_remaining_quals_cb)
745  : nullptr,
746  /*found_outer_matches=*/current_level_join_conditions.type == JoinType::LEFT
747  ? std::function<void(llvm::Value*)>(found_outer_join_matches_cb)
748  : nullptr,
749  /*hoisted_filters=*/hoisted_filters_cb,
750  /*is_deleted=*/is_deleted_cb,
751  /*nested_loop_join=*/false);
752  }
753  ++current_hash_table_idx;
754  } else {
755  const auto fail_reasons_str = current_level_join_conditions.quals.empty()
756  ? "No equijoin expression found"
757  : boost::algorithm::join(fail_reasons, " | ");
759  ra_exe_unit, eo, query_infos, level_idx, fail_reasons_str);
760  // Callback provided to the `JoinLoop` framework to evaluate the (outer) join
761  // condition.
762  VLOG(1) << "Unable to build hash table, falling back to loop join: "
763  << fail_reasons_str;
764  const auto outer_join_condition_cb =
765  [this, level_idx, &co, &current_level_join_conditions](
766  const std::vector<llvm::Value*>& prev_iters) {
767  // The values generated for the match path don't dominate all uses
768  // since on the non-match path nulls are generated. Reset the cache
769  // once the condition is generated to avoid incorrect reuse.
770  FetchCacheAnchor anchor(cgen_state_.get());
771  addJoinLoopIterator(prev_iters, level_idx + 1);
772  llvm::Value* left_join_cond = cgen_state_->llBool(true);
773  CodeGenerator code_generator(this);
774  for (auto expr : current_level_join_conditions.quals) {
775  left_join_cond = cgen_state_->ir_builder_.CreateAnd(
776  left_join_cond,
777  code_generator.toBool(
778  code_generator.codegen(expr.get(), true, co).front()));
779  }
780  return left_join_cond;
781  };
782  join_loops.emplace_back(
783  /*kind=*/JoinLoopKind::UpperBound,
784  /*type=*/current_level_join_conditions.type,
785  /*iteration_domain_codegen=*/
786  [this, level_idx](const std::vector<llvm::Value*>& prev_iters) {
787  addJoinLoopIterator(prev_iters, level_idx);
788  JoinLoopDomain domain{{0}};
789  auto* arg = get_arg_by_name(cgen_state_->row_func_, "num_rows_per_scan");
790  const auto rows_per_scan_ptr = cgen_state_->ir_builder_.CreateGEP(
791  arg->getType()->getScalarType()->getPointerElementType(),
792  arg,
793  cgen_state_->llInt(int32_t(level_idx + 1)));
794  domain.upper_bound = cgen_state_->ir_builder_.CreateLoad(
795  rows_per_scan_ptr->getType()->getPointerElementType(),
796  rows_per_scan_ptr,
797  "num_rows_per_scan");
798  return domain;
799  },
800  /*outer_condition_match=*/
801  current_level_join_conditions.type == JoinType::LEFT
802  ? std::function<llvm::Value*(const std::vector<llvm::Value*>&)>(
803  outer_join_condition_cb)
804  : nullptr,
805  /*found_outer_matches=*/
806  current_level_join_conditions.type == JoinType::LEFT
807  ? std::function<void(llvm::Value*)>(found_outer_join_matches_cb)
808  : nullptr,
809  /*hoisted_filters=*/nullptr,
810  /*is_deleted=*/is_deleted_cb,
811  /*nested_loop_join=*/true);
812  }
813  }
814  return join_loops;
815 }
816 
817 namespace {
818 
819 class ExprTableIdVisitor : public ScalarExprVisitor<std::set<shared::TableKey>> {
820  protected:
821  std::set<shared::TableKey> visitColumnVar(
822  const Analyzer::ColumnVar* col_expr) const final {
823  return {col_expr->getTableKey()};
824  }
825 
826  std::set<shared::TableKey> visitFunctionOper(
827  const Analyzer::FunctionOper* func_expr) const final {
828  std::set<shared::TableKey> ret;
829  for (size_t i = 0; i < func_expr->getArity(); i++) {
830  ret = aggregateResult(ret, visit(func_expr->getArg(i)));
831  }
832  return ret;
833  }
834 
835  std::set<shared::TableKey> visitBinOper(const Analyzer::BinOper* bin_oper) const final {
836  std::set<shared::TableKey> ret;
837  ret = aggregateResult(ret, visit(bin_oper->get_left_operand()));
838  return aggregateResult(ret, visit(bin_oper->get_right_operand()));
839  }
840 
841  std::set<shared::TableKey> visitUOper(const Analyzer::UOper* u_oper) const final {
842  return visit(u_oper->get_operand());
843  }
844 
845  std::set<shared::TableKey> aggregateResult(
846  const std::set<shared::TableKey>& aggregate,
847  const std::set<shared::TableKey>& next_result) const final {
848  auto ret = aggregate; // copy
849  for (const auto& el : next_result) {
850  ret.insert(el);
851  }
852  return ret;
853  }
854 };
855 
856 } // namespace
857 
859  const RelAlgExecutionUnit& ra_exe_unit,
860  const size_t level_idx,
861  const shared::TableKey& inner_table_id,
862  const CompilationOptions& co) {
864  return nullptr;
865  }
866 
867  const auto& current_level_join_conditions = ra_exe_unit.join_quals[level_idx];
868  if (level_idx == 0 && current_level_join_conditions.type == JoinType::LEFT) {
869  const auto& condition = current_level_join_conditions.quals.front();
870  const auto bin_oper = dynamic_cast<const Analyzer::BinOper*>(condition.get());
871  CHECK(bin_oper) << condition->toString();
872  const auto rhs =
873  dynamic_cast<const Analyzer::ColumnVar*>(bin_oper->get_right_operand());
874  const auto lhs =
875  dynamic_cast<const Analyzer::ColumnVar*>(bin_oper->get_left_operand());
876  if (lhs && rhs && lhs->getTableKey() != rhs->getTableKey()) {
877  const Analyzer::ColumnVar* selected_lhs{nullptr};
878  // grab the left hand side column -- this is somewhat similar to normalize column
879  // pair, and a better solution may be to hoist that function out of the join
880  // framework and normalize columns at the top of build join loops
881  if (lhs->getTableKey() == inner_table_id) {
882  selected_lhs = rhs;
883  } else if (rhs->getTableKey() == inner_table_id) {
884  selected_lhs = lhs;
885  }
886  if (selected_lhs) {
887  std::list<std::shared_ptr<Analyzer::Expr>> hoisted_quals;
888  // get all LHS-only filters
889  auto should_hoist_qual = [&hoisted_quals](const auto& qual,
890  const shared::TableKey& table_key) {
891  CHECK(qual);
892 
893  ExprTableIdVisitor visitor;
894  const auto table_keys = visitor.visit(qual.get());
895  if (table_keys.size() == 1 && table_keys.find(table_key) != table_keys.end()) {
896  hoisted_quals.push_back(qual);
897  }
898  };
899  for (const auto& qual : ra_exe_unit.simple_quals) {
900  should_hoist_qual(qual, selected_lhs->getTableKey());
901  }
902  for (const auto& qual : ra_exe_unit.quals) {
903  should_hoist_qual(qual, selected_lhs->getTableKey());
904  }
905 
906  // build the filters callback and return it
907  if (!hoisted_quals.empty()) {
908  return [this, hoisted_quals, co](llvm::BasicBlock* true_bb,
909  llvm::BasicBlock* exit_bb,
910  const std::string& loop_name,
911  llvm::Function* parent_func,
912  CgenState* cgen_state) -> llvm::BasicBlock* {
913  // make sure we have quals to hoist
914  bool has_quals_to_hoist = false;
915  for (const auto& qual : hoisted_quals) {
916  // check to see if the filter was previously hoisted. if all filters were
917  // previously hoisted, this callback becomes a noop
918  if (plan_state_->hoisted_filters_.count(qual) == 0) {
919  has_quals_to_hoist = true;
920  break;
921  }
922  }
923 
924  if (!has_quals_to_hoist) {
925  return nullptr;
926  }
927 
928  AUTOMATIC_IR_METADATA(cgen_state);
929 
930  llvm::IRBuilder<>& builder = cgen_state->ir_builder_;
931  auto& context = builder.getContext();
932 
933  const auto filter_bb =
934  llvm::BasicBlock::Create(context,
935  "hoisted_left_join_filters_" + loop_name,
936  parent_func,
937  /*insert_before=*/true_bb);
938  builder.SetInsertPoint(filter_bb);
939 
940  llvm::Value* filter_lv = cgen_state_->llBool(true);
941  CodeGenerator code_generator(this);
942  CHECK(plan_state_);
943  for (const auto& qual : hoisted_quals) {
944  if (plan_state_->hoisted_filters_.insert(qual).second) {
945  // qual was inserted into the hoisted filters map, which means we have not
946  // seen this qual before. Generate filter.
947  VLOG(1) << "Generating code for hoisted left hand side qualifier "
948  << qual->toString();
949  auto cond = code_generator.toBool(
950  code_generator.codegen(qual.get(), true, co).front());
951  filter_lv = builder.CreateAnd(filter_lv, cond);
952  }
953  }
954  CHECK(filter_lv->getType()->isIntegerTy(1));
955 
956  builder.CreateCondBr(filter_lv, true_bb, exit_bb);
957  return filter_bb;
958  };
959  }
960  }
961  }
962  }
963  return nullptr;
964 }
965 
966 std::function<llvm::Value*(const std::vector<llvm::Value*>&, llvm::Value*)>
968  const size_t level_idx,
969  const CompilationOptions& co) {
970  AUTOMATIC_IR_METADATA(cgen_state_.get());
971  if (!co.filter_on_deleted_column) {
972  return nullptr;
973  }
974  CHECK_LT(level_idx + 1, ra_exe_unit.input_descs.size());
975  const auto input_desc = ra_exe_unit.input_descs[level_idx + 1];
976  if (input_desc.getSourceType() != InputSourceType::TABLE) {
977  return nullptr;
978  }
979 
980  const auto deleted_cd = plan_state_->getDeletedColForTable(input_desc.getTableKey());
981  if (!deleted_cd) {
982  return nullptr;
983  }
984  CHECK(deleted_cd->columnType.is_boolean());
985  const auto deleted_expr = makeExpr<Analyzer::ColumnVar>(
986  deleted_cd->columnType,
987  shared::ColumnKey{input_desc.getTableKey(), deleted_cd->columnId},
988  input_desc.getNestLevel());
989  return [this, deleted_expr, level_idx, &co](const std::vector<llvm::Value*>& prev_iters,
990  llvm::Value* have_more_inner_rows) {
991  const auto matching_row_index = addJoinLoopIterator(prev_iters, level_idx + 1);
992  // Avoid fetching the deleted column from a position which is not valid.
993  // An invalid position can be returned by a one to one hash lookup (negative)
994  // or at the end of iteration over a set of matching values.
995  llvm::Value* is_valid_it{nullptr};
996  if (have_more_inner_rows) {
997  is_valid_it = have_more_inner_rows;
998  } else {
999  is_valid_it = cgen_state_->ir_builder_.CreateICmp(
1000  llvm::ICmpInst::ICMP_SGE, matching_row_index, cgen_state_->llInt<int64_t>(0));
1001  }
1002  const auto it_valid_bb = llvm::BasicBlock::Create(
1003  cgen_state_->context_, "it_valid", cgen_state_->current_func_);
1004  const auto it_not_valid_bb = llvm::BasicBlock::Create(
1005  cgen_state_->context_, "it_not_valid", cgen_state_->current_func_);
1006  cgen_state_->ir_builder_.CreateCondBr(is_valid_it, it_valid_bb, it_not_valid_bb);
1007  const auto row_is_deleted_bb = llvm::BasicBlock::Create(
1008  cgen_state_->context_, "row_is_deleted", cgen_state_->current_func_);
1009  cgen_state_->ir_builder_.SetInsertPoint(it_valid_bb);
1010  CodeGenerator code_generator(this);
1011  const auto row_is_deleted = code_generator.toBool(
1012  code_generator.codegen(deleted_expr.get(), true, co).front());
1013  cgen_state_->ir_builder_.CreateBr(row_is_deleted_bb);
1014  cgen_state_->ir_builder_.SetInsertPoint(it_not_valid_bb);
1015  const auto row_is_deleted_default = cgen_state_->llBool(false);
1016  cgen_state_->ir_builder_.CreateBr(row_is_deleted_bb);
1017  cgen_state_->ir_builder_.SetInsertPoint(row_is_deleted_bb);
1018  auto row_is_deleted_or_default =
1019  cgen_state_->ir_builder_.CreatePHI(row_is_deleted->getType(), 2);
1020  row_is_deleted_or_default->addIncoming(row_is_deleted, it_valid_bb);
1021  row_is_deleted_or_default->addIncoming(row_is_deleted_default, it_not_valid_bb);
1022  return row_is_deleted_or_default;
1023  };
1024 }
1025 
1026 std::shared_ptr<HashJoin> Executor::buildCurrentLevelHashTable(
1027  const JoinCondition& current_level_join_conditions,
1028  size_t level_idx,
1029  RelAlgExecutionUnit& ra_exe_unit,
1030  const CompilationOptions& co,
1031  const std::vector<InputTableInfo>& query_infos,
1032  ColumnCacheMap& column_cache,
1033  std::vector<std::string>& fail_reasons) {
1034  AUTOMATIC_IR_METADATA(cgen_state_.get());
1035  std::shared_ptr<HashJoin> current_level_hash_table;
1036  auto handleNonHashtableQual = [&ra_exe_unit, &level_idx, this](
1037  JoinType join_type,
1038  std::shared_ptr<Analyzer::Expr> qual) {
1039  if (join_type == JoinType::LEFT) {
1040  plan_state_->addNonHashtableQualForLeftJoin(level_idx, qual);
1041  } else {
1042  add_qualifier_to_execution_unit(ra_exe_unit, qual);
1043  }
1044  };
1045  for (const auto& join_qual : current_level_join_conditions.quals) {
1046  auto qual_bin_oper = std::dynamic_pointer_cast<Analyzer::BinOper>(join_qual);
1047  if (current_level_hash_table || !qual_bin_oper ||
1048  !IS_EQUIVALENCE(qual_bin_oper->get_optype())) {
1049  handleNonHashtableQual(current_level_join_conditions.type, join_qual);
1050  if (!current_level_hash_table) {
1051  fail_reasons.emplace_back("No equijoin expression found");
1052  }
1053  continue;
1054  }
1055  check_valid_join_qual(qual_bin_oper);
1056  JoinHashTableOrError hash_table_or_error;
1057  if (!current_level_hash_table) {
1058  hash_table_or_error = buildHashTableForQualifier(
1059  qual_bin_oper,
1060  query_infos,
1063  current_level_join_conditions.type,
1065  column_cache,
1066  ra_exe_unit.hash_table_build_plan_dag,
1067  ra_exe_unit.query_hint,
1068  ra_exe_unit.table_id_to_node_map);
1069  current_level_hash_table = hash_table_or_error.hash_table;
1070  }
1071  if (hash_table_or_error.hash_table) {
1072  plan_state_->join_info_.join_hash_tables_.push_back(hash_table_or_error.hash_table);
1073  plan_state_->join_info_.equi_join_tautologies_.push_back(qual_bin_oper);
1074  } else {
1075  fail_reasons.push_back(hash_table_or_error.fail_reason);
1076  if (!current_level_hash_table) {
1077  VLOG(2) << "Building a hashtable based on a qual " << qual_bin_oper->toString()
1078  << " fails: " << hash_table_or_error.fail_reason;
1079  }
1080  handleNonHashtableQual(current_level_join_conditions.type, qual_bin_oper);
1081  }
1082  }
1083  return current_level_hash_table;
1084 }
1085 
1087  if (!cgen_state_->filter_func_) {
1088  return;
1089  }
1090 
1091  // Loop over all the instructions used in the filter func.
1092  // The filter func instructions were generated as if for row func.
1093  // Remap any values used by those instructions to filter func args
1094  // and remember to forward them through the call in the row func.
1095  for (auto bb_it = cgen_state_->filter_func_->begin();
1096  bb_it != cgen_state_->filter_func_->end();
1097  ++bb_it) {
1098  for (auto instr_it = bb_it->begin(); instr_it != bb_it->end(); ++instr_it) {
1099  size_t i = 0;
1100  for (auto op_it = instr_it->value_op_begin(); op_it != instr_it->value_op_end();
1101  ++op_it, ++i) {
1102  llvm::Value* v = *op_it;
1103 
1104  // The last LLVM operand on a call instruction is the function to be called. Never
1105  // remap it.
1106  if (llvm::dyn_cast<const llvm::CallInst>(instr_it) &&
1107  op_it == instr_it->value_op_end() - 1) {
1108  continue;
1109  }
1110 
1111  CHECK(v);
1112  if (auto* instr = llvm::dyn_cast<llvm::Instruction>(v);
1113  instr && instr->getParent() &&
1114  instr->getParent()->getParent() == cgen_state_->row_func_) {
1115  // Remember that this filter func arg is needed.
1116  cgen_state_->filter_func_args_[v] = nullptr;
1117  } else if (auto* argum = llvm::dyn_cast<llvm::Argument>(v);
1118  argum && argum->getParent() == cgen_state_->row_func_) {
1119  // Remember that this filter func arg is needed.
1120  cgen_state_->filter_func_args_[v] = nullptr;
1121  }
1122  }
1123  }
1124  }
1125 
1126  // Create filter_func2 with parameters only for those row func values that are known to
1127  // be used in the filter func code.
1128  std::vector<llvm::Type*> filter_func_arg_types;
1129  filter_func_arg_types.reserve(cgen_state_->filter_func_args_.v_.size());
1130  for (auto& arg : cgen_state_->filter_func_args_.v_) {
1131  filter_func_arg_types.push_back(arg->getType());
1132  }
1133  auto ft = llvm::FunctionType::get(
1134  get_int_type(32, cgen_state_->context_), filter_func_arg_types, false);
1135  cgen_state_->filter_func_->setName("old_filter_func");
1136  auto filter_func2 = llvm::Function::Create(ft,
1137  llvm::Function::ExternalLinkage,
1138  "filter_func",
1139  cgen_state_->filter_func_->getParent());
1140  CHECK_EQ(filter_func2->arg_size(), cgen_state_->filter_func_args_.v_.size());
1141  auto arg_it = cgen_state_->filter_func_args_.begin();
1142  size_t i = 0;
1143  for (llvm::Function::arg_iterator I = filter_func2->arg_begin(),
1144  E = filter_func2->arg_end();
1145  I != E;
1146  ++I, ++arg_it) {
1147  arg_it->second = &*I;
1148  if (arg_it->first->hasName()) {
1149  I->setName(arg_it->first->getName());
1150  } else {
1151  I->setName("extra" + std::to_string(i++));
1152  }
1153  }
1154 
1155  // copy the filter_func function body over
1156  // see
1157  // https://stackoverflow.com/questions/12864106/move-function-body-avoiding-full-cloning/18751365
1158  filter_func2->getBasicBlockList().splice(
1159  filter_func2->begin(), cgen_state_->filter_func_->getBasicBlockList());
1160 
1161  if (cgen_state_->current_func_ == cgen_state_->filter_func_) {
1162  cgen_state_->current_func_ = filter_func2;
1163  }
1164  cgen_state_->filter_func_ = filter_func2;
1165 
1166  // loop over all the operands in the filter func
1167  for (auto bb_it = cgen_state_->filter_func_->begin();
1168  bb_it != cgen_state_->filter_func_->end();
1169  ++bb_it) {
1170  for (auto instr_it = bb_it->begin(); instr_it != bb_it->end(); ++instr_it) {
1171  size_t i = 0;
1172  for (auto op_it = instr_it->op_begin(); op_it != instr_it->op_end(); ++op_it, ++i) {
1173  llvm::Value* v = op_it->get();
1174  if (auto arg_it = cgen_state_->filter_func_args_.find(v);
1175  arg_it != cgen_state_->filter_func_args_.end()) {
1176  // replace row func value with a filter func arg
1177  llvm::Use* use = &*op_it;
1178  use->set(arg_it->second);
1179  }
1180  }
1181  }
1182  }
1183 }
1184 
1185 llvm::Value* Executor::addJoinLoopIterator(const std::vector<llvm::Value*>& prev_iters,
1186  const size_t level_idx) {
1187  AUTOMATIC_IR_METADATA(cgen_state_.get());
1188  // Iterators are added for loop-outer joins when the head of the loop is generated,
1189  // then once again when the body if generated. Allow this instead of special handling
1190  // of call sites.
1191  const auto it = cgen_state_->scan_idx_to_hash_pos_.find(level_idx);
1192  if (it != cgen_state_->scan_idx_to_hash_pos_.end()) {
1193  return it->second;
1194  }
1195  CHECK(!prev_iters.empty());
1196  llvm::Value* matching_row_index = prev_iters.back();
1197  const auto it_ok =
1198  cgen_state_->scan_idx_to_hash_pos_.emplace(level_idx, matching_row_index);
1199  CHECK(it_ok.second);
1200  return matching_row_index;
1201 }
1202 
1203 void Executor::codegenJoinLoops(const std::vector<JoinLoop>& join_loops,
1204  const RelAlgExecutionUnit& ra_exe_unit,
1205  GroupByAndAggregate& group_by_and_aggregate,
1206  llvm::Function* query_func,
1207  llvm::BasicBlock* entry_bb,
1209  const CompilationOptions& co,
1210  const ExecutionOptions& eo) {
1211  AUTOMATIC_IR_METADATA(cgen_state_.get());
1212  const auto exit_bb =
1213  llvm::BasicBlock::Create(cgen_state_->context_, "exit", cgen_state_->current_func_);
1214  cgen_state_->ir_builder_.SetInsertPoint(exit_bb);
1215  cgen_state_->ir_builder_.CreateRet(cgen_state_->llInt<int32_t>(0));
1216  cgen_state_->ir_builder_.SetInsertPoint(entry_bb);
1217  CodeGenerator code_generator(this);
1218 
1219  llvm::BasicBlock* loops_entry_bb{nullptr};
1220  auto has_range_join =
1221  std::any_of(join_loops.begin(), join_loops.end(), [](const auto& join_loop) {
1222  return join_loop.kind() == JoinLoopKind::MultiSet;
1223  });
1224  if (has_range_join) {
1225  CHECK_EQ(join_loops.size(), size_t(1));
1226  const auto element_count =
1227  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_), 9);
1228 
1229  auto compute_packed_offset = [](const int32_t x, const int32_t y) -> uint64_t {
1230  const uint64_t y_shifted = static_cast<uint64_t>(y) << 32;
1231  return y_shifted | static_cast<uint32_t>(x);
1232  };
1233 
1234  const auto values_arr = std::vector<llvm::Constant*>{
1235  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_), 0),
1236  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1237  compute_packed_offset(0, 1)),
1238  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1239  compute_packed_offset(0, -1)),
1240  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1241  compute_packed_offset(1, 0)),
1242  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1243  compute_packed_offset(1, 1)),
1244  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1245  compute_packed_offset(1, -1)),
1246  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1247  compute_packed_offset(-1, 0)),
1248  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1249  compute_packed_offset(-1, 1)),
1250  llvm::ConstantInt::get(get_int_type(64, cgen_state_->context_),
1251  compute_packed_offset(-1, -1))};
1252 
1253  const auto constant_values_array = llvm::ConstantArray::get(
1254  get_int_array_type(64, 9, cgen_state_->context_), values_arr);
1255  CHECK(cgen_state_->module_);
1256  const auto values =
1257  new llvm::GlobalVariable(*cgen_state_->module_,
1258  get_int_array_type(64, 9, cgen_state_->context_),
1259  true,
1260  llvm::GlobalValue::LinkageTypes::InternalLinkage,
1261  constant_values_array);
1262  JoinLoop join_loop(
1265  [element_count, values](const std::vector<llvm::Value*>& v) {
1266  JoinLoopDomain domain{{0}};
1267  domain.element_count = element_count;
1268  domain.values_buffer = values;
1269  return domain;
1270  },
1271  nullptr,
1272  nullptr,
1273  nullptr,
1274  nullptr,
1275  "range_key_loop");
1276 
1277  loops_entry_bb = JoinLoop::codegen(
1278  {join_loop},
1279  [this,
1280  query_func,
1281  &query_mem_desc,
1282  &co,
1283  &eo,
1284  &group_by_and_aggregate,
1285  &join_loops,
1286  &ra_exe_unit](const std::vector<llvm::Value*>& prev_iters) {
1287  auto& builder = cgen_state_->ir_builder_;
1288 
1289  auto body_exit_bb =
1290  llvm::BasicBlock::Create(cgen_state_->context_,
1291  "range_key_inner_body_exit",
1292  builder.GetInsertBlock()->getParent());
1293 
1294  auto range_key_body_bb =
1295  llvm::BasicBlock::Create(cgen_state_->context_,
1296  "range_key_loop_body",
1297  builder.GetInsertBlock()->getParent());
1298  builder.SetInsertPoint(range_key_body_bb);
1299 
1300  const auto body_loops_entry_bb = JoinLoop::codegen(
1301  join_loops,
1302  [this,
1303  query_func,
1304  &query_mem_desc,
1305  &co,
1306  &eo,
1307  &group_by_and_aggregate,
1308  &join_loops,
1309  &ra_exe_unit](const std::vector<llvm::Value*>& prev_iters) {
1310  addJoinLoopIterator(prev_iters, join_loops.size());
1311  auto& builder = cgen_state_->ir_builder_;
1312  const auto loop_body_bb =
1313  llvm::BasicBlock::Create(builder.getContext(),
1314  "loop_body",
1315  builder.GetInsertBlock()->getParent());
1316  builder.SetInsertPoint(loop_body_bb);
1317  const bool can_return_error =
1318  compileBody(ra_exe_unit, group_by_and_aggregate, query_mem_desc, co);
1319  if (can_return_error || cgen_state_->needs_error_check_ ||
1320  eo.with_dynamic_watchdog || eo.allow_runtime_query_interrupt) {
1321  createErrorCheckControlFlow(query_func,
1322  eo.with_dynamic_watchdog,
1323  eo.allow_runtime_query_interrupt,
1324  join_loops,
1325  co.device_type,
1326  group_by_and_aggregate.query_infos_);
1327  }
1328  return loop_body_bb;
1329  },
1330  prev_iters.back(),
1331  body_exit_bb,
1332  cgen_state_.get());
1333 
1334  builder.SetInsertPoint(range_key_body_bb);
1335  cgen_state_->ir_builder_.CreateBr(body_loops_entry_bb);
1336 
1337  builder.SetInsertPoint(body_exit_bb);
1338  return range_key_body_bb;
1339  },
1340  code_generator.posArg(nullptr),
1341  exit_bb,
1342  cgen_state_.get());
1343  } else {
1344  loops_entry_bb = JoinLoop::codegen(
1345  join_loops,
1346  /*body_codegen=*/
1347  [this,
1348  query_func,
1349  &query_mem_desc,
1350  &co,
1351  &eo,
1352  &group_by_and_aggregate,
1353  &join_loops,
1354  &ra_exe_unit](const std::vector<llvm::Value*>& prev_iters) {
1355  AUTOMATIC_IR_METADATA(cgen_state_.get());
1356  addJoinLoopIterator(prev_iters, join_loops.size());
1357  auto& builder = cgen_state_->ir_builder_;
1358  const auto loop_body_bb = llvm::BasicBlock::Create(
1359  builder.getContext(), "loop_body", builder.GetInsertBlock()->getParent());
1360  builder.SetInsertPoint(loop_body_bb);
1361  const bool can_return_error =
1362  compileBody(ra_exe_unit, group_by_and_aggregate, query_mem_desc, co);
1363  if (can_return_error || cgen_state_->needs_error_check_ ||
1365  createErrorCheckControlFlow(query_func,
1368  join_loops,
1369  co.device_type,
1370  group_by_and_aggregate.query_infos_);
1371  }
1372  return loop_body_bb;
1373  },
1374  /*outer_iter=*/code_generator.posArg(nullptr),
1375  exit_bb,
1376  cgen_state_.get());
1377  }
1378  CHECK(loops_entry_bb);
1379  cgen_state_->ir_builder_.SetInsertPoint(entry_bb);
1380  cgen_state_->ir_builder_.CreateBr(loops_entry_bb);
1381 }
1382 
1384  Analyzer::Expr* group_by_col,
1385  const size_t col_width,
1386  const CompilationOptions& co,
1387  const bool translate_null_val,
1388  const int64_t translated_null_val,
1389  DiamondCodegen& diamond_codegen,
1390  std::stack<llvm::BasicBlock*>& array_loops,
1391  const bool thread_mem_shared) {
1392  AUTOMATIC_IR_METADATA(cgen_state_.get());
1393  CHECK_GE(col_width, sizeof(int32_t));
1394  CodeGenerator code_generator(this);
1395  auto group_key = code_generator.codegen(group_by_col, true, co).front();
1396  auto key_to_cache = group_key;
1397  if (dynamic_cast<Analyzer::UOper*>(group_by_col) &&
1398  static_cast<Analyzer::UOper*>(group_by_col)->get_optype() == kUNNEST) {
1399  auto preheader = cgen_state_->ir_builder_.GetInsertBlock();
1400  auto array_loop_head = llvm::BasicBlock::Create(cgen_state_->context_,
1401  "array_loop_head",
1402  cgen_state_->current_func_,
1403  preheader->getNextNode());
1404  diamond_codegen.setFalseTarget(array_loop_head);
1405  const auto ret_ty = get_int_type(32, cgen_state_->context_);
1406  auto array_idx_ptr = cgen_state_->ir_builder_.CreateAlloca(ret_ty);
1407  CHECK(array_idx_ptr);
1408  cgen_state_->ir_builder_.CreateStore(cgen_state_->llInt(int32_t(0)), array_idx_ptr);
1409  const auto arr_expr = static_cast<Analyzer::UOper*>(group_by_col)->get_operand();
1410  const auto& array_ti = arr_expr->get_type_info();
1411  CHECK(array_ti.is_array());
1412  const auto& elem_ti = array_ti.get_elem_type();
1413  auto array_len =
1414  (array_ti.get_size() > 0)
1415  ? cgen_state_->llInt(array_ti.get_size() / elem_ti.get_size())
1416  : cgen_state_->emitExternalCall(
1417  "array_size",
1418  ret_ty,
1419  {group_key,
1420  code_generator.posArg(arr_expr),
1421  cgen_state_->llInt(log2_bytes(elem_ti.get_logical_size()))});
1422  cgen_state_->ir_builder_.CreateBr(array_loop_head);
1423  cgen_state_->ir_builder_.SetInsertPoint(array_loop_head);
1424  CHECK(array_len);
1425  auto array_idx = cgen_state_->ir_builder_.CreateLoad(
1426  array_idx_ptr->getType()->getPointerElementType(), array_idx_ptr);
1427  auto bound_check = cgen_state_->ir_builder_.CreateICmp(
1428  llvm::ICmpInst::ICMP_SLT, array_idx, array_len);
1429  auto array_loop_body = llvm::BasicBlock::Create(
1430  cgen_state_->context_, "array_loop_body", cgen_state_->current_func_);
1431  cgen_state_->ir_builder_.CreateCondBr(
1432  bound_check,
1433  array_loop_body,
1434  array_loops.empty() ? diamond_codegen.orig_cond_false_ : array_loops.top());
1435  cgen_state_->ir_builder_.SetInsertPoint(array_loop_body);
1436  cgen_state_->ir_builder_.CreateStore(
1437  cgen_state_->ir_builder_.CreateAdd(array_idx, cgen_state_->llInt(int32_t(1))),
1438  array_idx_ptr);
1439  auto array_at_fname = "array_at_" + numeric_type_name(elem_ti);
1440  if (array_ti.get_size() < 0) {
1441  if (array_ti.get_notnull()) {
1442  array_at_fname = "notnull_" + array_at_fname;
1443  }
1444  array_at_fname = "varlen_" + array_at_fname;
1445  }
1446  const auto ar_ret_ty =
1447  elem_ti.is_fp()
1448  ? (elem_ti.get_type() == kDOUBLE
1449  ? llvm::Type::getDoubleTy(cgen_state_->context_)
1450  : llvm::Type::getFloatTy(cgen_state_->context_))
1451  : get_int_type(elem_ti.get_logical_size() * 8, cgen_state_->context_);
1452  group_key = cgen_state_->emitExternalCall(
1453  array_at_fname,
1454  ar_ret_ty,
1455  {group_key, code_generator.posArg(arr_expr), array_idx});
1457  elem_ti, isArchMaxwell(co.device_type), thread_mem_shared)) {
1458  key_to_cache = spillDoubleElement(group_key, ar_ret_ty);
1459  } else {
1460  key_to_cache = group_key;
1461  }
1462  CHECK(array_loop_head);
1463  array_loops.push(array_loop_head);
1464  }
1465  cgen_state_->group_by_expr_cache_.push_back(key_to_cache);
1466  llvm::Value* orig_group_key{nullptr};
1467  if (translate_null_val) {
1468  const std::string translator_func_name(
1469  col_width == sizeof(int32_t) ? "translate_null_key_i32_" : "translate_null_key_");
1470  const auto& ti = group_by_col->get_type_info();
1471  const auto key_type = get_int_type(ti.get_logical_size() * 8, cgen_state_->context_);
1472  orig_group_key = group_key;
1473  group_key = cgen_state_->emitCall(
1474  translator_func_name + numeric_type_name(ti),
1475  {group_key,
1476  static_cast<llvm::Value*>(
1477  llvm::ConstantInt::get(key_type, inline_int_null_val(ti))),
1478  static_cast<llvm::Value*>(llvm::ConstantInt::get(
1479  llvm::Type::getInt64Ty(cgen_state_->context_), translated_null_val))});
1480  }
1481  group_key = cgen_state_->ir_builder_.CreateBitCast(
1482  cgen_state_->castToTypeIn(group_key, col_width * 8),
1483  get_int_type(col_width * 8, cgen_state_->context_));
1484  if (orig_group_key) {
1485  orig_group_key = cgen_state_->ir_builder_.CreateBitCast(
1486  cgen_state_->castToTypeIn(orig_group_key, col_width * 8),
1487  get_int_type(col_width * 8, cgen_state_->context_));
1488  }
1489  return {group_key, orig_group_key};
1490 }
1491 
1493  Executor* executor,
1494  llvm::Value* nullable_lv,
1495  const SQLTypeInfo& nullable_ti,
1496  const std::string& name)
1497  : cgen_state(cgen_state), name(name) {
1498  AUTOMATIC_IR_METADATA(cgen_state);
1499  CHECK(nullable_ti.is_number() || nullable_ti.is_time() || nullable_ti.is_boolean() ||
1500  nullable_ti.is_dict_encoded_string());
1501 
1502  llvm::Value* is_null_lv{nullptr};
1503  if (nullable_ti.is_fp()) {
1504  is_null_lv = cgen_state->ir_builder_.CreateFCmp(
1505  llvm::FCmpInst::FCMP_OEQ, nullable_lv, cgen_state->inlineFpNull(nullable_ti));
1506  } else if (nullable_ti.is_boolean() &&
1507  nullable_lv->getType()->getIntegerBitWidth() == 1) {
1508  is_null_lv = cgen_state->ir_builder_.CreateICmp(
1509  llvm::ICmpInst::ICMP_EQ, nullable_lv, cgen_state->llBool(true));
1510  } else {
1511  is_null_lv = cgen_state->ir_builder_.CreateICmp(
1512  llvm::ICmpInst::ICMP_EQ, nullable_lv, cgen_state->inlineIntNull(nullable_ti));
1513  }
1514  CHECK(is_null_lv);
1515  null_check =
1516  std::make_unique<DiamondCodegen>(is_null_lv, executor, false, name, nullptr, false);
1517 
1518  // generate a phi node depending on whether we got a null or not
1519  nullcheck_bb = llvm::BasicBlock::Create(
1520  cgen_state->context_, name + "_bb", cgen_state->current_func_);
1521 
1522  // update the blocks created by diamond codegen to point to the newly created phi
1523  // block
1524  cgen_state->ir_builder_.SetInsertPoint(null_check->cond_true_);
1525  cgen_state->ir_builder_.CreateBr(nullcheck_bb);
1526  cgen_state->ir_builder_.SetInsertPoint(null_check->cond_false_);
1527 }
1528 
1529 llvm::Value* CodeGenerator::NullCheckCodegen::finalize(llvm::Value* null_lv,
1530  llvm::Value* notnull_lv) {
1531  AUTOMATIC_IR_METADATA(cgen_state);
1532  CHECK(null_check);
1533  cgen_state->ir_builder_.CreateBr(nullcheck_bb);
1534 
1535  CHECK_EQ(null_lv->getType(), notnull_lv->getType());
1536 
1537  cgen_state->ir_builder_.SetInsertPoint(nullcheck_bb);
1538  nullcheck_value =
1539  cgen_state->ir_builder_.CreatePHI(null_lv->getType(), 2, name + "_value");
1540  nullcheck_value->addIncoming(notnull_lv, null_check->cond_false_);
1541  nullcheck_value->addIncoming(null_lv, null_check->cond_true_);
1542 
1543  null_check.reset(nullptr);
1544  cgen_state->ir_builder_.SetInsertPoint(nullcheck_bb);
1545  return nullcheck_value;
1546 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
bool g_enable_left_join_filter_hoisting
Definition: Execute.cpp:103
NullCheckCodegen(CgenState *cgen_state, Executor *executor, llvm::Value *nullable_lv, const SQLTypeInfo &nullable_ti, const std::string &name="")
Definition: IRCodegen.cpp:1492
void codegenJoinLoops(const std::vector< JoinLoop > &join_loops, const RelAlgExecutionUnit &ra_exe_unit, GroupByAndAggregate &group_by_and_aggregate, llvm::Function *query_func, llvm::BasicBlock *entry_bb, QueryMemoryDescriptor &query_mem_desc, const CompilationOptions &co, const ExecutionOptions &eo)
Definition: IRCodegen.cpp:1203
#define IS_LOGIC(X)
Definition: sqldefs.h:61
const Expr * get_partition_count() const
Definition: Analyzer.h:1201
#define NULL_DOUBLE
JoinType
Definition: sqldefs.h:174
std::vector< llvm::Value * > outer_join_match_found_per_level_
Definition: CgenState.h:395
bool is_constant_expr() const
Definition: Analyzer.h:1246
std::unordered_map< size_t, std::vector< std::shared_ptr< Analyzer::Expr > > > left_join_non_hashtable_quals_
Definition: PlanState.h:61
llvm::Value * codegenConstantWidthBucketExpr(const Analyzer::WidthBucketExpr *, const CompilationOptions &)
Definition: IRCodegen.cpp:364
llvm::BasicBlock * nullcheck_bb
llvm::Value * element_count
Definition: JoinLoop.h:46
llvm::Value * values_buffer
Definition: JoinLoop.h:49
#define IS_EQUIVALENCE(X)
Definition: sqldefs.h:69
llvm::Value * codegenArith(const Analyzer::BinOper *, const CompilationOptions &)
CgenState * cgen_state_
GroupColLLVMValue groupByColumnCodegen(Analyzer::Expr *group_by_col, const size_t col_width, const CompilationOptions &, const bool translate_null_val, const int64_t translated_null_val, DiamondCodegen &, std::stack< llvm::BasicBlock * > &, const bool thread_mem_shared)
Definition: IRCodegen.cpp:1383
bool is_fp() const
Definition: sqltypes.h:571
llvm::IRBuilder ir_builder_
Definition: CgenState.h:384
std::function< llvm::BasicBlock *(llvm::BasicBlock *, llvm::BasicBlock *, const std::string &, llvm::Function *, CgenState *)> HoistedFiltersCallback
Definition: JoinLoop.h:61
llvm::Value * posArg(const Analyzer::Expr *) const
Definition: ColumnIR.cpp:590
std::string join(T const &container, std::string const &delim)
std::vector< InputDescriptor > input_descs
#define UNREACHABLE()
Definition: Logger.h:338
#define CHECK_GE(x, y)
Definition: Logger.h:306
bool need_patch_unnest_double(const SQLTypeInfo &ti, const bool is_maxwell, const bool mem_shared)
Definition: sqldefs.h:48
llvm::ConstantInt * llBool(const bool v) const
Definition: CgenState.h:263
virtual std::vector< llvm::Value * > codegenColumn(const Analyzer::ColumnVar *, const bool fetch_column, const CompilationOptions &)
Definition: ColumnIR.cpp:94
void set_constant_expr() const
Definition: Analyzer.h:1245
unsigned g_trivial_loop_join_threshold
Definition: Execute.cpp:92
llvm::Value * codegenArrayAt(const Analyzer::BinOper *, const CompilationOptions &)
Definition: ArrayIR.cpp:26
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:391
void setFalseTarget(llvm::BasicBlock *cond_false)
QualsConjunctiveForm qual_to_conjunctive_form(const std::shared_ptr< Analyzer::Expr > qual_expr)
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
bool is_number() const
Definition: sqltypes.h:574
double inline_fp_null_val(const SQL_TYPE_INFO &ti)
std::vector< llvm::Value * > codegenGeoBinOper(const Analyzer::GeoBinOper *, const CompilationOptions &)
Definition: GeoIR.cpp:261
bool is_time() const
Definition: sqltypes.h:577
std::shared_ptr< HashJoin > hash_table
Definition: Execute.h:1236
double get_bound_val(const Analyzer::Expr *bound_expr) const
Definition: Analyzer.cpp:3913
std::string to_string(char const *&&v)
llvm::Function * row_func_
Definition: CgenState.h:374
llvm::Value * codegenIsNull(const Analyzer::UOper *, const CompilationOptions &)
Definition: LogicalIR.cpp:380
SQLOps get_optype() const
Definition: Analyzer.h:452
std::vector< llvm::Value * > codegenGeoExpr(const Analyzer::GeoExpr *, const CompilationOptions &)
Definition: GeoIR.cpp:95
llvm::LLVMContext & context_
Definition: CgenState.h:382
llvm::Function * current_func_
Definition: CgenState.h:376
llvm::Value * get_arg_by_name(llvm::Function *func, const std::string &name)
Definition: Execute.h:168
std::set< shared::TableKey > visitFunctionOper(const Analyzer::FunctionOper *func_expr) const final
Definition: IRCodegen.cpp:826
#define INJECT_TIMER(DESC)
Definition: measure.h:96
#define CHECK_NE(x, y)
Definition: Logger.h:302
const JoinQualsPerNestingLevel join_quals
std::vector< llvm::Value * > codegenGeoUOper(const Analyzer::GeoUOper *, const CompilationOptions &)
Definition: GeoIR.cpp:181
llvm::ConstantInt * inlineIntNull(const SQLTypeInfo &)
Definition: CgenState.cpp:65
TableIdToNodeMap table_id_to_node_map
llvm::Value * codegenWidthBucketExpr(const Analyzer::WidthBucketExpr *, const CompilationOptions &)
Definition: IRCodegen.cpp:437
llvm::Value * codegenCastBetweenIntTypes(llvm::Value *operand_lv, const SQLTypeInfo &operand_ti, const SQLTypeInfo &ti, bool upscale=true)
Definition: CastIR.cpp:427
llvm::Value * codegenFunctionOper(const Analyzer::FunctionOper *, const CompilationOptions &)
Executor * executor_
static llvm::BasicBlock * codegen(const std::vector< JoinLoop > &join_loops, const std::function< llvm::BasicBlock *(const std::vector< llvm::Value * > &)> &body_codegen, llvm::Value *outer_iter, llvm::BasicBlock *exit_bb, CgenState *cgen_state)
Definition: JoinLoop.cpp:50
void add_qualifier_to_execution_unit(RelAlgExecutionUnit &ra_exe_unit, const std::shared_ptr< Analyzer::Expr > &qual)
Definition: IRCodegen.cpp:535
const std::vector< InputTableInfo > & query_infos_
Definition: PlanState.h:65
bool needs_error_check_
Definition: CgenState.h:405
bool is_boolean() const
Definition: sqltypes.h:580
ExpressionRange getExpressionRange(const Analyzer::BinOper *expr, const std::vector< InputTableInfo > &query_infos, const Executor *, boost::optional< std::list< std::shared_ptr< Analyzer::Expr >>> simple_quals)
std::vector< llvm::Value * > codegenArrayExpr(const Analyzer::ArrayExpr *, const CompilationOptions &)
Definition: ArrayIR.cpp:97
#define AUTOMATIC_IR_METADATA(CGENSTATE)
llvm::BasicBlock * orig_cond_false_
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:79
llvm::Value * codegenUMinus(const Analyzer::UOper *, const CompilationOptions &)
llvm::Value * emitCall(const std::string &fname, const std::vector< llvm::Value * > &args)
Definition: CgenState.cpp:217
llvm::Value * slot_lookup_result
Definition: JoinLoop.h:47
ExecutorDeviceType device_type
Definition: sqldefs.h:33
PlanState * plan_state_
std::vector< llvm::Value * > codegen(const Analyzer::Expr *, const bool fetch_columns, const CompilationOptions &)
Definition: IRCodegen.cpp:30
#define CHECK_LT(x, y)
Definition: Logger.h:303
const std::vector< InputTableInfo > & query_infos_
Definition: sqldefs.h:71
Expression class for string functions The &quot;arg&quot; constructor parameter must be an expression that reso...
Definition: Analyzer.h:1601
std::set< shared::TableKey > aggregateResult(const std::set< shared::TableKey > &aggregate, const std::set< shared::TableKey > &next_result) const final
Definition: IRCodegen.cpp:845
#define CHECK_LE(x, y)
Definition: Logger.h:304
std::shared_ptr< HashJoin > buildCurrentLevelHashTable(const JoinCondition &current_level_join_conditions, size_t level_idx, RelAlgExecutionUnit &ra_exe_unit, const CompilationOptions &co, const std::vector< InputTableInfo > &query_infos, ColumnCacheMap &column_cache, std::vector< std::string > &fail_reasons)
Definition: IRCodegen.cpp:1026
#define IS_ARITHMETIC(X)
Definition: sqldefs.h:62
bool isHintRegistered(const QueryHint hint) const
Definition: QueryHint.h:383
const Expr * get_arg() const
Definition: Analyzer.h:962
std::set< shared::TableKey > visitBinOper(const Analyzer::BinOper *bin_oper) const final
Definition: IRCodegen.cpp:835
std::unordered_map< shared::TableKey, std::unordered_map< int, std::shared_ptr< const ColumnarResults >>> ColumnCacheMap
std::set< shared::TableKey > visitUOper(const Analyzer::UOper *u_oper) const final
Definition: IRCodegen.cpp:841
llvm::StructType * createStringViewStructType()
int32_t get_partition_count_val() const
Definition: Analyzer.cpp:3923
static const int32_t ERR_WIDTH_BUCKET_INVALID_ARGUMENT
Definition: Execute.h:1630
llvm::Value * toBool(llvm::Value *)
Definition: LogicalIR.cpp:343
std::vector< llvm::Value * > codegenGeoColumnVar(const Analyzer::GeoColumnVar *, const bool fetch_columns, const CompilationOptions &co)
Definition: GeoIR.cpp:52
llvm::Value * codegenFunctionOperWithCustomTypeHandling(const Analyzer::FunctionOperWithCustomTypeHandling *, const CompilationOptions &)
llvm::Value * codegenCmp(const Analyzer::BinOper *, const CompilationOptions &)
Definition: CompareIR.cpp:230
std::list< std::shared_ptr< Analyzer::Expr > > getSimpleQuals() const
Definition: PlanState.h:97
const Expr * get_target_value() const
Definition: Analyzer.h:1198
std::list< std::shared_ptr< Analyzer::Expr > > quals
llvm::ConstantInt * llInt(const T v) const
Definition: CgenState.h:249
llvm::Value * codegenUnnest(const Analyzer::UOper *, const CompilationOptions &)
Definition: ArrayIR.cpp:20
llvm::Value * addJoinLoopIterator(const std::vector< llvm::Value * > &prev_iters, const size_t level_idx)
Definition: IRCodegen.cpp:1185
std::list< std::shared_ptr< Analyzer::Expr > > quals
RegisteredQueryHint query_hint
llvm::Value * finalize(llvm::Value *null_lv, llvm::Value *notnull_lv)
Definition: IRCodegen.cpp:1529
#define CHECK(condition)
Definition: Logger.h:291
bool can_skip_out_of_bound_check() const
Definition: Analyzer.h:1243
llvm::Value * codegenLogical(const Analyzer::BinOper *, const CompilationOptions &)
Definition: LogicalIR.cpp:298
void check_if_loop_join_is_allowed(RelAlgExecutionUnit &ra_exe_unit, const ExecutionOptions &eo, const std::vector< InputTableInfo > &query_infos, const size_t level_idx, const std::string &fail_reason)
Definition: IRCodegen.cpp:545
int64_t inline_int_null_val(const SQL_TYPE_INFO &ti)
llvm::ConstantInt * ll_bool(const bool v, llvm::LLVMContext &context)
size_t loop_join_inner_table_max_num_rows
Definition: QueryHint.h:357
llvm::Value * codegenCast(const Analyzer::UOper *, const CompilationOptions &)
Definition: CastIR.cpp:21
uint32_t log2_bytes(const uint32_t bytes)
Definition: Execute.h:198
std::string numeric_type_name(const SQLTypeInfo &ti)
Definition: Execute.h:230
bool is_dict_encoded_string() const
Definition: sqltypes.h:641
Definition: sqltypes.h:72
void skip_out_of_bound_check() const
Definition: Analyzer.h:1244
void redeclareFilterFunction()
Definition: IRCodegen.cpp:1086
bool any_of(std::vector< Analyzer::Expr * > const &target_exprs)
const Expr * get_lower_bound() const
Definition: Analyzer.h:1199
std::vector< JoinLoop > buildJoinLoops(RelAlgExecutionUnit &ra_exe_unit, const CompilationOptions &co, const ExecutionOptions &eo, const std::vector< InputTableInfo > &query_infos, ColumnCacheMap &column_cache)
Definition: IRCodegen.cpp:610
std::function< llvm::Value *(const std::vector< llvm::Value * > &, llvm::Value *)> buildIsDeletedCb(const RelAlgExecutionUnit &ra_exe_unit, const size_t level_idx, const CompilationOptions &co)
Definition: IRCodegen.cpp:967
string name
Definition: setup.in.py:72
JoinLoop::HoistedFiltersCallback buildHoistLeftHandSideFiltersCb(const RelAlgExecutionUnit &ra_exe_unit, const size_t level_idx, const shared::TableKey &inner_table_key, const CompilationOptions &co)
Definition: IRCodegen.cpp:858
const Expr * get_upper_bound() const
Definition: Analyzer.h:1200
const size_t g_maximum_conditions_to_coalesce
Definition: Datum.h:69
llvm::ArrayType * get_int_array_type(int const width, int count, llvm::LLVMContext &context)
Definition: sqldefs.h:38
SQLOps get_optype() const
Definition: Analyzer.h:383
#define VLOG(n)
Definition: Logger.h:388
std::unique_ptr< DiamondCodegen > null_check
std::set< shared::TableKey > visitColumnVar(const Analyzer::ColumnVar *col_expr) const final
Definition: IRCodegen.cpp:821
std::list< std::shared_ptr< Analyzer::Expr > > simple_quals
#define IS_COMPARISON(X)
Definition: sqldefs.h:58
double doubleval
Definition: Datum.h:76
HashTableBuildDagMap hash_table_build_plan_dag
llvm::ConstantFP * inlineFpNull(const SQLTypeInfo &)
Definition: CgenState.cpp:104
void check_valid_join_qual(std::shared_ptr< Analyzer::BinOper > &bin_oper)
Definition: IRCodegen.cpp:586
Executor * executor() const
size_t get_loop_join_size(const std::vector< InputTableInfo > &query_infos, const RelAlgExecutionUnit &ra_exe_unit)
Definition: Execute.cpp:1880
RUNTIME_EXPORT ALWAYS_INLINE DEVICE int32_t width_bucket_expr(const double target_value, const bool reversed, const double lower_bound, const double upper_bound, const int32_t partition_count)