OmniSciDB  340b00dbf6
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
DateTimeIR.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "CodeGenerator.h"
18 
19 #include "DateTimeUtils.h"
20 #include "Execute.h"
21 
22 using namespace DateTimeUtils;
23 
24 namespace {
25 
27  switch (field) {
28  case kEPOCH:
29  return "extract_epoch";
30  case kDATEEPOCH:
31  return "extract_dateepoch";
32  case kQUARTERDAY:
33  return "extract_quarterday";
34  case kHOUR:
35  return "extract_hour";
36  case kMINUTE:
37  return "extract_minute";
38  case kSECOND:
39  return "extract_second";
40  case kMILLISECOND:
41  return "extract_millisecond";
42  case kMICROSECOND:
43  return "extract_microsecond";
44  case kNANOSECOND:
45  return "extract_nanosecond";
46  case kDOW:
47  return "extract_dow";
48  case kISODOW:
49  return "extract_isodow";
50  case kDAY:
51  return "extract_day";
52  case kWEEK:
53  return "extract_week_monday";
54  case kWEEK_SUNDAY:
55  return "extract_week_sunday";
56  case kWEEK_SATURDAY:
57  return "extract_week_saturday";
58  case kDOY:
59  return "extract_day_of_year";
60  case kMONTH:
61  return "extract_month";
62  case kQUARTER:
63  return "extract_quarter";
64  case kYEAR:
65  return "extract_year";
66  }
67  UNREACHABLE();
68  return "";
69 }
70 
71 } // namespace
72 
73 llvm::Value* CodeGenerator::codegen(const Analyzer::ExtractExpr* extract_expr,
74  const CompilationOptions& co) {
75  AUTOMATIC_IR_METADATA(cgen_state_);
76  auto from_expr = codegen(extract_expr->get_from_expr(), true, co).front();
77  const int32_t extract_field{extract_expr->get_field()};
78  const auto& extract_expr_ti = extract_expr->get_from_expr()->get_type_info();
79  if (extract_field == kEPOCH) {
80  CHECK(extract_expr_ti.get_type() == kTIMESTAMP ||
81  extract_expr_ti.get_type() == kDATE);
82  if (from_expr->getType()->isIntegerTy(32)) {
83  from_expr =
84  cgen_state_->ir_builder_.CreateCast(llvm::Instruction::CastOps::SExt,
85  from_expr,
86  get_int_type(64, cgen_state_->context_));
87  return from_expr;
88  }
89  }
90  CHECK(from_expr->getType()->isIntegerTy(64));
91  if (extract_expr_ti.is_high_precision_timestamp()) {
92  from_expr = codegenExtractHighPrecisionTimestamps(
93  from_expr, extract_expr_ti, extract_expr->get_field());
94  }
95  if (!extract_expr_ti.is_high_precision_timestamp() &&
96  is_subsecond_extract_field(extract_expr->get_field())) {
97  from_expr =
98  extract_expr_ti.get_notnull()
99  ? cgen_state_->ir_builder_.CreateMul(
100  from_expr,
101  cgen_state_->llInt(
103  : cgen_state_->emitCall(
104  "mul_int64_t_nullable_lhs",
105  {from_expr,
106  cgen_state_->llInt(
108  cgen_state_->inlineIntNull(extract_expr_ti)});
109  }
110  const auto extract_fname = get_extract_function_name(extract_expr->get_field());
111  if (!extract_expr_ti.get_notnull()) {
112  llvm::BasicBlock* extract_nullcheck_bb{nullptr};
113  llvm::PHINode* extract_nullcheck_value{nullptr};
114  {
116  cgen_state_->ir_builder_.CreateICmp(
117  llvm::ICmpInst::ICMP_EQ,
118  from_expr,
119  cgen_state_->inlineIntNull(extract_expr_ti)),
120  executor(),
121  false,
122  "extract_nullcheck",
123  nullptr,
124  false);
125  // generate a phi node depending on whether we got a null or not
126  extract_nullcheck_bb = llvm::BasicBlock::Create(
127  cgen_state_->context_, "extract_nullcheck_bb", cgen_state_->current_func_);
128 
129  // update the blocks created by diamond codegen to point to the newly created phi
130  // block
131  cgen_state_->ir_builder_.SetInsertPoint(null_check.cond_true_);
132  cgen_state_->ir_builder_.CreateBr(extract_nullcheck_bb);
133  cgen_state_->ir_builder_.SetInsertPoint(null_check.cond_false_);
134  auto extract_call =
135  cgen_state_->emitExternalCall(extract_fname,
136  get_int_type(64, cgen_state_->context_),
137  std::vector<llvm::Value*>{from_expr});
138  cgen_state_->ir_builder_.CreateBr(extract_nullcheck_bb);
139 
140  cgen_state_->ir_builder_.SetInsertPoint(extract_nullcheck_bb);
141  extract_nullcheck_value = cgen_state_->ir_builder_.CreatePHI(
142  get_int_type(64, cgen_state_->context_), 2, "extract_value");
143  extract_nullcheck_value->addIncoming(extract_call, null_check.cond_false_);
144  extract_nullcheck_value->addIncoming(cgen_state_->inlineIntNull(extract_expr_ti),
145  null_check.cond_true_);
146  }
147 
148  // diamond codegen will set the insert point in its destructor. override it to
149  // continue using the extract nullcheck bb
150  CHECK(extract_nullcheck_bb);
151  cgen_state_->ir_builder_.SetInsertPoint(extract_nullcheck_bb);
152  CHECK(extract_nullcheck_value);
153  return extract_nullcheck_value;
154  } else {
155  return cgen_state_->emitExternalCall(extract_fname,
156  get_int_type(64, cgen_state_->context_),
157  std::vector<llvm::Value*>{from_expr});
158  }
159 }
160 
161 llvm::Value* CodeGenerator::codegen(const Analyzer::DateaddExpr* dateadd_expr,
162  const CompilationOptions& co) {
164  const auto& dateadd_expr_ti = dateadd_expr->get_type_info();
165  CHECK(dateadd_expr_ti.get_type() == kTIMESTAMP || dateadd_expr_ti.get_type() == kDATE);
166  auto datetime = codegen(dateadd_expr->get_datetime_expr(), true, co).front();
167  CHECK(datetime->getType()->isIntegerTy(64));
168  auto number = codegen(dateadd_expr->get_number_expr(), true, co).front();
169 
170  const auto& datetime_ti = dateadd_expr->get_datetime_expr()->get_type_info();
171  std::vector<llvm::Value*> dateadd_args{
172  cgen_state_->llInt(static_cast<int32_t>(dateadd_expr->get_field())),
173  number,
174  datetime};
175  std::string dateadd_fname{"DateAdd"};
176  if (is_subsecond_dateadd_field(dateadd_expr->get_field()) ||
177  dateadd_expr_ti.is_high_precision_timestamp()) {
178  dateadd_fname += "HighPrecision";
179  dateadd_args.push_back(
180  cgen_state_->llInt(static_cast<int32_t>(datetime_ti.get_dimension())));
181  }
182  if (!datetime_ti.get_notnull()) {
183  dateadd_args.push_back(cgen_state_->inlineIntNull(datetime_ti));
184  dateadd_fname += "Nullable";
185  }
186  return cgen_state_->emitExternalCall(dateadd_fname,
188  dateadd_args,
189  {llvm::Attribute::NoUnwind,
190  llvm::Attribute::ReadNone,
191  llvm::Attribute::Speculatable});
192 }
193 
194 llvm::Value* CodeGenerator::codegen(const Analyzer::DatediffExpr* datediff_expr,
195  const CompilationOptions& co) {
197  auto start = codegen(datediff_expr->get_start_expr(), true, co).front();
198  CHECK(start->getType()->isIntegerTy(64));
199  auto end = codegen(datediff_expr->get_end_expr(), true, co).front();
200  CHECK(end->getType()->isIntegerTy(32) || end->getType()->isIntegerTy(64));
201  const auto& start_ti = datediff_expr->get_start_expr()->get_type_info();
202  const auto& end_ti = datediff_expr->get_end_expr()->get_type_info();
203  std::vector<llvm::Value*> datediff_args{
204  cgen_state_->llInt(static_cast<int32_t>(datediff_expr->get_field())), start, end};
205  std::string datediff_fname{"DateDiff"};
206  if (start_ti.is_high_precision_timestamp() || end_ti.is_high_precision_timestamp()) {
207  datediff_fname += "HighPrecision";
208  datediff_args.push_back(
209  cgen_state_->llInt(static_cast<int32_t>(start_ti.get_dimension())));
210  datediff_args.push_back(
211  cgen_state_->llInt(static_cast<int32_t>(end_ti.get_dimension())));
212  }
213  const auto& ret_ti = datediff_expr->get_type_info();
214  if (!start_ti.get_notnull() || !end_ti.get_notnull()) {
215  datediff_args.push_back(cgen_state_->inlineIntNull(ret_ti));
216  datediff_fname += "Nullable";
217  }
219  datediff_fname, get_int_type(64, cgen_state_->context_), datediff_args);
220 }
221 
222 llvm::Value* CodeGenerator::codegen(const Analyzer::DatetruncExpr* datetrunc_expr,
223  const CompilationOptions& co) {
225  auto from_expr = codegen(datetrunc_expr->get_from_expr(), true, co).front();
226  const auto& datetrunc_expr_ti = datetrunc_expr->get_from_expr()->get_type_info();
227  CHECK(from_expr->getType()->isIntegerTy(64));
228  DatetruncField const field = datetrunc_expr->get_field();
229  if (datetrunc_expr_ti.is_high_precision_timestamp()) {
230  return codegenDateTruncHighPrecisionTimestamps(from_expr, datetrunc_expr_ti, field);
231  }
232  static_assert(dtSECOND + 1 == dtMILLISECOND, "Please keep these consecutive.");
233  static_assert(dtMILLISECOND + 1 == dtMICROSECOND, "Please keep these consecutive.");
234  static_assert(dtMICROSECOND + 1 == dtNANOSECOND, "Please keep these consecutive.");
235  if (dtSECOND <= field && field <= dtNANOSECOND) {
236  return cgen_state_->ir_builder_.CreateCast(llvm::Instruction::CastOps::SExt,
237  from_expr,
239  }
240  std::unique_ptr<CodeGenerator::NullCheckCodegen> nullcheck_codegen;
241  const bool is_nullable = !datetrunc_expr_ti.get_notnull();
242  if (is_nullable) {
243  nullcheck_codegen = std::make_unique<NullCheckCodegen>(
244  cgen_state_, executor(), from_expr, datetrunc_expr_ti, "date_trunc_nullcheck");
245  }
246  char const* const fname = datetrunc_fname_lookup.at(field);
247  auto ret = cgen_state_->emitExternalCall(
248  fname, get_int_type(64, cgen_state_->context_), {from_expr});
249  if (is_nullable) {
250  ret = nullcheck_codegen->finalize(ll_int(NULL_BIGINT, cgen_state_->context_), ret);
251  }
252  return ret;
253 }
254 
256  llvm::Value* ts_lv,
257  const SQLTypeInfo& ti,
258  const ExtractField& field) {
261  CHECK(ts_lv->getType()->isIntegerTy(64));
262  if (is_subsecond_extract_field(field)) {
263  const auto result =
265  if (result.first == kMULTIPLY) {
266  return ti.get_notnull()
267  ? cgen_state_->ir_builder_.CreateMul(
268  ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second)))
270  "mul_int64_t_nullable_lhs",
271  {ts_lv,
272  cgen_state_->llInt(static_cast<int64_t>(result.second)),
273  cgen_state_->inlineIntNull(ti)});
274  } else if (result.first == kDIVIDE) {
275  return ti.get_notnull()
276  ? cgen_state_->ir_builder_.CreateSDiv(
277  ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second)))
279  "floor_div_nullable_lhs",
280  {ts_lv,
281  cgen_state_->llInt(static_cast<int64_t>(result.second)),
282  cgen_state_->inlineIntNull(ti)});
283  } else {
284  return ts_lv;
285  }
286  }
287  return ti.get_notnull()
288  ? cgen_state_->ir_builder_.CreateSDiv(
289  ts_lv,
290  cgen_state_->llInt(static_cast<int64_t>(
291  get_timestamp_precision_scale(ti.get_dimension()))))
292  : cgen_state_->emitCall(
293  "floor_div_nullable_lhs",
294  {ts_lv,
295  cgen_state_->llInt(get_timestamp_precision_scale(ti.get_dimension())),
296  cgen_state_->inlineIntNull(ti)});
297 }
298 
300  llvm::Value* ts_lv,
301  const SQLTypeInfo& ti,
302  const DatetruncField& field) {
303  // Only needed for i in { 0, 3, 6, 9 }.
304  constexpr int64_t pow10[10]{1, 0, 0, 1000, 0, 0, 1000000, 0, 0, 1000000000};
307  CHECK(ts_lv->getType()->isIntegerTy(64));
308  bool const is_nullable = !ti.get_notnull();
309  static_assert(dtSECOND + 1 == dtMILLISECOND, "Please keep these consecutive.");
310  static_assert(dtMILLISECOND + 1 == dtMICROSECOND, "Please keep these consecutive.");
311  static_assert(dtMICROSECOND + 1 == dtNANOSECOND, "Please keep these consecutive.");
312  if (dtSECOND <= field && field <= dtNANOSECOND) {
313  unsigned const start_dim = ti.get_dimension(); // 0, 3, 6, 9
314  unsigned const trunc_dim = (field - dtSECOND) * 3; // 0, 3, 6, 9
315  if (start_dim <= trunc_dim) {
316  return ts_lv; // Truncating to an equal or higher precision has no effect.
317  }
318  int64_t const dscale = pow10[start_dim - trunc_dim]; // 1e3, 1e6, 1e9
319  if (is_nullable) {
320  ts_lv = cgen_state_->emitCall(
321  "floor_div_nullable_lhs",
322  {ts_lv, cgen_state_->llInt(dscale), cgen_state_->inlineIntNull(ti)});
323  return cgen_state_->emitCall(
324  "mul_int64_t_nullable_lhs",
325  {ts_lv, cgen_state_->llInt(dscale), cgen_state_->inlineIntNull(ti)});
326  } else {
327  ts_lv = cgen_state_->ir_builder_.CreateSDiv(ts_lv, cgen_state_->llInt(dscale));
328  return cgen_state_->ir_builder_.CreateMul(ts_lv, cgen_state_->llInt(dscale));
329  }
330  }
331  int64_t const scale = pow10[ti.get_dimension()];
332  ts_lv = is_nullable
334  "floor_div_nullable_lhs",
335  {ts_lv, cgen_state_->llInt(scale), cgen_state_->inlineIntNull(ti)})
336  : cgen_state_->ir_builder_.CreateSDiv(ts_lv, cgen_state_->llInt(scale));
337 
338  std::unique_ptr<CodeGenerator::NullCheckCodegen> nullcheck_codegen;
339  if (is_nullable) {
340  nullcheck_codegen = std::make_unique<NullCheckCodegen>(
341  cgen_state_, executor(), ts_lv, ti, "date_trunc_hp_nullcheck");
342  }
343  char const* const fname = datetrunc_fname_lookup.at(field);
344  ts_lv = cgen_state_->emitExternalCall(
345  fname, get_int_type(64, cgen_state_->context_), {ts_lv});
346  if (is_nullable) {
347  ts_lv =
348  nullcheck_codegen->finalize(ll_int(NULL_BIGINT, cgen_state_->context_), ts_lv);
349  }
350 
351  return is_nullable
352  ? cgen_state_->emitCall(
353  "mul_int64_t_nullable_lhs",
354  {ts_lv, cgen_state_->llInt(scale), cgen_state_->inlineIntNull(ti)})
355  : cgen_state_->ir_builder_.CreateMul(ts_lv, cgen_state_->llInt(scale));
356 }
const Expr * get_from_expr() const
Definition: Analyzer.h:1197
constexpr int64_t get_extract_timestamp_precision_scale(const ExtractField field)
Definition: DateTimeUtils.h:81
CgenState * cgen_state_
#define NULL_BIGINT
Definition: sqltypes.h:255
ExtractField get_field() const
Definition: Analyzer.h:1196
llvm::Value * emitExternalCall(const std::string &fname, llvm::Type *ret_type, const std::vector< llvm::Value * > args, const std::vector< llvm::Attribute::AttrKind > &fnattrs={}, const bool has_struct_return=false)
Definition: CgenState.h:222
llvm::ConstantInt * ll_int(const T v, llvm::LLVMContext &context)
llvm::IRBuilder ir_builder_
Definition: CgenState.h:329
const char * get_extract_function_name(ExtractField field)
Definition: DateTimeIR.cpp:26
#define UNREACHABLE()
Definition: Logger.h:241
llvm::Value * codegenExtractHighPrecisionTimestamps(llvm::Value *, const SQLTypeInfo &, const ExtractField &)
Definition: DateTimeIR.cpp:255
DatetruncField get_field() const
Definition: Analyzer.h:1321
const std::pair< SQLOps, int64_t > get_extract_high_precision_adjusted_scale(const ExtractField &field, const int32_t dimen)
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
llvm::LLVMContext & context_
Definition: CgenState.h:327
DatetruncField
Definition: DateTruncate.h:27
llvm::ConstantInt * inlineIntNull(const SQLTypeInfo &)
Definition: CgenState.cpp:27
#define AUTOMATIC_IR_METADATA(CGENSTATE)
const Expr * get_start_expr() const
Definition: Analyzer.h:1280
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:78
llvm::Value * emitCall(const std::string &fname, const std::vector< llvm::Value * > &args)
Definition: CgenState.cpp:137
std::vector< llvm::Value * > codegen(const Analyzer::Expr *, const bool fetch_columns, const CompilationOptions &)
Definition: IRCodegen.cpp:26
Definition: sqltypes.h:55
constexpr std::array< char const *, dtINVALID > datetrunc_fname_lookup
Definition: DateTruncate.h:49
const Expr * get_from_expr() const
Definition: Analyzer.h:1322
const Expr * get_datetime_expr() const
Definition: Analyzer.h:1239
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:332
ExtractField
DateaddField get_field() const
Definition: Analyzer.h:1237
constexpr bool is_subsecond_dateadd_field(const DateaddField field)
Definition: DateTimeUtils.h:99
llvm::ConstantInt * llInt(const T v) const
Definition: CgenState.h:300
const Expr * get_end_expr() const
Definition: Analyzer.h:1281
#define CHECK(condition)
Definition: Logger.h:197
constexpr int64_t get_timestamp_precision_scale(const int32_t dimen)
Definition: DateTimeUtils.h:51
bool is_high_precision_timestamp() const
Definition: sqltypes.h:723
llvm::Value * codegenDateTruncHighPrecisionTimestamps(llvm::Value *, const SQLTypeInfo &, const DatetruncField &)
Definition: DateTimeIR.cpp:299
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:337
DatetruncField get_field() const
Definition: Analyzer.h:1279
constexpr bool is_subsecond_extract_field(const ExtractField &field)
Definition: DateTimeUtils.h:95
const Expr * get_number_expr() const
Definition: Analyzer.h:1238
Executor * executor() const