OmniSciDB  06b3bd477c
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
QueryTemplateGenerator.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 "QueryTemplateGenerator.h"
18 #include "IRCodegenUtils.h"
19 #include "Shared/Logger.h"
20 
21 #include <llvm/IR/Constants.h>
22 #include <llvm/IR/IRBuilder.h>
23 #include <llvm/IR/Instructions.h>
24 #include <llvm/IR/Verifier.h>
25 
26 // This file was pretty much auto-generated by running:
27 // llc -march=cpp RuntimeFunctions.ll
28 // and formatting the results to be more readable.
29 
30 namespace {
31 
32 template <class Attributes>
33 llvm::Function* default_func_builder(llvm::Module* mod, const std::string& name) {
34  using namespace llvm;
35 
36  std::vector<Type*> func_args;
37  FunctionType* func_type = FunctionType::get(
38  /*Result=*/IntegerType::get(mod->getContext(), 32),
39  /*Params=*/func_args,
40  /*isVarArg=*/false);
41 
42  auto func_ptr = mod->getFunction(name);
43  if (!func_ptr) {
44  func_ptr = Function::Create(
45  /*Type=*/func_type,
46  /*Linkage=*/GlobalValue::ExternalLinkage,
47  /*Name=*/name,
48  mod); // (external, no body)
49  func_ptr->setCallingConv(CallingConv::C);
50  }
51 
52  Attributes func_pal;
53  {
54  SmallVector<Attributes, 4> Attrs;
55  Attributes PAS;
56  {
57  AttrBuilder B;
58  PAS = Attributes::get(mod->getContext(), ~0U, B);
59  }
60 
61  Attrs.push_back(PAS);
62  func_pal = Attributes::get(mod->getContext(), Attrs);
63  }
64  func_ptr->setAttributes(func_pal);
65 
66  return func_ptr;
67 }
68 
69 template <class Attributes>
70 llvm::Function* pos_start(llvm::Module* mod) {
71  return default_func_builder<Attributes>(mod, "pos_start");
72 }
73 
74 template <class Attributes>
75 llvm::Function* group_buff_idx(llvm::Module* mod) {
76  return default_func_builder<Attributes>(mod, "group_buff_idx");
77 }
78 
79 template <class Attributes>
80 llvm::Function* pos_step(llvm::Module* mod) {
81  using namespace llvm;
82 
83  std::vector<Type*> func_args;
84  FunctionType* func_type = FunctionType::get(
85  /*Result=*/IntegerType::get(mod->getContext(), 32),
86  /*Params=*/func_args,
87  /*isVarArg=*/false);
88 
89  auto func_ptr = mod->getFunction("pos_step");
90  if (!func_ptr) {
91  func_ptr = Function::Create(
92  /*Type=*/func_type,
93  /*Linkage=*/GlobalValue::ExternalLinkage,
94  /*Name=*/"pos_step",
95  mod); // (external, no body)
96  func_ptr->setCallingConv(CallingConv::C);
97  }
98 
99  Attributes func_pal;
100  {
101  SmallVector<Attributes, 4> Attrs;
102  Attributes PAS;
103  {
104  AttrBuilder B;
105  PAS = Attributes::get(mod->getContext(), ~0U, B);
106  }
107 
108  Attrs.push_back(PAS);
109  func_pal = Attributes::get(mod->getContext(), Attrs);
110  }
111  func_ptr->setAttributes(func_pal);
112 
113  return func_ptr;
114 }
115 
116 template <class Attributes>
117 llvm::Function* row_process(llvm::Module* mod,
118  const size_t aggr_col_count,
119  const bool hoist_literals) {
120  using namespace llvm;
121 
122  std::vector<Type*> func_args;
123  auto i8_type = IntegerType::get(mod->getContext(), 8);
124  auto i32_type = IntegerType::get(mod->getContext(), 32);
125  auto i64_type = IntegerType::get(mod->getContext(), 64);
126  auto pi32_type = PointerType::get(i32_type, 0);
127  auto pi64_type = PointerType::get(i64_type, 0);
128 
129  if (aggr_col_count) {
130  for (size_t i = 0; i < aggr_col_count; ++i) {
131  func_args.push_back(pi64_type);
132  }
133  } else { // group by query
134  func_args.push_back(pi64_type); // groups buffer
135  func_args.push_back(pi32_type); // 1 iff current row matched, else 0
136  func_args.push_back(pi32_type); // total rows matched from the caller
137  func_args.push_back(pi32_type); // total rows matched before atomic increment
138  func_args.push_back(pi32_type); // max number of slots in the output buffer
139  }
140 
141  func_args.push_back(pi64_type); // aggregate init values
142 
143  func_args.push_back(i64_type);
144  func_args.push_back(pi64_type);
145  func_args.push_back(pi64_type);
146  if (hoist_literals) {
147  func_args.push_back(PointerType::get(i8_type, 0));
148  }
149  FunctionType* func_type = FunctionType::get(
150  /*Result=*/i32_type,
151  /*Params=*/func_args,
152  /*isVarArg=*/false);
153 
154  std::string func_name{"row_process"};
155  auto func_ptr = mod->getFunction(func_name);
156 
157  if (!func_ptr) {
158  func_ptr = Function::Create(
159  /*Type=*/func_type,
160  /*Linkage=*/GlobalValue::ExternalLinkage,
161  /*Name=*/func_name,
162  mod); // (external, no body)
163  func_ptr->setCallingConv(CallingConv::C);
164 
165  Attributes func_pal;
166  {
167  SmallVector<Attributes, 4> Attrs;
168  Attributes PAS;
169  {
170  AttrBuilder B;
171  PAS = Attributes::get(mod->getContext(), ~0U, B);
172  }
173 
174  Attrs.push_back(PAS);
175  func_pal = Attributes::get(mod->getContext(), Attrs);
176  }
177  func_ptr->setAttributes(func_pal);
178  }
179 
180  return func_ptr;
181 }
182 
183 } // namespace
184 
185 template <class Attributes>
186 llvm::Function* query_template_impl(llvm::Module* mod,
187  const size_t aggr_col_count,
188  const bool hoist_literals,
189  const bool is_estimate_query,
190  const GpuSharedMemoryContext& gpu_smem_context) {
191  using namespace llvm;
192 
193  auto func_pos_start = pos_start<Attributes>(mod);
194  CHECK(func_pos_start);
195  auto func_pos_step = pos_step<Attributes>(mod);
196  CHECK(func_pos_step);
197  auto func_group_buff_idx = group_buff_idx<Attributes>(mod);
198  CHECK(func_group_buff_idx);
199  auto func_row_process = row_process<Attributes>(
200  mod, is_estimate_query ? 1 : aggr_col_count, hoist_literals);
201  CHECK(func_row_process);
202 
203  auto i8_type = IntegerType::get(mod->getContext(), 8);
204  auto i32_type = IntegerType::get(mod->getContext(), 32);
205  auto i64_type = IntegerType::get(mod->getContext(), 64);
206  auto pi8_type = PointerType::get(i8_type, 0);
207  auto ppi8_type = PointerType::get(pi8_type, 0);
208  auto pi32_type = PointerType::get(i32_type, 0);
209  auto pi64_type = PointerType::get(i64_type, 0);
210  auto ppi64_type = PointerType::get(pi64_type, 0);
211 
212  std::vector<Type*> query_args;
213  query_args.push_back(ppi8_type);
214  if (hoist_literals) {
215  query_args.push_back(pi8_type);
216  }
217  query_args.push_back(pi64_type);
218  query_args.push_back(pi64_type);
219  query_args.push_back(pi32_type);
220 
221  query_args.push_back(pi64_type);
222  query_args.push_back(ppi64_type);
223  query_args.push_back(i32_type);
224  query_args.push_back(pi64_type);
225  query_args.push_back(pi32_type);
226  query_args.push_back(pi32_type);
227 
228  FunctionType* query_func_type = FunctionType::get(
229  /*Result=*/Type::getVoidTy(mod->getContext()),
230  /*Params=*/query_args,
231  /*isVarArg=*/false);
232 
233  std::string query_template_name{"query_template"};
234  auto query_func_ptr = mod->getFunction(query_template_name);
235  CHECK(!query_func_ptr);
236 
237  query_func_ptr = Function::Create(
238  /*Type=*/query_func_type,
239  /*Linkage=*/GlobalValue::ExternalLinkage,
240  /*Name=*/query_template_name,
241  mod);
242  query_func_ptr->setCallingConv(CallingConv::C);
243 
244  Attributes query_func_pal;
245  {
246  SmallVector<Attributes, 4> Attrs;
247  Attributes PAS;
248  {
249  AttrBuilder B;
250  B.addAttribute(Attribute::NoCapture);
251  PAS = Attributes::get(mod->getContext(), 1U, B);
252  }
253 
254  Attrs.push_back(PAS);
255  {
256  AttrBuilder B;
257  B.addAttribute(Attribute::NoCapture);
258  PAS = Attributes::get(mod->getContext(), 2U, B);
259  }
260 
261  Attrs.push_back(PAS);
262 
263  {
264  AttrBuilder B;
265  B.addAttribute(Attribute::NoCapture);
266  Attrs.push_back(Attributes::get(mod->getContext(), 3U, B));
267  }
268 
269  {
270  AttrBuilder B;
271  B.addAttribute(Attribute::NoCapture);
272  Attrs.push_back(Attributes::get(mod->getContext(), 4U, B));
273  }
274 
275  Attrs.push_back(PAS);
276 
277  query_func_pal = Attributes::get(mod->getContext(), Attrs);
278  }
279  query_func_ptr->setAttributes(query_func_pal);
280 
281  Function::arg_iterator query_arg_it = query_func_ptr->arg_begin();
282  Value* byte_stream = &*query_arg_it;
283  byte_stream->setName("byte_stream");
284  Value* literals{nullptr};
285  if (hoist_literals) {
286  literals = &*(++query_arg_it);
287  literals->setName("literals");
288  }
289  Value* row_count_ptr = &*(++query_arg_it);
290  row_count_ptr->setName("row_count_ptr");
291  Value* frag_row_off_ptr = &*(++query_arg_it);
292  frag_row_off_ptr->setName("frag_row_off_ptr");
293  Value* max_matched_ptr = &*(++query_arg_it);
294  max_matched_ptr->setName("max_matched_ptr");
295  Value* agg_init_val = &*(++query_arg_it);
296  agg_init_val->setName("agg_init_val");
297  Value* out = &*(++query_arg_it);
298  out->setName("out");
299  Value* frag_idx = &*(++query_arg_it);
300  frag_idx->setName("frag_idx");
301  Value* join_hash_tables = &*(++query_arg_it);
302  join_hash_tables->setName("join_hash_tables");
303  Value* total_matched = &*(++query_arg_it);
304  total_matched->setName("total_matched");
305  Value* error_code = &*(++query_arg_it);
306  error_code->setName("error_code");
307 
308  auto bb_entry = BasicBlock::Create(mod->getContext(), ".entry", query_func_ptr, 0);
309  auto bb_preheader =
310  BasicBlock::Create(mod->getContext(), ".loop.preheader", query_func_ptr, 0);
311  auto bb_forbody = BasicBlock::Create(mod->getContext(), ".for.body", query_func_ptr, 0);
312  auto bb_crit_edge =
313  BasicBlock::Create(mod->getContext(), "._crit_edge", query_func_ptr, 0);
314  auto bb_exit = BasicBlock::Create(mod->getContext(), ".exit", query_func_ptr, 0);
315 
316  // Block (.entry)
317  std::vector<Value*> result_ptr_vec;
318  llvm::CallInst* smem_output_buffer{nullptr};
319  if (!is_estimate_query) {
320  for (size_t i = 0; i < aggr_col_count; ++i) {
321  auto result_ptr = new AllocaInst(i64_type, 0, "result", bb_entry);
322  result_ptr->setAlignment(LLVM_ALIGN(8));
323  result_ptr_vec.push_back(result_ptr);
324  }
325  if (gpu_smem_context.isSharedMemoryUsed()) {
326  auto init_smem_func = mod->getFunction("init_shared_mem");
327  CHECK(init_smem_func);
328  // only one slot per aggregate column is needed, and so we can initialize shared
329  // memory buffer for intermediate results to be exactly like the agg_init_val array
330  smem_output_buffer = CallInst::Create(
331  init_smem_func,
332  std::vector<llvm::Value*>{
333  agg_init_val,
334  llvm::ConstantInt::get(i32_type, aggr_col_count * sizeof(int64_t))},
335  "smem_buffer",
336  bb_entry);
337  }
338  }
339 
340  LoadInst* row_count = new LoadInst(row_count_ptr, "row_count", false, bb_entry);
341  row_count->setAlignment(LLVM_ALIGN(8));
342  row_count->setName("row_count");
343  std::vector<Value*> agg_init_val_vec;
344  if (!is_estimate_query) {
345  for (size_t i = 0; i < aggr_col_count; ++i) {
346  auto idx_lv = ConstantInt::get(i32_type, i);
347  auto agg_init_gep =
348  GetElementPtrInst::CreateInBounds(agg_init_val, idx_lv, "", bb_entry);
349  auto agg_init_val = new LoadInst(agg_init_gep, "", false, bb_entry);
350  agg_init_val->setAlignment(LLVM_ALIGN(8));
351  agg_init_val_vec.push_back(agg_init_val);
352  auto init_val_st = new StoreInst(agg_init_val, result_ptr_vec[i], false, bb_entry);
353  init_val_st->setAlignment(LLVM_ALIGN(8));
354  }
355  }
356 
357  CallInst* pos_start = CallInst::Create(func_pos_start, "pos_start", bb_entry);
358  pos_start->setCallingConv(CallingConv::C);
359  pos_start->setTailCall(true);
360  Attributes pos_start_pal;
361  pos_start->setAttributes(pos_start_pal);
362 
363  CallInst* pos_step = CallInst::Create(func_pos_step, "pos_step", bb_entry);
364  pos_step->setCallingConv(CallingConv::C);
365  pos_step->setTailCall(true);
366  Attributes pos_step_pal;
367  pos_step->setAttributes(pos_step_pal);
368 
369  CallInst* group_buff_idx = nullptr;
370  if (!is_estimate_query) {
371  group_buff_idx = CallInst::Create(func_group_buff_idx, "group_buff_idx", bb_entry);
372  group_buff_idx->setCallingConv(CallingConv::C);
373  group_buff_idx->setTailCall(true);
374  Attributes group_buff_idx_pal;
375  group_buff_idx->setAttributes(group_buff_idx_pal);
376  }
377 
378  CastInst* pos_start_i64 = new SExtInst(pos_start, i64_type, "", bb_entry);
379  ICmpInst* enter_or_not =
380  new ICmpInst(*bb_entry, ICmpInst::ICMP_SLT, pos_start_i64, row_count, "");
381  BranchInst::Create(bb_preheader, bb_exit, enter_or_not, bb_entry);
382 
383  // Block .loop.preheader
384  CastInst* pos_step_i64 = new SExtInst(pos_step, i64_type, "", bb_preheader);
385  BranchInst::Create(bb_forbody, bb_preheader);
386 
387  // Block .forbody
388  Argument* pos_inc_pre = new Argument(i64_type);
389  PHINode* pos = PHINode::Create(i64_type, 2, "pos", bb_forbody);
390  pos->addIncoming(pos_start_i64, bb_preheader);
391  pos->addIncoming(pos_inc_pre, bb_forbody);
392 
393  std::vector<Value*> row_process_params;
394  row_process_params.insert(
395  row_process_params.end(), result_ptr_vec.begin(), result_ptr_vec.end());
396  if (is_estimate_query) {
397  row_process_params.push_back(new LoadInst(out, "", false, bb_forbody));
398  }
399  row_process_params.push_back(agg_init_val);
400  row_process_params.push_back(pos);
401  row_process_params.push_back(frag_row_off_ptr);
402  row_process_params.push_back(row_count_ptr);
403  if (hoist_literals) {
404  CHECK(literals);
405  row_process_params.push_back(literals);
406  }
407  CallInst* row_process =
408  CallInst::Create(func_row_process, row_process_params, "", bb_forbody);
409  row_process->setCallingConv(CallingConv::C);
410  row_process->setTailCall(false);
411  Attributes row_process_pal;
412  row_process->setAttributes(row_process_pal);
413 
414  BinaryOperator* pos_inc =
415  BinaryOperator::CreateNSW(Instruction::Add, pos, pos_step_i64, "", bb_forbody);
416  ICmpInst* loop_or_exit =
417  new ICmpInst(*bb_forbody, ICmpInst::ICMP_SLT, pos_inc, row_count, "");
418  BranchInst::Create(bb_forbody, bb_crit_edge, loop_or_exit, bb_forbody);
419 
420  // Block ._crit_edge
421  std::vector<Instruction*> result_vec_pre;
422  if (!is_estimate_query) {
423  for (size_t i = 0; i < aggr_col_count; ++i) {
424  auto result = new LoadInst(result_ptr_vec[i], ".pre.result", false, bb_crit_edge);
425  result->setAlignment(LLVM_ALIGN(8));
426  result_vec_pre.push_back(result);
427  }
428  }
429 
430  BranchInst::Create(bb_exit, bb_crit_edge);
431 
432  // Block .exit
444  if (!is_estimate_query) {
445  std::vector<PHINode*> result_vec;
446  for (int64_t i = aggr_col_count - 1; i >= 0; --i) {
447  auto result =
448  PHINode::Create(IntegerType::get(mod->getContext(), 64), 2, "", bb_exit);
449  result->addIncoming(result_vec_pre[i], bb_crit_edge);
450  result->addIncoming(agg_init_val_vec[i], bb_entry);
451  result_vec.insert(result_vec.begin(), result);
452  }
453 
454  for (size_t i = 0; i < aggr_col_count; ++i) {
455  auto col_idx = ConstantInt::get(i32_type, i);
456  if (gpu_smem_context.isSharedMemoryUsed()) {
457  auto target_addr =
458  GetElementPtrInst::CreateInBounds(smem_output_buffer, col_idx, "", bb_exit);
459  // TODO: generalize this once we want to support other types of aggregate
460  // functions besides COUNT.
461  auto agg_func = mod->getFunction("agg_sum_shared");
462  CHECK(agg_func);
463  CallInst::Create(
464  agg_func, std::vector<llvm::Value*>{target_addr, result_vec[i]}, "", bb_exit);
465  } else {
466  auto out_gep = GetElementPtrInst::CreateInBounds(out, col_idx, "", bb_exit);
467  auto col_buffer = new LoadInst(out_gep, "", false, bb_exit);
468  col_buffer->setAlignment(LLVM_ALIGN(8));
469  auto slot_idx = BinaryOperator::CreateAdd(
471  BinaryOperator::CreateMul(frag_idx, pos_step, "", bb_exit),
472  "",
473  bb_exit);
474  auto target_addr =
475  GetElementPtrInst::CreateInBounds(col_buffer, slot_idx, "", bb_exit);
476  StoreInst* result_st = new StoreInst(result_vec[i], target_addr, false, bb_exit);
477  result_st->setAlignment(LLVM_ALIGN(8));
478  }
479  }
480  if (gpu_smem_context.isSharedMemoryUsed()) {
481  // final reduction of results from shared memory buffer back into global memory.
482  auto sync_thread_func = mod->getFunction("sync_threadblock");
483  CHECK(sync_thread_func);
484  CallInst::Create(sync_thread_func, std::vector<llvm::Value*>{}, "", bb_exit);
485  auto reduce_smem_to_gmem_func = mod->getFunction("write_back_non_grouped_agg");
486  CHECK(reduce_smem_to_gmem_func);
487  // each thread reduce the aggregate target corresponding to its own thread ID.
488  // If there are more targets than threads we do not currently use shared memory
489  // optimization. This can be relaxed if necessary
490  for (size_t i = 0; i < aggr_col_count; i++) {
491  auto out_gep = GetElementPtrInst::CreateInBounds(
492  out, ConstantInt::get(i32_type, i), "", bb_exit);
493  auto gmem_output_buffer = new LoadInst(
494  out_gep, "gmem_output_buffer_" + std::to_string(i), false, bb_exit);
495  CallInst::Create(
496  reduce_smem_to_gmem_func,
497  std::vector<llvm::Value*>{
498  smem_output_buffer, gmem_output_buffer, ConstantInt::get(i32_type, i)},
499  "",
500  bb_exit);
501  }
502  }
503  }
504 
505  ReturnInst::Create(mod->getContext(), bb_exit);
506 
507  // Resolve Forward References
508  pos_inc_pre->replaceAllUsesWith(pos_inc);
509  delete pos_inc_pre;
510 
511  if (verifyFunction(*query_func_ptr)) {
512  LOG(FATAL) << "Generated invalid code. ";
513  }
514 
515  return query_func_ptr;
516 }
517 
518 template <class Attributes>
520  llvm::Module* mod,
521  const bool hoist_literals,
523  const ExecutorDeviceType device_type,
524  const bool check_scan_limit,
525  const GpuSharedMemoryContext& gpu_smem_context) {
526  if (gpu_smem_context.isSharedMemoryUsed()) {
527  CHECK(device_type == ExecutorDeviceType::GPU);
528  }
529  using namespace llvm;
530 
531  auto func_pos_start = pos_start<Attributes>(mod);
532  CHECK(func_pos_start);
533  auto func_pos_step = pos_step<Attributes>(mod);
534  CHECK(func_pos_step);
535  auto func_group_buff_idx = group_buff_idx<Attributes>(mod);
536  CHECK(func_group_buff_idx);
537  auto func_row_process = row_process<Attributes>(mod, 0, hoist_literals);
538  CHECK(func_row_process);
539  auto func_init_shared_mem = gpu_smem_context.isSharedMemoryUsed()
540  ? mod->getFunction("init_shared_mem")
541  : mod->getFunction("init_shared_mem_nop");
542  CHECK(func_init_shared_mem);
543 
544  auto func_write_back = mod->getFunction("write_back_nop");
545  CHECK(func_write_back);
546 
547  auto i32_type = IntegerType::get(mod->getContext(), 32);
548  auto i64_type = IntegerType::get(mod->getContext(), 64);
549  auto pi8_type = PointerType::get(IntegerType::get(mod->getContext(), 8), 0);
550  auto pi32_type = PointerType::get(i32_type, 0);
551  auto pi64_type = PointerType::get(i64_type, 0);
552  auto ppi64_type = PointerType::get(pi64_type, 0);
553  auto ppi8_type = PointerType::get(pi8_type, 0);
554 
555  std::vector<Type*> query_args;
556  query_args.push_back(ppi8_type);
557  if (hoist_literals) {
558  query_args.push_back(pi8_type);
559  }
560  query_args.push_back(pi64_type);
561  query_args.push_back(pi64_type);
562  query_args.push_back(pi32_type);
563  query_args.push_back(pi64_type);
564 
565  query_args.push_back(ppi64_type);
566  query_args.push_back(i32_type);
567  query_args.push_back(pi64_type);
568  query_args.push_back(pi32_type);
569  query_args.push_back(pi32_type);
570 
571  FunctionType* query_func_type = FunctionType::get(
572  /*Result=*/Type::getVoidTy(mod->getContext()),
573  /*Params=*/query_args,
574  /*isVarArg=*/false);
575 
576  std::string query_name{"query_group_by_template"};
577  auto query_func_ptr = mod->getFunction(query_name);
578  CHECK(!query_func_ptr);
579 
580  query_func_ptr = Function::Create(
581  /*Type=*/query_func_type,
582  /*Linkage=*/GlobalValue::ExternalLinkage,
583  /*Name=*/"query_group_by_template",
584  mod);
585 
586  query_func_ptr->setCallingConv(CallingConv::C);
587 
588  Attributes query_func_pal;
589  {
590  SmallVector<Attributes, 4> Attrs;
591  Attributes PAS;
592  {
593  AttrBuilder B;
594  B.addAttribute(Attribute::ReadNone);
595  B.addAttribute(Attribute::NoCapture);
596  PAS = Attributes::get(mod->getContext(), 1U, B);
597  }
598 
599  Attrs.push_back(PAS);
600  {
601  AttrBuilder B;
602  B.addAttribute(Attribute::ReadOnly);
603  B.addAttribute(Attribute::NoCapture);
604  PAS = Attributes::get(mod->getContext(), 2U, B);
605  }
606 
607  Attrs.push_back(PAS);
608  {
609  AttrBuilder B;
610  B.addAttribute(Attribute::ReadNone);
611  B.addAttribute(Attribute::NoCapture);
612  PAS = Attributes::get(mod->getContext(), 3U, B);
613  }
614 
615  Attrs.push_back(PAS);
616  {
617  AttrBuilder B;
618  B.addAttribute(Attribute::ReadOnly);
619  B.addAttribute(Attribute::NoCapture);
620  PAS = Attributes::get(mod->getContext(), 4U, B);
621  }
622 
623  Attrs.push_back(PAS);
624  {
625  AttrBuilder B;
626  B.addAttribute(Attribute::UWTable);
627  PAS = Attributes::get(mod->getContext(), ~0U, B);
628  }
629 
630  Attrs.push_back(PAS);
631 
632  query_func_pal = Attributes::get(mod->getContext(), Attrs);
633  }
634  query_func_ptr->setAttributes(query_func_pal);
635 
636  Function::arg_iterator query_arg_it = query_func_ptr->arg_begin();
637  Value* byte_stream = &*query_arg_it;
638  byte_stream->setName("byte_stream");
639  Value* literals{nullptr};
640  if (hoist_literals) {
641  literals = &*(++query_arg_it);
642  ;
643  literals->setName("literals");
644  }
645  Value* row_count_ptr = &*(++query_arg_it);
646  row_count_ptr->setName("row_count_ptr");
647  Value* frag_row_off_ptr = &*(++query_arg_it);
648  frag_row_off_ptr->setName("frag_row_off_ptr");
649  Value* max_matched_ptr = &*(++query_arg_it);
650  max_matched_ptr->setName("max_matched_ptr");
651  Value* agg_init_val = &*(++query_arg_it);
652  agg_init_val->setName("agg_init_val");
653  Value* group_by_buffers = &*(++query_arg_it);
654  group_by_buffers->setName("group_by_buffers");
655  Value* frag_idx = &*(++query_arg_it);
656  frag_idx->setName("frag_idx");
657  Value* join_hash_tables = &*(++query_arg_it);
658  join_hash_tables->setName("join_hash_tables");
659  Value* total_matched = &*(++query_arg_it);
660  total_matched->setName("total_matched");
661  Value* error_code = &*(++query_arg_it);
662  error_code->setName("error_code");
663 
664  auto bb_entry = BasicBlock::Create(mod->getContext(), ".entry", query_func_ptr, 0);
665  auto bb_preheader =
666  BasicBlock::Create(mod->getContext(), ".loop.preheader", query_func_ptr, 0);
667  auto bb_forbody = BasicBlock::Create(mod->getContext(), ".forbody", query_func_ptr, 0);
668  auto bb_crit_edge =
669  BasicBlock::Create(mod->getContext(), "._crit_edge", query_func_ptr, 0);
670  auto bb_exit = BasicBlock::Create(mod->getContext(), ".exit", query_func_ptr, 0);
671 
672  // Block .entry
673  LoadInst* row_count = new LoadInst(row_count_ptr, "", false, bb_entry);
674  row_count->setAlignment(LLVM_ALIGN(8));
675  row_count->setName("row_count");
676 
677  LoadInst* max_matched = new LoadInst(max_matched_ptr, "", false, bb_entry);
678  max_matched->setAlignment(LLVM_ALIGN(8));
679 
680  auto crt_matched_ptr = new AllocaInst(i32_type, 0, "crt_matched", bb_entry);
681  auto old_total_matched_ptr = new AllocaInst(i32_type, 0, "old_total_matched", bb_entry);
682  CallInst* pos_start = CallInst::Create(func_pos_start, "", bb_entry);
683  pos_start->setCallingConv(CallingConv::C);
684  pos_start->setTailCall(true);
685  Attributes pos_start_pal;
686  pos_start->setAttributes(pos_start_pal);
687 
688  CallInst* pos_step = CallInst::Create(func_pos_step, "", bb_entry);
689  pos_step->setCallingConv(CallingConv::C);
690  pos_step->setTailCall(true);
691  Attributes pos_step_pal;
692  pos_step->setAttributes(pos_step_pal);
693 
694  CallInst* group_buff_idx = CallInst::Create(func_group_buff_idx, "", bb_entry);
695  group_buff_idx->setCallingConv(CallingConv::C);
696  group_buff_idx->setTailCall(true);
697  Attributes group_buff_idx_pal;
698  group_buff_idx->setAttributes(group_buff_idx_pal);
699 
700  CastInst* pos_start_i64 = new SExtInst(pos_start, i64_type, "", bb_entry);
701  const PointerType* Ty = dyn_cast<PointerType>(group_by_buffers->getType());
702  CHECK(Ty);
703  GetElementPtrInst* group_by_buffers_gep = GetElementPtrInst::Create(
704  Ty->getElementType(), group_by_buffers, group_buff_idx, "", bb_entry);
705  LoadInst* col_buffer = new LoadInst(group_by_buffers_gep, "", false, bb_entry);
706  col_buffer->setName("col_buffer");
707  col_buffer->setAlignment(LLVM_ALIGN(8));
708 
709  llvm::ConstantInt* shared_mem_bytes_lv =
710  ConstantInt::get(i32_type, gpu_smem_context.getSharedMemorySize());
711  llvm::CallInst* result_buffer =
712  CallInst::Create(func_init_shared_mem,
713  std::vector<llvm::Value*>{col_buffer, shared_mem_bytes_lv},
714  "result_buffer",
715  bb_entry);
716  // TODO(Saman): change this further, normal path should not go through this
717 
718  ICmpInst* enter_or_not =
719  new ICmpInst(*bb_entry, ICmpInst::ICMP_SLT, pos_start_i64, row_count, "");
720  BranchInst::Create(bb_preheader, bb_exit, enter_or_not, bb_entry);
721 
722  // Block .loop.preheader
723  CastInst* pos_step_i64 = new SExtInst(pos_step, i64_type, "", bb_preheader);
724  BranchInst::Create(bb_forbody, bb_preheader);
725 
726  // Block .forbody
727  Argument* pos_pre = new Argument(i64_type);
728  PHINode* pos = PHINode::Create(i64_type, check_scan_limit ? 3 : 2, "pos", bb_forbody);
729 
730  std::vector<Value*> row_process_params;
731  row_process_params.push_back(result_buffer);
732  row_process_params.push_back(crt_matched_ptr);
733  row_process_params.push_back(total_matched);
734  row_process_params.push_back(old_total_matched_ptr);
735  row_process_params.push_back(max_matched_ptr);
736  row_process_params.push_back(agg_init_val);
737  row_process_params.push_back(pos);
738  row_process_params.push_back(frag_row_off_ptr);
739  row_process_params.push_back(row_count_ptr);
740  if (hoist_literals) {
741  CHECK(literals);
742  row_process_params.push_back(literals);
743  }
744  if (check_scan_limit) {
745  new StoreInst(ConstantInt::get(IntegerType::get(mod->getContext(), 32), 0),
746  crt_matched_ptr,
747  bb_forbody);
748  }
749  CallInst* row_process =
750  CallInst::Create(func_row_process, row_process_params, "", bb_forbody);
751  row_process->setCallingConv(CallingConv::C);
752  row_process->setTailCall(true);
753  Attributes row_process_pal;
754  row_process->setAttributes(row_process_pal);
755 
756  // Forcing all threads within a warp to be synchronized (Compute >= 7.x)
757  if (query_mem_desc.isWarpSyncRequired(device_type)) {
758  auto func_sync_warp_protected = mod->getFunction("sync_warp_protected");
759  CHECK(func_sync_warp_protected);
760  CallInst::Create(func_sync_warp_protected,
761  std::vector<llvm::Value*>{pos, row_count},
762  "",
763  bb_forbody);
764  }
765 
766  BinaryOperator* pos_inc =
767  BinaryOperator::Create(Instruction::Add, pos, pos_step_i64, "", bb_forbody);
768  ICmpInst* loop_or_exit =
769  new ICmpInst(*bb_forbody, ICmpInst::ICMP_SLT, pos_inc, row_count, "");
770  if (check_scan_limit) {
771  auto crt_matched = new LoadInst(crt_matched_ptr, "crt_matched", false, bb_forbody);
772  auto filter_match = BasicBlock::Create(
773  mod->getContext(), "filter_match", query_func_ptr, bb_crit_edge);
774  llvm::Value* new_total_matched =
775  new LoadInst(old_total_matched_ptr, "", false, filter_match);
776  new_total_matched =
777  BinaryOperator::CreateAdd(new_total_matched, crt_matched, "", filter_match);
778  CHECK(new_total_matched);
779  ICmpInst* limit_not_reached = new ICmpInst(*filter_match,
780  ICmpInst::ICMP_SLT,
781  new_total_matched,
782  max_matched,
783  "limit_not_reached");
784  BranchInst::Create(
785  bb_forbody,
786  bb_crit_edge,
787  BinaryOperator::Create(
788  BinaryOperator::And, loop_or_exit, limit_not_reached, "", filter_match),
789  filter_match);
790  auto filter_nomatch = BasicBlock::Create(
791  mod->getContext(), "filter_nomatch", query_func_ptr, bb_crit_edge);
792  BranchInst::Create(bb_forbody, bb_crit_edge, loop_or_exit, filter_nomatch);
793  ICmpInst* crt_matched_nz = new ICmpInst(
794  *bb_forbody, ICmpInst::ICMP_NE, crt_matched, ConstantInt::get(i32_type, 0), "");
795  BranchInst::Create(filter_match, filter_nomatch, crt_matched_nz, bb_forbody);
796  pos->addIncoming(pos_start_i64, bb_preheader);
797  pos->addIncoming(pos_pre, filter_match);
798  pos->addIncoming(pos_pre, filter_nomatch);
799  } else {
800  pos->addIncoming(pos_start_i64, bb_preheader);
801  pos->addIncoming(pos_pre, bb_forbody);
802  BranchInst::Create(bb_forbody, bb_crit_edge, loop_or_exit, bb_forbody);
803  }
804 
805  // Block ._crit_edge
806  BranchInst::Create(bb_exit, bb_crit_edge);
807 
808  // Block .exit
809  CallInst::Create(func_write_back,
810  std::vector<Value*>{col_buffer, result_buffer, shared_mem_bytes_lv},
811  "",
812  bb_exit);
813 
814  ReturnInst::Create(mod->getContext(), bb_exit);
815 
816  // Resolve Forward References
817  pos_pre->replaceAllUsesWith(pos_inc);
818  delete pos_pre;
819 
820  if (verifyFunction(*query_func_ptr, &llvm::errs())) {
821  LOG(FATAL) << "Generated invalid code. ";
822  }
823 
824  return query_func_ptr;
825 }
826 
827 #if LLVM_VERSION_MAJOR >= 6
828 llvm::Function* query_template(llvm::Module* module,
829  const size_t aggr_col_count,
830  const bool hoist_literals,
831  const bool is_estimate_query,
832  const GpuSharedMemoryContext& gpu_smem_context) {
833  return query_template_impl<llvm::AttributeList>(
834  module, aggr_col_count, hoist_literals, is_estimate_query, gpu_smem_context);
835 }
836 llvm::Function* query_group_by_template(llvm::Module* module,
837  const bool hoist_literals,
839  const ExecutorDeviceType device_type,
840  const bool check_scan_limit,
841  const GpuSharedMemoryContext& gpu_smem_context) {
842  return query_group_by_template_impl<llvm::AttributeList>(module,
843  hoist_literals,
845  device_type,
846  check_scan_limit,
847  gpu_smem_context);
848 }
849 #else
850 llvm::Function* query_template(llvm::Module* module,
851  const size_t aggr_col_count,
852  const bool hoist_literals,
853  const bool is_estimate_query,
854  const GpuSharedMemoryContext& gpu_smem_context) {
855  return query_template_impl<llvm::AttributeSet>(
856  module, aggr_col_count, hoist_literals, is_estimate_query, gpu_smem_context);
857 }
858 llvm::Function* query_group_by_template(llvm::Module* module,
859  const bool hoist_literals,
861  const ExecutorDeviceType device_type,
862  const bool check_scan_limit,
863  const GpuSharedMemoryContext& gpu_smem_context) {
864  return query_group_by_template_impl<llvm::AttributeSet>(module,
865  hoist_literals,
867  device_type,
868  check_scan_limit,
869  gpu_smem_context);
870 }
871 #endif
const int8_t const int64_t const uint64_t const int32_t const int64_t int64_t uint32_t const int64_t * join_hash_tables
std::unique_ptr< llvm::Module > module(runtime_module_shallow_copy(cgen_state))
ExecutorDeviceType
#define LOG(tag)
Definition: Logger.h:188
size_t getSharedMemorySize() const
llvm::Function * query_group_by_template_impl(llvm::Module *mod, const bool hoist_literals, const QueryMemoryDescriptor &query_mem_desc, const ExecutorDeviceType device_type, const bool check_scan_limit, const GpuSharedMemoryContext &gpu_smem_context)
llvm::Function * query_template(llvm::Module *module, const size_t aggr_col_count, const bool hoist_literals, const bool is_estimate_query, const GpuSharedMemoryContext &gpu_smem_context)
#define LLVM_ALIGN(alignment)
std::string to_string(char const *&&v)
llvm::Function * group_buff_idx(llvm::Module *mod)
CHECK(cgen_state)
llvm::Function * default_func_builder(llvm::Module *mod, const std::string &name)
const int8_t const int64_t const uint64_t const int32_t const int64_t int64_t uint32_t const int64_t int32_t * error_code
const int8_t const int64_t const uint64_t const int32_t * max_matched
const int8_t const int64_t const uint64_t const int32_t const int64_t int64_t uint32_t frag_idx
bool isWarpSyncRequired(const ExecutorDeviceType) const
const int8_t * literals
llvm::Function * query_template_impl(llvm::Module *mod, const size_t aggr_col_count, const bool hoist_literals, const bool is_estimate_query, const GpuSharedMemoryContext &gpu_smem_context)
const int8_t const int64_t const uint64_t const int32_t const int64_t int64_t ** out
llvm::Function * row_process(llvm::Module *mod, const size_t aggr_col_count, const bool hoist_literals)
llvm::Function * query_group_by_template(llvm::Module *module, const bool hoist_literals, const QueryMemoryDescriptor &query_mem_desc, const ExecutorDeviceType device_type, const bool check_scan_limit, const GpuSharedMemoryContext &gpu_smem_context)