OmniSciDB  16c4e035a1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
RelAlgOptimizer.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 "RelAlgOptimizer.h"
18 #include "Logger/Logger.h"
19 #include "RexVisitor.h"
21 
22 #include <numeric>
23 #include <string>
24 #include <unordered_map>
25 
26 namespace {
27 
29  public:
30  RexProjectInputRedirector(const std::unordered_set<const RelProject*>& crt_inputs)
31  : crt_projects_(crt_inputs) {}
32 
33  RetType visitInput(const RexInput* input) const override {
34  auto source = dynamic_cast<const RelProject*>(input->getSourceNode());
35  if (!source || !crt_projects_.count(source)) {
36  return input->deepCopy();
37  }
38  auto new_source = source->getInput(0);
39  auto new_input =
40  dynamic_cast<const RexInput*>(source->getProjectAt(input->getIndex()));
41  if (!new_input) {
42  return input->deepCopy();
43  }
44  if (auto join = dynamic_cast<const RelJoin*>(new_source)) {
45  CHECK(new_input->getSourceNode() == join->getInput(0) ||
46  new_input->getSourceNode() == join->getInput(1));
47  } else {
48  CHECK_EQ(new_input->getSourceNode(), new_source);
49  }
50  return new_input->deepCopy();
51  }
52 
53  private:
54  const std::unordered_set<const RelProject*>& crt_projects_;
55 };
56 
57 class RexRebindInputsVisitor : public RexVisitor<void*> {
58  public:
59  RexRebindInputsVisitor(const RelAlgNode* old_input, const RelAlgNode* new_input)
60  : old_input_(old_input), new_input_(new_input) {}
61 
62  void* visitInput(const RexInput* rex_input) const override {
63  const auto old_source = rex_input->getSourceNode();
64  if (old_source == old_input_) {
65  rex_input->setSourceNode(new_input_);
66  }
67  return nullptr;
68  };
69 
70  void visitNode(const RelAlgNode* node) const {
71  if (dynamic_cast<const RelAggregate*>(node) || dynamic_cast<const RelSort*>(node)) {
72  return;
73  }
74  if (auto join = dynamic_cast<const RelJoin*>(node)) {
75  if (auto condition = join->getCondition()) {
76  visit(condition);
77  }
78  return;
79  }
80  if (auto project = dynamic_cast<const RelProject*>(node)) {
81  for (size_t i = 0; i < project->size(); ++i) {
82  visit(project->getProjectAt(i));
83  }
84  return;
85  }
86  if (auto filter = dynamic_cast<const RelFilter*>(node)) {
87  visit(filter->getCondition());
88  return;
89  }
90  CHECK(false);
91  }
92 
93  private:
96 };
97 
99  const RelProject* curr_project,
100  const std::unordered_set<const RelProject*>& projects_to_remove) {
101  auto source = curr_project->getInput(0);
102  while (auto filter = dynamic_cast<const RelFilter*>(source)) {
103  source = filter->getInput(0);
104  }
105  if (auto src_project = dynamic_cast<const RelProject*>(source)) {
106  if (projects_to_remove.count(src_project)) {
107  return get_actual_source_size(src_project, projects_to_remove);
108  }
109  }
110  return curr_project->getInput(0)->size();
111 }
112 
114  const RelProject* project,
115  const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
116  du_web) {
117  if (!project->isSimple()) {
118  return false;
119  }
120  auto usrs_it = du_web.find(project);
121  CHECK(usrs_it != du_web.end());
122  for (auto usr : usrs_it->second) {
123  if (!dynamic_cast<const RelProject*>(usr) && !dynamic_cast<const RelFilter*>(usr)) {
124  return false;
125  }
126  }
127  return true;
128 }
129 
131  const RelProject* project,
132  const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
133  du_web,
134  const std::unordered_set<const RelProject*>& projects_to_remove,
135  std::unordered_set<const RelProject*>& permutating_projects) {
136  auto source_size = get_actual_source_size(project, projects_to_remove);
137  if (project->size() > source_size) {
138  return false;
139  }
140 
141  if (project->size() < source_size) {
142  auto usrs_it = du_web.find(project);
143  CHECK(usrs_it != du_web.end());
144  bool guard_found = false;
145  while (usrs_it->second.size() == size_t(1)) {
146  auto only_usr = *usrs_it->second.begin();
147  if (dynamic_cast<const RelProject*>(only_usr)) {
148  guard_found = true;
149  break;
150  }
151  if (dynamic_cast<const RelAggregate*>(only_usr) ||
152  dynamic_cast<const RelSort*>(only_usr) ||
153  dynamic_cast<const RelJoin*>(only_usr) ||
154  dynamic_cast<const RelTableFunction*>(only_usr) ||
155  dynamic_cast<const RelLogicalUnion*>(only_usr)) {
156  return false;
157  }
158  CHECK(dynamic_cast<const RelFilter*>(only_usr))
159  << "only_usr: " << only_usr->toString();
160  usrs_it = du_web.find(only_usr);
161  CHECK(usrs_it != du_web.end());
162  }
163 
164  if (!guard_found) {
165  return false;
166  }
167  }
168 
169  bool identical = true;
170  for (size_t i = 0; i < project->size(); ++i) {
171  auto target = dynamic_cast<const RexInput*>(project->getProjectAt(i));
172  CHECK(target);
173  if (i != target->getIndex()) {
174  identical = false;
175  break;
176  }
177  }
178 
179  if (identical) {
180  return true;
181  }
182 
183  if (safe_to_redirect(project, du_web)) {
184  permutating_projects.insert(project);
185  return true;
186  }
187 
188  return false;
189 }
190 
192  const RelFilter* excluded_root,
193  const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
194  du_web) {
195  CHECK(excluded_root);
196  auto src_project = dynamic_cast<const RelProject*>(excluded_root->getInput(0));
197  CHECK(src_project && src_project->isSimple());
198  const auto indirect_join_src = dynamic_cast<const RelJoin*>(src_project->getInput(0));
199  std::unordered_map<size_t, size_t> old_to_new_idx;
200  for (size_t i = 0; i < src_project->size(); ++i) {
201  auto rex_in = dynamic_cast<const RexInput*>(src_project->getProjectAt(i));
202  CHECK(rex_in);
203  size_t src_base = 0;
204  if (indirect_join_src != nullptr &&
205  indirect_join_src->getInput(1) == rex_in->getSourceNode()) {
206  src_base = indirect_join_src->getInput(0)->size();
207  }
208  old_to_new_idx.insert(std::make_pair(i, src_base + rex_in->getIndex()));
209  old_to_new_idx.insert(std::make_pair(i, rex_in->getIndex()));
210  }
211  CHECK(old_to_new_idx.size());
212  RexInputRenumber<false> renumber(old_to_new_idx);
213  auto usrs_it = du_web.find(excluded_root);
214  CHECK(usrs_it != du_web.end());
215  std::vector<const RelAlgNode*> work_set(usrs_it->second.begin(), usrs_it->second.end());
216  while (!work_set.empty()) {
217  auto node = work_set.back();
218  work_set.pop_back();
219  auto modified_node = const_cast<RelAlgNode*>(node);
220  if (auto filter = dynamic_cast<RelFilter*>(modified_node)) {
221  auto new_condition = renumber.visit(filter->getCondition());
222  filter->setCondition(new_condition);
223  auto usrs_it = du_web.find(filter);
224  CHECK(usrs_it != du_web.end() && usrs_it->second.size() == 1);
225  work_set.push_back(*usrs_it->second.begin());
226  continue;
227  }
228  if (auto project = dynamic_cast<RelProject*>(modified_node)) {
229  std::vector<std::unique_ptr<const RexScalar>> new_exprs;
230  for (size_t i = 0; i < project->size(); ++i) {
231  new_exprs.push_back(renumber.visit(project->getProjectAt(i)));
232  }
233  project->setExpressions(new_exprs);
234  continue;
235  }
236  CHECK(false);
237  }
238 }
239 
240 // This function appears to redirect/remove redundant Projection input nodes(?)
242  std::shared_ptr<RelAlgNode> node,
243  const std::unordered_set<const RelProject*>& projects,
244  const std::unordered_set<const RelProject*>& permutating_projects,
245  const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
246  du_web) {
247  if (dynamic_cast<RelLogicalUnion*>(node.get())) {
248  return; // UNION keeps all Projection inputs.
249  }
250  std::shared_ptr<const RelProject> src_project = nullptr;
251  for (size_t i = 0; i < node->inputCount(); ++i) {
252  if (auto project =
253  std::dynamic_pointer_cast<const RelProject>(node->getAndOwnInput(i))) {
254  if (projects.count(project.get())) {
255  src_project = project;
256  break;
257  }
258  }
259  }
260  if (!src_project) {
261  return;
262  }
263  if (auto join = std::dynamic_pointer_cast<RelJoin>(node)) {
264  auto other_project =
265  src_project == node->getAndOwnInput(0)
266  ? std::dynamic_pointer_cast<const RelProject>(node->getAndOwnInput(1))
267  : std::dynamic_pointer_cast<const RelProject>(node->getAndOwnInput(0));
268  join->replaceInput(src_project, src_project->getAndOwnInput(0));
269  RexRebindInputsVisitor rebinder(src_project.get(), src_project->getInput(0));
270  auto usrs_it = du_web.find(join.get());
271  CHECK(usrs_it != du_web.end());
272  for (auto usr : usrs_it->second) {
273  rebinder.visitNode(usr);
274  }
275 
276  if (other_project && projects.count(other_project.get())) {
277  join->replaceInput(other_project, other_project->getAndOwnInput(0));
278  RexRebindInputsVisitor other_rebinder(other_project.get(),
279  other_project->getInput(0));
280  for (auto usr : usrs_it->second) {
281  other_rebinder.visitNode(usr);
282  }
283  }
284  return;
285  }
286  if (auto project = std::dynamic_pointer_cast<RelProject>(node)) {
287  project->RelAlgNode::replaceInput(src_project, src_project->getAndOwnInput(0));
288  RexProjectInputRedirector redirector(projects);
289  std::vector<std::unique_ptr<const RexScalar>> new_exprs;
290  for (size_t i = 0; i < project->size(); ++i) {
291  new_exprs.push_back(redirector.visit(project->getProjectAt(i)));
292  }
293  project->setExpressions(new_exprs);
294  return;
295  }
296  if (auto filter = std::dynamic_pointer_cast<RelFilter>(node)) {
297  const bool is_permutating_proj = permutating_projects.count(src_project.get());
298  if (is_permutating_proj || dynamic_cast<const RelJoin*>(src_project->getInput(0))) {
299  if (is_permutating_proj) {
300  propagate_rex_input_renumber(filter.get(), du_web);
301  }
302  filter->RelAlgNode::replaceInput(src_project, src_project->getAndOwnInput(0));
303  RexProjectInputRedirector redirector(projects);
304  auto new_condition = redirector.visit(filter->getCondition());
305  filter->setCondition(new_condition);
306  } else {
307  filter->replaceInput(src_project, src_project->getAndOwnInput(0));
308  }
309  return;
310  }
311  if (std::dynamic_pointer_cast<RelSort>(node)) {
312  auto const src_project_input = src_project->getInput(0);
313  if (dynamic_cast<const RelScan*>(src_project_input) ||
314  dynamic_cast<const RelLogicalValues*>(src_project_input) ||
315  dynamic_cast<const RelLogicalUnion*>(src_project_input)) {
316  return;
317  }
318  }
319  if (std::dynamic_pointer_cast<RelModify>(node)) {
320  return; // NOTE: Review this. Not sure about this.
321  }
322  if (std::dynamic_pointer_cast<RelTableFunction>(node)) {
323  return;
324  }
325  CHECK(std::dynamic_pointer_cast<RelAggregate>(node) ||
326  std::dynamic_pointer_cast<RelSort>(node));
327  node->replaceInput(src_project, src_project->getAndOwnInput(0));
328 }
329 
330 void cleanup_dead_nodes(std::vector<std::shared_ptr<RelAlgNode>>& nodes) {
331  for (auto nodeIt = nodes.rbegin(); nodeIt != nodes.rend(); ++nodeIt) {
332  if (nodeIt->use_count() == 1) {
333  VLOG(1) << "Node (ID: " << (*nodeIt)->getId() << ") deleted.";
335  auto node_str = (*nodeIt)->toString();
336  auto [node_substr, post_fix] = ::substring(node_str, g_max_log_length);
337  VLOG(2) << "Deleted Node (ID: " << (*nodeIt)->getId()
338  << ") contents: " << node_substr << post_fix;
339  }
340  nodeIt->reset();
341  }
342  }
343 
344  std::vector<std::shared_ptr<RelAlgNode>> new_nodes;
345  for (auto node : nodes) {
346  if (!node) {
347  continue;
348  }
349  new_nodes.push_back(node);
350  }
351  nodes.swap(new_nodes);
352 }
353 
354 std::unordered_set<const RelProject*> get_visible_projects(const RelAlgNode* root) {
355  if (auto project = dynamic_cast<const RelProject*>(root)) {
356  return {project};
357  }
358 
359  if (dynamic_cast<const RelAggregate*>(root) || dynamic_cast<const RelScan*>(root) ||
360  dynamic_cast<const RelLogicalValues*>(root) ||
361  dynamic_cast<const RelModify*>(root)) {
362  return std::unordered_set<const RelProject*>{};
363  }
364 
365  if (auto join = dynamic_cast<const RelJoin*>(root)) {
366  auto lhs_projs = get_visible_projects(join->getInput(0));
367  auto rhs_projs = get_visible_projects(join->getInput(1));
368  lhs_projs.insert(rhs_projs.begin(), rhs_projs.end());
369  return lhs_projs;
370  }
371 
372  if (auto logical_union = dynamic_cast<const RelLogicalUnion*>(root)) {
373  auto projections = get_visible_projects(logical_union->getInput(0));
374  for (size_t i = 1; i < logical_union->inputCount(); ++i) {
375  auto next = get_visible_projects(logical_union->getInput(i));
376  projections.insert(next.begin(), next.end());
377  }
378  return projections;
379  }
380 
381  CHECK(dynamic_cast<const RelFilter*>(root) || dynamic_cast<const RelSort*>(root))
382  << "root = " << root->toString();
383  return get_visible_projects(root->getInput(0));
384 }
385 
386 // TODO(miyu): checking this at runtime is more accurate
387 bool is_distinct(const size_t input_idx, const RelAlgNode* node) {
388  if (dynamic_cast<const RelFilter*>(node) || dynamic_cast<const RelSort*>(node)) {
389  CHECK_EQ(size_t(1), node->inputCount());
390  return is_distinct(input_idx, node->getInput(0));
391  }
392  if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
393  CHECK_EQ(size_t(1), node->inputCount());
394  if (aggregate->getGroupByCount() == 1 && !input_idx) {
395  return true;
396  }
397  if (input_idx < aggregate->getGroupByCount()) {
398  return is_distinct(input_idx, node->getInput(0));
399  }
400  return false;
401  }
402  if (auto project = dynamic_cast<const RelProject*>(node)) {
403  CHECK_LT(input_idx, project->size());
404  if (auto input = dynamic_cast<const RexInput*>(project->getProjectAt(input_idx))) {
405  CHECK_EQ(size_t(1), node->inputCount());
406  return is_distinct(input->getIndex(), project->getInput(0));
407  }
408  return false;
409  }
410  CHECK(dynamic_cast<const RelJoin*>(node) || dynamic_cast<const RelScan*>(node));
411  return false;
412 }
413 
414 } // namespace
415 
416 std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>> build_du_web(
417  const std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
418  std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>> web;
419  std::unordered_set<const RelAlgNode*> visited;
420  std::vector<const RelAlgNode*> work_set;
421  for (auto node : nodes) {
422  if (std::dynamic_pointer_cast<RelScan>(node) ||
423  std::dynamic_pointer_cast<RelModify>(node) || visited.count(node.get())) {
424  continue;
425  }
426  work_set.push_back(node.get());
427  while (!work_set.empty()) {
428  auto walker = work_set.back();
429  work_set.pop_back();
430  if (visited.count(walker)) {
431  continue;
432  }
433  CHECK(!web.count(walker));
434  auto it_ok =
435  web.insert(std::make_pair(walker, std::unordered_set<const RelAlgNode*>{}));
436  CHECK(it_ok.second);
437  visited.insert(walker);
438  CHECK(dynamic_cast<const RelJoin*>(walker) ||
439  dynamic_cast<const RelProject*>(walker) ||
440  dynamic_cast<const RelAggregate*>(walker) ||
441  dynamic_cast<const RelFilter*>(walker) ||
442  dynamic_cast<const RelSort*>(walker) ||
443  dynamic_cast<const RelLeftDeepInnerJoin*>(walker) ||
444  dynamic_cast<const RelLogicalValues*>(walker) ||
445  dynamic_cast<const RelTableFunction*>(walker) ||
446  dynamic_cast<const RelLogicalUnion*>(walker));
447  for (size_t i = 0; i < walker->inputCount(); ++i) {
448  auto src = walker->getInput(i);
449  if (dynamic_cast<const RelScan*>(src) || dynamic_cast<const RelModify*>(src)) {
450  continue;
451  }
452  if (web.empty() || !web.count(src)) {
453  web.insert(std::make_pair(src, std::unordered_set<const RelAlgNode*>{}));
454  }
455  web[src].insert(walker);
456  work_set.push_back(src);
457  }
458  }
459  }
460  return web;
461 }
462 
471 bool project_separates_sort(const RelProject* project, const RelAlgNode* next_node) {
472  CHECK(project);
473  if (!next_node) {
474  return false;
475  }
476 
477  auto sort = dynamic_cast<const RelSort*>(next_node);
478  if (!sort) {
479  return false;
480  }
481  if (!(project->inputCount() == 1)) {
482  return false;
483  }
484 
485  if (dynamic_cast<const RelSort*>(project->getInput(0))) {
486  return true;
487  }
488  return false;
489 }
490 
491 // For now, the only target to eliminate is restricted to project-aggregate pair between
492 // scan/sort and join
493 // TODO(miyu): allow more chance if proved safe
494 void eliminate_identical_copy(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
495  std::unordered_set<std::shared_ptr<const RelAlgNode>> copies;
496  auto sink = nodes.back();
497  for (auto node : nodes) {
498  auto aggregate = std::dynamic_pointer_cast<const RelAggregate>(node);
499  if (!aggregate || aggregate == sink ||
500  !(aggregate->getGroupByCount() == 1 && aggregate->getAggExprsCount() == 0)) {
501  continue;
502  }
503  auto project =
504  std::dynamic_pointer_cast<const RelProject>(aggregate->getAndOwnInput(0));
505  if (project && project->size() == aggregate->size() &&
506  project->getFields() == aggregate->getFields()) {
507  CHECK_EQ(size_t(0), copies.count(aggregate));
508  copies.insert(aggregate);
509  }
510  }
511  for (auto node : nodes) {
512  if (!node->inputCount()) {
513  continue;
514  }
515  auto last_source = node->getAndOwnInput(node->inputCount() - 1);
516  if (!copies.count(last_source)) {
517  continue;
518  }
519  auto aggregate = std::dynamic_pointer_cast<const RelAggregate>(last_source);
520  CHECK(aggregate);
521  if (!std::dynamic_pointer_cast<const RelJoin>(node) || aggregate->size() != 1) {
522  continue;
523  }
524  auto project =
525  std::dynamic_pointer_cast<const RelProject>(aggregate->getAndOwnInput(0));
526  CHECK(project);
527  CHECK_EQ(size_t(1), project->size());
528  if (!is_distinct(size_t(0), project.get())) {
529  continue;
530  }
531  auto new_source = project->getAndOwnInput(0);
532  if (std::dynamic_pointer_cast<const RelSort>(new_source) ||
533  std::dynamic_pointer_cast<const RelScan>(new_source)) {
534  node->replaceInput(last_source, new_source);
535  }
536  }
537  decltype(copies)().swap(copies);
538 
539  auto web = build_du_web(nodes);
540 
541  std::unordered_set<const RelProject*> projects;
542  std::unordered_set<const RelProject*> permutating_projects;
543  auto const visible_projs = get_visible_projects(nodes.back().get());
544  for (auto node_it = nodes.begin(); node_it != nodes.end(); node_it++) {
545  auto node = *node_it;
546  auto project = std::dynamic_pointer_cast<RelProject>(node);
547  auto next_node_it = std::next(node_it);
548  if (project && project->isSimple() &&
549  (!visible_projs.count(project.get()) || !project->isRenaming()) &&
550  is_identical_copy(project.get(), web, projects, permutating_projects) &&
552  project.get(), next_node_it == nodes.end() ? nullptr : next_node_it->get())) {
553  projects.insert(project.get());
554  }
555  }
556 
557  for (auto node : nodes) {
558  redirect_inputs_of(node, projects, permutating_projects, web);
559  }
560 
561  cleanup_dead_nodes(nodes);
562 }
563 
564 namespace {
565 
566 class RexInputCollector : public RexVisitor<std::unordered_set<RexInput>> {
567  private:
569 
570  protected:
571  using RetType = std::unordered_set<RexInput>;
572  RetType aggregateResult(const RetType& aggregate,
573  const RetType& next_result) const override {
574  RetType result(aggregate.begin(), aggregate.end());
575  result.insert(next_result.begin(), next_result.end());
576  return result;
577  }
578 
579  public:
580  RexInputCollector(const RelAlgNode* node) : node_(node) {}
581 
582  RetType visitInput(const RexInput* input) const override {
583  RetType result;
584  if (node_->inputCount() == 1) {
585  auto src = node_->getInput(0);
586  if (auto join = dynamic_cast<const RelJoin*>(src)) {
587  CHECK_EQ(join->inputCount(), size_t(2));
588  const auto src2_in_offset = join->getInput(0)->size();
589  if (input->getSourceNode() == join->getInput(1)) {
590  result.emplace(src, input->getIndex() + src2_in_offset);
591  } else {
592  result.emplace(src, input->getIndex());
593  }
594  return result;
595  }
596  }
597  result.insert(*input);
598  return result;
599  }
600 };
601 
603  CHECK(node->size());
604  RexInputCollector collector(node);
605  if (auto filter = dynamic_cast<const RelFilter*>(node)) {
606  auto rex_ins = collector.visit(filter->getCondition());
607  if (!rex_ins.empty()) {
608  return static_cast<size_t>(rex_ins.begin()->getIndex());
609  }
610  return pick_always_live_col_idx(filter->getInput(0));
611  } else if (auto join = dynamic_cast<const RelJoin*>(node)) {
612  auto rex_ins = collector.visit(join->getCondition());
613  if (!rex_ins.empty()) {
614  return static_cast<size_t>(rex_ins.begin()->getIndex());
615  }
616  if (auto lhs_idx = pick_always_live_col_idx(join->getInput(0))) {
617  return lhs_idx;
618  }
619  if (auto rhs_idx = pick_always_live_col_idx(join->getInput(0))) {
620  return rhs_idx + join->getInput(0)->size();
621  }
622  } else if (auto sort = dynamic_cast<const RelSort*>(node)) {
623  if (sort->collationCount()) {
624  return sort->getCollation(0).getField();
625  }
626  return pick_always_live_col_idx(sort->getInput(0));
627  }
628  return size_t(0);
629 }
630 
631 std::vector<std::unordered_set<size_t>> get_live_ins(
632  const RelAlgNode* node,
633  const std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& live_outs) {
634  if (!node || dynamic_cast<const RelScan*>(node)) {
635  return {};
636  }
637  RexInputCollector collector(node);
638  auto it = live_outs.find(node);
639  CHECK(it != live_outs.end());
640  auto live_out = it->second;
641  if (auto project = dynamic_cast<const RelProject*>(node)) {
642  CHECK_EQ(size_t(1), project->inputCount());
643  std::unordered_set<size_t> live_in;
644  for (const auto& idx : live_out) {
645  CHECK_LT(idx, project->size());
646  auto partial_in = collector.visit(project->getProjectAt(idx));
647  for (auto rex_in : partial_in) {
648  live_in.insert(rex_in.getIndex());
649  }
650  }
651  if (project->size() == 1 &&
652  dynamic_cast<const RexLiteral*>(project->getProjectAt(0))) {
653  CHECK(live_in.empty());
654  live_in.insert(pick_always_live_col_idx(project->getInput(0)));
655  }
656  return {live_in};
657  }
658  if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
659  CHECK_EQ(size_t(1), aggregate->inputCount());
660  const auto group_key_count = static_cast<size_t>(aggregate->getGroupByCount());
661  const auto agg_expr_count = static_cast<size_t>(aggregate->getAggExprsCount());
662  std::unordered_set<size_t> live_in;
663  for (size_t i = 0; i < group_key_count; ++i) {
664  live_in.insert(i);
665  }
666  bool has_count_star_only{false};
667  for (const auto& idx : live_out) {
668  if (idx < group_key_count) {
669  continue;
670  }
671  const auto agg_idx = idx - group_key_count;
672  CHECK_LT(agg_idx, agg_expr_count);
673  const auto& cur_agg_expr = aggregate->getAggExprs()[agg_idx];
674  const auto n_operands = cur_agg_expr->size();
675  for (size_t i = 0; i < n_operands; ++i) {
676  live_in.insert(static_cast<size_t>(cur_agg_expr->getOperand(i)));
677  }
678  if (n_operands == 0) {
679  has_count_star_only = true;
680  }
681  }
682  if (has_count_star_only && !group_key_count) {
683  live_in.insert(size_t(0));
684  }
685  return {live_in};
686  }
687  if (auto join = dynamic_cast<const RelJoin*>(node)) {
688  std::unordered_set<size_t> lhs_live_ins;
689  std::unordered_set<size_t> rhs_live_ins;
690  CHECK_EQ(size_t(2), join->inputCount());
691  auto lhs = join->getInput(0);
692  auto rhs = join->getInput(1);
693  const auto rhs_idx_base = lhs->size();
694  for (const auto idx : live_out) {
695  if (idx < rhs_idx_base) {
696  lhs_live_ins.insert(idx);
697  } else {
698  rhs_live_ins.insert(idx - rhs_idx_base);
699  }
700  }
701  auto rex_ins = collector.visit(join->getCondition());
702  for (const auto& rex_in : rex_ins) {
703  const auto in_idx = static_cast<size_t>(rex_in.getIndex());
704  if (rex_in.getSourceNode() == lhs) {
705  lhs_live_ins.insert(in_idx);
706  continue;
707  }
708  if (rex_in.getSourceNode() == rhs) {
709  rhs_live_ins.insert(in_idx);
710  continue;
711  }
712  CHECK(false);
713  }
714  return {lhs_live_ins, rhs_live_ins};
715  }
716  if (auto sort = dynamic_cast<const RelSort*>(node)) {
717  CHECK_EQ(size_t(1), sort->inputCount());
718  std::unordered_set<size_t> live_in(live_out.begin(), live_out.end());
719  for (size_t i = 0; i < sort->collationCount(); ++i) {
720  live_in.insert(sort->getCollation(i).getField());
721  }
722  return {live_in};
723  }
724  if (auto filter = dynamic_cast<const RelFilter*>(node)) {
725  CHECK_EQ(size_t(1), filter->inputCount());
726  std::unordered_set<size_t> live_in(live_out.begin(), live_out.end());
727  auto rex_ins = collector.visit(filter->getCondition());
728  for (const auto& rex_in : rex_ins) {
729  live_in.insert(static_cast<size_t>(rex_in.getIndex()));
730  }
731  return {live_in};
732  }
733  if (auto table_func = dynamic_cast<const RelTableFunction*>(node)) {
734  const auto input_count = table_func->size();
735  std::unordered_set<size_t> live_in;
736  for (size_t i = 0; i < input_count; i++) {
737  live_in.insert(i);
738  }
739 
740  std::vector<std::unordered_set<size_t>> result;
741  // Is the computed result correct in general?
742  for (size_t i = table_func->inputCount(); i > 0; i--) {
743  result.push_back(live_in);
744  }
745 
746  return result;
747  }
748  if (auto logical_union = dynamic_cast<const RelLogicalUnion*>(node)) {
749  return std::vector<std::unordered_set<size_t>>(logical_union->inputCount(), live_out);
750  }
751  return {};
752 }
753 
754 bool any_dead_col_in(const RelAlgNode* node,
755  const std::unordered_set<size_t>& live_outs) {
756  CHECK(!dynamic_cast<const RelScan*>(node));
757  if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
758  for (size_t i = aggregate->getGroupByCount(); i < aggregate->size(); ++i) {
759  if (!live_outs.count(i)) {
760  return true;
761  }
762  }
763  return false;
764  }
765 
766  return node->size() > live_outs.size();
767 }
768 
769 bool does_redef_cols(const RelAlgNode* node) {
770  return dynamic_cast<const RelAggregate*>(node) || dynamic_cast<const RelProject*>(node);
771 }
772 
774  public:
776  const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
777  liveouts,
778  const std::unordered_set<const RelAlgNode*>& intact_nodes)
779  : liveouts_(liveouts), intact_nodes_(intact_nodes) {}
780 
781  bool hasAllSrcReady(const RelAlgNode* node) const {
782  for (size_t i = 0; i < node->inputCount(); ++i) {
783  auto src = node->getInput(i);
784  if (!dynamic_cast<const RelScan*>(src) && liveouts_.find(src) == liveouts_.end() &&
785  !intact_nodes_.count(src)) {
786  return false;
787  }
788  }
789  return true;
790  }
791 
792  private:
793  const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
795  const std::unordered_set<const RelAlgNode*>& intact_nodes_;
796 };
797 
799  const RelAlgNode* node,
800  std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
801  new_liveouts,
802  const std::unordered_set<size_t>& old_liveouts,
803  const std::unordered_set<const RelAlgNode*>& intact_nodes,
804  const std::unordered_map<const RelAlgNode*, size_t>& orig_node_sizes) {
805  auto live_fields = old_liveouts;
806  if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
807  for (size_t i = 0; i < aggregate->getGroupByCount(); ++i) {
808  live_fields.insert(i);
809  }
810  }
811  auto it_ok =
812  new_liveouts.insert(std::make_pair(node, std::unordered_map<size_t, size_t>{}));
813  CHECK(it_ok.second);
814  auto& new_indices = it_ok.first->second;
815  if (intact_nodes.count(node)) {
816  for (size_t i = 0, e = node->size(); i < e; ++i) {
817  new_indices.insert(std::make_pair(i, i));
818  }
819  return;
820  }
821  if (does_redef_cols(node)) {
822  auto node_sz_it = orig_node_sizes.find(node);
823  CHECK(node_sz_it != orig_node_sizes.end());
824  const auto node_size = node_sz_it->second;
825  CHECK_GT(node_size, live_fields.size());
826  auto node_str = node->toString();
827  auto [node_substr, post_fix] = ::substring(node_str, g_max_log_length);
828  LOG(INFO) << node_substr << post_fix << " eliminated "
829  << node_size - live_fields.size() << " columns.";
830  std::vector<size_t> ordered_indices(live_fields.begin(), live_fields.end());
831  std::sort(ordered_indices.begin(), ordered_indices.end());
832  for (size_t i = 0; i < ordered_indices.size(); ++i) {
833  new_indices.insert(std::make_pair(ordered_indices[i], i));
834  }
835  return;
836  }
837  std::vector<size_t> ordered_indices;
838  for (size_t i = 0, old_base = 0, new_base = 0; i < node->inputCount(); ++i) {
839  auto src = node->getInput(i);
840  auto src_renum_it = new_liveouts.find(src);
841  if (src_renum_it != new_liveouts.end()) {
842  for (auto m : src_renum_it->second) {
843  new_indices.insert(std::make_pair(old_base + m.first, new_base + m.second));
844  }
845  new_base += src_renum_it->second.size();
846  } else if (dynamic_cast<const RelScan*>(src) || intact_nodes.count(src)) {
847  for (size_t i = 0; i < src->size(); ++i) {
848  new_indices.insert(std::make_pair(old_base + i, new_base + i));
849  }
850  new_base += src->size();
851  } else {
852  CHECK(false);
853  }
854  auto src_sz_it = orig_node_sizes.find(src);
855  CHECK(src_sz_it != orig_node_sizes.end());
856  old_base += src_sz_it->second;
857  }
858 }
859 
861  public:
863  const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
864  new_numbering)
865  : node_to_input_renum_(new_numbering) {}
866  RetType visitInput(const RexInput* input) const override {
867  auto source = input->getSourceNode();
868  auto node_it = node_to_input_renum_.find(source);
869  if (node_it != node_to_input_renum_.end()) {
870  auto old_to_new_num = node_it->second;
871  auto renum_it = old_to_new_num.find(input->getIndex());
872  CHECK(renum_it != old_to_new_num.end());
873  return boost::make_unique<RexInput>(source, renum_it->second);
874  }
875  return input->deepCopy();
876  }
877 
878  private:
879  const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
881 };
882 
883 std::vector<std::unique_ptr<const RexAgg>> renumber_rex_aggs(
884  std::vector<std::unique_ptr<const RexAgg>>& agg_exprs,
885  const std::unordered_map<size_t, size_t>& new_numbering) {
886  std::vector<std::unique_ptr<const RexAgg>> new_exprs;
887  for (auto& expr : agg_exprs) {
888  if (expr->size() >= 1) {
889  auto old_idx = expr->getOperand(0);
890  auto idx_it = new_numbering.find(old_idx);
891  if (idx_it != new_numbering.end()) {
892  std::vector<size_t> operands;
893  operands.push_back(idx_it->second);
894  if (expr->size() == 2) {
895  operands.push_back(expr->getOperand(1));
896  }
897  new_exprs.push_back(boost::make_unique<RexAgg>(
898  expr->getKind(), expr->isDistinct(), expr->getType(), operands));
899  continue;
900  }
901  }
902  new_exprs.push_back(std::move(expr));
903  }
904  return new_exprs;
905 }
906 
908  const std::unordered_map<size_t, size_t>& new_numbering) {
909  auto field_idx = old_field.getField();
910  auto idx_it = new_numbering.find(field_idx);
911  if (idx_it != new_numbering.end()) {
912  field_idx = idx_it->second;
913  }
914  return SortField(field_idx, old_field.getSortDir(), old_field.getNullsPosition());
915 }
916 
917 std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>> mark_live_columns(
918  std::vector<std::shared_ptr<RelAlgNode>>& nodes) {
919  std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>> live_outs;
920  std::vector<const RelAlgNode*> work_set;
921  for (auto node_it = nodes.rbegin(); node_it != nodes.rend(); ++node_it) {
922  auto node = node_it->get();
923  if (dynamic_cast<const RelScan*>(node) || live_outs.count(node) ||
924  dynamic_cast<const RelModify*>(node) ||
925  dynamic_cast<const RelTableFunction*>(node)) {
926  continue;
927  }
928  std::vector<size_t> all_live(node->size());
929  std::iota(all_live.begin(), all_live.end(), size_t(0));
930  live_outs.insert(std::make_pair(
931  node, std::unordered_set<size_t>(all_live.begin(), all_live.end())));
932 
933  work_set.push_back(node);
934  while (!work_set.empty()) {
935  auto walker = work_set.back();
936  work_set.pop_back();
937  CHECK(!dynamic_cast<const RelScan*>(walker));
938  CHECK(live_outs.count(walker));
939  auto live_ins = get_live_ins(walker, live_outs);
940  CHECK_EQ(live_ins.size(), walker->inputCount());
941  for (size_t i = 0; i < walker->inputCount(); ++i) {
942  auto src = walker->getInput(i);
943  if (dynamic_cast<const RelScan*>(src) ||
944  dynamic_cast<const RelTableFunction*>(src) || live_ins[i].empty()) {
945  continue;
946  }
947  if (!live_outs.count(src)) {
948  live_outs.insert(std::make_pair(src, std::unordered_set<size_t>{}));
949  }
950  auto src_it = live_outs.find(src);
951  CHECK(src_it != live_outs.end());
952  auto& live_out = src_it->second;
953  bool changed = false;
954  if (!live_out.empty()) {
955  live_out.insert(live_ins[i].begin(), live_ins[i].end());
956  changed = true;
957  } else {
958  for (int idx : live_ins[i]) {
959  changed |= live_out.insert(idx).second;
960  }
961  }
962  if (changed) {
963  work_set.push_back(src);
964  }
965  }
966  }
967  }
968  return live_outs;
969 }
970 
971 std::string get_field_name(const RelAlgNode* node, size_t index) {
972  CHECK_LT(index, node->size());
973  if (auto scan = dynamic_cast<const RelScan*>(node)) {
974  return scan->getFieldName(index);
975  }
976  if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
977  CHECK_EQ(aggregate->size(), aggregate->getFields().size());
978  return aggregate->getFieldName(index);
979  }
980  if (auto join = dynamic_cast<const RelJoin*>(node)) {
981  const auto lhs_size = join->getInput(0)->size();
982  if (index < lhs_size) {
983  return get_field_name(join->getInput(0), index);
984  }
985  return get_field_name(join->getInput(1), index - lhs_size);
986  }
987  if (auto project = dynamic_cast<const RelProject*>(node)) {
988  return project->getFieldName(index);
989  }
990  CHECK(dynamic_cast<const RelSort*>(node) || dynamic_cast<const RelFilter*>(node));
991  return get_field_name(node->getInput(0), index);
992 }
993 
995  std::vector<std::shared_ptr<RelAlgNode>>& nodes,
996  std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& liveouts,
997  std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
998  du_web) {
999  std::vector<std::shared_ptr<RelAlgNode>> new_nodes;
1000  for (auto node : nodes) {
1001  new_nodes.push_back(node);
1002  if (!std::dynamic_pointer_cast<RelFilter>(node)) {
1003  continue;
1004  }
1005  const auto filter = node.get();
1006  auto liveout_it = liveouts.find(filter);
1007  CHECK(liveout_it != liveouts.end());
1008  auto& outs = liveout_it->second;
1009  if (!any_dead_col_in(filter, outs)) {
1010  continue;
1011  }
1012  auto usrs_it = du_web.find(filter);
1013  CHECK(usrs_it != du_web.end());
1014  auto& usrs = usrs_it->second;
1015  if (usrs.size() != 1 || does_redef_cols(*usrs.begin())) {
1016  continue;
1017  }
1018  auto only_usr = const_cast<RelAlgNode*>(*usrs.begin());
1019 
1020  std::vector<std::unique_ptr<const RexScalar>> exprs;
1021  std::vector<std::string> fields;
1022  for (size_t i = 0; i < filter->size(); ++i) {
1023  exprs.push_back(boost::make_unique<RexInput>(filter, i));
1024  fields.push_back(get_field_name(filter, i));
1025  }
1026  auto project_owner = std::make_shared<RelProject>(exprs, fields, node);
1027  auto project = project_owner.get();
1028 
1029  only_usr->replaceInput(node, project_owner);
1030  if (dynamic_cast<const RelJoin*>(only_usr)) {
1031  RexRebindInputsVisitor visitor(filter, project);
1032  for (auto usr : du_web[only_usr]) {
1033  visitor.visitNode(usr);
1034  }
1035  }
1036 
1037  liveouts.insert(std::make_pair(project, outs));
1038 
1039  usrs.clear();
1040  usrs.insert(project);
1041  du_web.insert(
1042  std::make_pair(project, std::unordered_set<const RelAlgNode*>{only_usr}));
1043 
1044  new_nodes.push_back(project_owner);
1045  }
1046  if (new_nodes.size() > nodes.size()) {
1047  nodes.swap(new_nodes);
1048  }
1049 }
1050 
1051 std::pair<std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>,
1052  std::vector<const RelAlgNode*>>
1054  const std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& live_outs,
1055  const std::vector<std::shared_ptr<RelAlgNode>>& nodes,
1056  const std::unordered_set<const RelAlgNode*>& intact_nodes,
1057  const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
1058  du_web,
1059  const std::unordered_map<const RelAlgNode*, size_t>& orig_node_sizes) {
1060  std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>
1061  liveouts_renumbering;
1062  std::vector<const RelAlgNode*> ready_nodes;
1063  AvailabilityChecker checker(liveouts_renumbering, intact_nodes);
1064  for (auto node : nodes) {
1065  // Ignore empty live_out due to some invalid node
1066  if (!does_redef_cols(node.get()) || intact_nodes.count(node.get())) {
1067  continue;
1068  }
1069  auto live_pair = live_outs.find(node.get());
1070  CHECK(live_pair != live_outs.end());
1071  auto old_live_outs = live_pair->second;
1073  node.get(), liveouts_renumbering, old_live_outs, intact_nodes, orig_node_sizes);
1074  if (auto aggregate = std::dynamic_pointer_cast<RelAggregate>(node)) {
1075  auto old_exprs = aggregate->getAggExprsAndRelease();
1076  std::vector<std::unique_ptr<const RexAgg>> new_exprs;
1077  auto key_name_it = aggregate->getFields().begin();
1078  std::vector<std::string> new_fields(key_name_it,
1079  key_name_it + aggregate->getGroupByCount());
1080  for (size_t i = aggregate->getGroupByCount(), j = 0;
1081  i < aggregate->getFields().size() && j < old_exprs.size();
1082  ++i, ++j) {
1083  if (old_live_outs.count(i)) {
1084  new_exprs.push_back(std::move(old_exprs[j]));
1085  new_fields.push_back(aggregate->getFieldName(i));
1086  }
1087  }
1088  aggregate->setAggExprs(new_exprs);
1089  aggregate->setFields(std::move(new_fields));
1090  } else if (auto project = std::dynamic_pointer_cast<RelProject>(node)) {
1091  auto old_exprs = project->getExpressionsAndRelease();
1092  std::vector<std::unique_ptr<const RexScalar>> new_exprs;
1093  std::vector<std::string> new_fields;
1094  for (size_t i = 0; i < old_exprs.size(); ++i) {
1095  if (old_live_outs.count(i)) {
1096  new_exprs.push_back(std::move(old_exprs[i]));
1097  new_fields.push_back(project->getFieldName(i));
1098  }
1099  }
1100  project->setExpressions(new_exprs);
1101  project->setFields(std::move(new_fields));
1102  } else {
1103  CHECK(false);
1104  }
1105  auto usrs_it = du_web.find(node.get());
1106  CHECK(usrs_it != du_web.end());
1107  for (auto usr : usrs_it->second) {
1108  if (checker.hasAllSrcReady(usr)) {
1109  ready_nodes.push_back(usr);
1110  }
1111  }
1112  }
1113  return {liveouts_renumbering, ready_nodes};
1114 }
1115 
1117  std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
1118  liveout_renumbering,
1119  const std::vector<const RelAlgNode*>& ready_nodes,
1120  const std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& old_liveouts,
1121  const std::unordered_set<const RelAlgNode*>& intact_nodes,
1122  const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
1123  du_web,
1124  const std::unordered_map<const RelAlgNode*, size_t>& orig_node_sizes) {
1125  RexInputRenumberVisitor renumberer(liveout_renumbering);
1126  AvailabilityChecker checker(liveout_renumbering, intact_nodes);
1127  std::deque<const RelAlgNode*> work_set(ready_nodes.begin(), ready_nodes.end());
1128  while (!work_set.empty()) {
1129  auto walker = work_set.front();
1130  work_set.pop_front();
1131  CHECK(!dynamic_cast<const RelScan*>(walker));
1132  auto node = const_cast<RelAlgNode*>(walker);
1133  if (auto project = dynamic_cast<RelProject*>(node)) {
1134  auto old_exprs = project->getExpressionsAndRelease();
1135  std::vector<std::unique_ptr<const RexScalar>> new_exprs;
1136  for (auto& expr : old_exprs) {
1137  new_exprs.push_back(renumberer.visit(expr.get()));
1138  }
1139  project->setExpressions(new_exprs);
1140  } else if (auto aggregate = dynamic_cast<RelAggregate*>(node)) {
1141  auto src_it = liveout_renumbering.find(node->getInput(0));
1142  CHECK(src_it != liveout_renumbering.end());
1143  auto old_exprs = aggregate->getAggExprsAndRelease();
1144  auto new_exprs = renumber_rex_aggs(old_exprs, src_it->second);
1145  aggregate->setAggExprs(new_exprs);
1146  } else if (auto join = dynamic_cast<RelJoin*>(node)) {
1147  auto new_condition = renumberer.visit(join->getCondition());
1148  join->setCondition(new_condition);
1149  } else if (auto filter = dynamic_cast<RelFilter*>(node)) {
1150  auto new_condition = renumberer.visit(filter->getCondition());
1151  filter->setCondition(new_condition);
1152  } else if (auto sort = dynamic_cast<RelSort*>(node)) {
1153  auto src_it = liveout_renumbering.find(node->getInput(0));
1154  CHECK(src_it != liveout_renumbering.end());
1155  std::vector<SortField> new_collations;
1156  for (size_t i = 0; i < sort->collationCount(); ++i) {
1157  new_collations.push_back(
1158  renumber_sort_field(sort->getCollation(i), src_it->second));
1159  }
1160  sort->setCollation(std::move(new_collations));
1161  } else if (!dynamic_cast<RelLogicalUnion*>(node)) {
1162  LOG(FATAL) << "Unhandled node type: " << node->toString();
1163  }
1164 
1165  // Ignore empty live_out due to some invalid node
1166  if (does_redef_cols(node) || intact_nodes.count(node)) {
1167  continue;
1168  }
1169  auto live_pair = old_liveouts.find(node);
1170  CHECK(live_pair != old_liveouts.end());
1171  auto live_out = live_pair->second;
1173  node, liveout_renumbering, live_out, intact_nodes, orig_node_sizes);
1174  auto usrs_it = du_web.find(walker);
1175  CHECK(usrs_it != du_web.end());
1176  for (auto usr : usrs_it->second) {
1177  if (checker.hasAllSrcReady(usr)) {
1178  work_set.push_back(usr);
1179  }
1180  }
1181  }
1182 }
1183 
1184 } // namespace
1185 
1186 void eliminate_dead_columns(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1187  if (nodes.empty()) {
1188  return;
1189  }
1190  auto root = nodes.back().get();
1191  if (!root) {
1192  return;
1193  }
1194  CHECK(!dynamic_cast<const RelScan*>(root) && !dynamic_cast<const RelJoin*>(root));
1195  // Mark
1196  auto old_liveouts = mark_live_columns(nodes);
1197  std::unordered_set<const RelAlgNode*> intact_nodes;
1198  bool has_dead_cols = false;
1199  for (auto live_pair : old_liveouts) {
1200  auto node = live_pair.first;
1201  const auto& outs = live_pair.second;
1202  if (outs.empty()) {
1203  LOG(WARNING) << "RA node with no used column: " << node->toString();
1204  // Ignore empty live_out due to some invalid node
1205  intact_nodes.insert(node);
1206  }
1207  if (any_dead_col_in(node, outs)) {
1208  has_dead_cols = true;
1209  } else {
1210  intact_nodes.insert(node);
1211  }
1212  }
1213  if (!has_dead_cols) {
1214  return;
1215  }
1216  auto web = build_du_web(nodes);
1217  try_insert_coalesceable_proj(nodes, old_liveouts, web);
1218 
1219  for (auto node : nodes) {
1220  if (intact_nodes.count(node.get()) || does_redef_cols(node.get())) {
1221  continue;
1222  }
1223  bool intact = true;
1224  for (size_t i = 0; i < node->inputCount(); ++i) {
1225  auto source = node->getInput(i);
1226  if (!dynamic_cast<const RelScan*>(source) && !intact_nodes.count(source)) {
1227  intact = false;
1228  break;
1229  }
1230  }
1231  if (intact) {
1232  intact_nodes.insert(node.get());
1233  }
1234  }
1235 
1236  std::unordered_map<const RelAlgNode*, size_t> orig_node_sizes;
1237  for (auto node : nodes) {
1238  orig_node_sizes.insert(std::make_pair(node.get(), node->size()));
1239  }
1240  // Sweep
1241  std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>
1242  liveout_renumbering;
1243  std::vector<const RelAlgNode*> ready_nodes;
1244  std::tie(liveout_renumbering, ready_nodes) =
1245  sweep_dead_columns(old_liveouts, nodes, intact_nodes, web, orig_node_sizes);
1246  // Propagate
1248  liveout_renumbering, ready_nodes, old_liveouts, intact_nodes, web, orig_node_sizes);
1249 }
1250 
1251 void eliminate_dead_subqueries(std::vector<std::shared_ptr<RexSubQuery>>& subqueries,
1252  RelAlgNode const* root) {
1253  if (!subqueries.empty()) {
1254  auto live_ids = RexSubQueryIdCollector::getLiveRexSubQueryIds(root);
1255  auto sort_live_ids_first = [&live_ids](auto& a, auto& b) {
1256  return live_ids.count(a->getId()) && !live_ids.count(b->getId());
1257  };
1258  std::stable_sort(subqueries.begin(), subqueries.end(), sort_live_ids_first);
1259  size_t n_dead_subqueries;
1260  if (live_ids.count(subqueries.front()->getId())) {
1261  auto first_dead_itr = std::upper_bound(subqueries.cbegin(),
1262  subqueries.cend(),
1263  subqueries.front(),
1264  sort_live_ids_first);
1265  n_dead_subqueries = subqueries.cend() - first_dead_itr;
1266  } else {
1267  n_dead_subqueries = subqueries.size();
1268  }
1269  if (n_dead_subqueries) {
1270  VLOG(1) << "Eliminating " << n_dead_subqueries
1271  << (n_dead_subqueries == 1 ? " subquery." : " subqueries.");
1272  subqueries.resize(subqueries.size() - n_dead_subqueries);
1273  subqueries.shrink_to_fit();
1274  }
1275  }
1276 }
1277 
1278 namespace {
1279 
1281  public:
1282  RexInputSinker(const std::unordered_map<size_t, size_t>& old_to_new_idx,
1283  const RelAlgNode* new_src)
1284  : old_to_new_in_idx_(old_to_new_idx), target_(new_src) {}
1285 
1286  RetType visitInput(const RexInput* input) const override {
1287  CHECK_EQ(target_->inputCount(), size_t(1));
1288  CHECK_EQ(target_->getInput(0), input->getSourceNode());
1289  auto idx_it = old_to_new_in_idx_.find(input->getIndex());
1290  CHECK(idx_it != old_to_new_in_idx_.end());
1291  return boost::make_unique<RexInput>(target_, idx_it->second);
1292  }
1293 
1294  private:
1295  const std::unordered_map<size_t, size_t>& old_to_new_in_idx_;
1297 };
1298 
1300  public:
1301  SubConditionReplacer(const std::unordered_map<size_t, std::unique_ptr<const RexScalar>>&
1302  idx_to_sub_condition)
1303  : idx_to_subcond_(idx_to_sub_condition) {}
1304  RetType visitInput(const RexInput* input) const override {
1305  auto subcond_it = idx_to_subcond_.find(input->getIndex());
1306  if (subcond_it != idx_to_subcond_.end()) {
1307  return RexDeepCopyVisitor::visit(subcond_it->second.get());
1308  }
1309  return RexDeepCopyVisitor::visitInput(input);
1310  }
1311 
1312  private:
1313  const std::unordered_map<size_t, std::unique_ptr<const RexScalar>>& idx_to_subcond_;
1314 };
1315 
1316 } // namespace
1317 
1319  std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1320  auto web = build_du_web(nodes);
1321  auto liveouts = mark_live_columns(nodes);
1322  for (auto node : nodes) {
1323  auto project = std::dynamic_pointer_cast<RelProject>(node);
1324  // TODO(miyu): relax RelScan limitation
1325  if (!project || project->isSimple() ||
1326  !dynamic_cast<const RelScan*>(project->getInput(0))) {
1327  continue;
1328  }
1329  auto usrs_it = web.find(project.get());
1330  CHECK(usrs_it != web.end());
1331  auto& usrs = usrs_it->second;
1332  if (usrs.size() != 1) {
1333  continue;
1334  }
1335  auto join = dynamic_cast<RelJoin*>(const_cast<RelAlgNode*>(*usrs.begin()));
1336  if (!join) {
1337  continue;
1338  }
1339  auto outs_it = liveouts.find(join);
1340  CHECK(outs_it != liveouts.end());
1341  std::unordered_map<size_t, size_t> in_to_out_index;
1342  std::unordered_set<size_t> boolean_expr_indicies;
1343  bool discarded = false;
1344  for (size_t i = 0; i < project->size(); ++i) {
1345  auto oper = dynamic_cast<const RexOperator*>(project->getProjectAt(i));
1346  if (oper && oper->getType().get_type() == kBOOLEAN) {
1347  boolean_expr_indicies.insert(i);
1348  } else {
1349  // TODO(miyu): relax?
1350  if (auto input = dynamic_cast<const RexInput*>(project->getProjectAt(i))) {
1351  in_to_out_index.insert(std::make_pair(input->getIndex(), i));
1352  } else {
1353  discarded = true;
1354  }
1355  }
1356  }
1357  if (discarded || boolean_expr_indicies.empty()) {
1358  continue;
1359  }
1360  const size_t index_base =
1361  join->getInput(0) == project.get() ? 0 : join->getInput(0)->size();
1362  for (auto i : boolean_expr_indicies) {
1363  auto join_idx = index_base + i;
1364  if (outs_it->second.count(join_idx)) {
1365  discarded = true;
1366  break;
1367  }
1368  }
1369  if (discarded) {
1370  continue;
1371  }
1372  RexInputCollector collector(project.get());
1373  std::vector<size_t> unloaded_input_indices;
1374  std::unordered_map<size_t, std::unique_ptr<const RexScalar>> in_idx_to_new_subcond;
1375  // Given all are dead right after join, safe to sink
1376  for (auto i : boolean_expr_indicies) {
1377  auto rex_ins = collector.visit(project->getProjectAt(i));
1378  for (auto& in : rex_ins) {
1379  CHECK_EQ(in.getSourceNode(), project->getInput(0));
1380  if (!in_to_out_index.count(in.getIndex())) {
1381  auto curr_out_index = project->size() + unloaded_input_indices.size();
1382  in_to_out_index.insert(std::make_pair(in.getIndex(), curr_out_index));
1383  unloaded_input_indices.push_back(in.getIndex());
1384  }
1385  RexInputSinker sinker(in_to_out_index, project.get());
1386  in_idx_to_new_subcond.insert(
1387  std::make_pair(i, sinker.visit(project->getProjectAt(i))));
1388  }
1389  }
1390  if (in_idx_to_new_subcond.empty()) {
1391  continue;
1392  }
1393  std::vector<std::unique_ptr<const RexScalar>> new_projections;
1394  for (size_t i = 0; i < project->size(); ++i) {
1395  if (boolean_expr_indicies.count(i)) {
1396  new_projections.push_back(boost::make_unique<RexInput>(project->getInput(0), 0));
1397  } else {
1398  auto rex_input = dynamic_cast<const RexInput*>(project->getProjectAt(i));
1399  CHECK(rex_input != nullptr);
1400  new_projections.push_back(rex_input->deepCopy());
1401  }
1402  }
1403  for (auto i : unloaded_input_indices) {
1404  new_projections.push_back(boost::make_unique<RexInput>(project->getInput(0), i));
1405  }
1406  project->setExpressions(new_projections);
1407 
1408  SubConditionReplacer replacer(in_idx_to_new_subcond);
1409  auto new_condition = replacer.visit(join->getCondition());
1410  join->setCondition(new_condition);
1411  }
1412 }
1413 
1414 namespace {
1415 
1417  public:
1418  RexInputRedirector(const RelAlgNode* old_src, const RelAlgNode* new_src)
1419  : old_src_(old_src), new_src_(new_src) {}
1420 
1421  RetType visitInput(const RexInput* input) const override {
1422  CHECK_EQ(old_src_, input->getSourceNode());
1423  CHECK_NE(old_src_, new_src_);
1424  auto actual_new_src = new_src_;
1425  if (auto join = dynamic_cast<const RelJoin*>(new_src_)) {
1426  actual_new_src = join->getInput(0);
1427  CHECK_EQ(join->inputCount(), size_t(2));
1428  auto src2_input_base = actual_new_src->size();
1429  if (input->getIndex() >= src2_input_base) {
1430  actual_new_src = join->getInput(1);
1431  return boost::make_unique<RexInput>(actual_new_src,
1432  input->getIndex() - src2_input_base);
1433  }
1434  }
1435 
1436  return boost::make_unique<RexInput>(actual_new_src, input->getIndex());
1437  }
1438 
1439  private:
1442 };
1443 
1445  std::shared_ptr<const RelAlgNode> old_def_node,
1446  std::shared_ptr<const RelAlgNode> new_def_node,
1447  std::unordered_map<const RelAlgNode*, std::shared_ptr<RelAlgNode>>& deconst_mapping,
1448  std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
1449  du_web) {
1450  auto usrs_it = du_web.find(old_def_node.get());
1451  RexInputRedirector redirector(new_def_node.get(), old_def_node.get());
1452  CHECK(usrs_it != du_web.end());
1453  for (auto usr : usrs_it->second) {
1454  auto usr_it = deconst_mapping.find(usr);
1455  CHECK(usr_it != deconst_mapping.end());
1456  usr_it->second->replaceInput(old_def_node, new_def_node);
1457  }
1458  auto new_usrs_it = du_web.find(new_def_node.get());
1459  CHECK(new_usrs_it != du_web.end());
1460  new_usrs_it->second.insert(usrs_it->second.begin(), usrs_it->second.end());
1461  usrs_it->second.clear();
1462 }
1463 
1464 } // namespace
1465 
1466 void fold_filters(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1467  std::unordered_map<const RelAlgNode*, std::shared_ptr<RelAlgNode>> deconst_mapping;
1468  for (auto node : nodes) {
1469  deconst_mapping.insert(std::make_pair(node.get(), node));
1470  }
1471 
1472  auto web = build_du_web(nodes);
1473  for (auto node_it = nodes.rbegin(); node_it != nodes.rend(); ++node_it) {
1474  auto& node = *node_it;
1475  if (auto filter = std::dynamic_pointer_cast<RelFilter>(node)) {
1476  CHECK_EQ(filter->inputCount(), size_t(1));
1477  auto src_filter = dynamic_cast<const RelFilter*>(filter->getInput(0));
1478  if (!src_filter) {
1479  continue;
1480  }
1481  auto siblings_it = web.find(src_filter);
1482  if (siblings_it == web.end() || siblings_it->second.size() != size_t(1)) {
1483  continue;
1484  }
1485  auto src_it = deconst_mapping.find(src_filter);
1486  CHECK(src_it != deconst_mapping.end());
1487  auto folded_filter = std::dynamic_pointer_cast<RelFilter>(src_it->second);
1488  CHECK(folded_filter);
1489  // TODO(miyu) : drop filter w/ only expression valued constant TRUE?
1490  if (auto rex_operator = dynamic_cast<const RexOperator*>(filter->getCondition())) {
1491  VLOG(1) << "Node ID=" << filter->getId() << " folded into "
1492  << "ID=" << folded_filter->getId();
1494  auto node_str = folded_filter->toString();
1495  auto [node_substr, post_fix] = ::substring(node_str, g_max_log_length);
1496  VLOG(2) << "Folded Node (ID: " << folded_filter->getId()
1497  << ") contents: " << node_substr << post_fix;
1498  }
1499  std::vector<std::unique_ptr<const RexScalar>> operands;
1500  operands.emplace_back(folded_filter->getAndReleaseCondition());
1501  auto old_condition = dynamic_cast<const RexOperator*>(operands.back().get());
1502  CHECK(old_condition && old_condition->getType().get_type() == kBOOLEAN);
1503  RexInputRedirector redirector(folded_filter.get(), folded_filter->getInput(0));
1504  operands.push_back(redirector.visit(rex_operator));
1505  auto other_condition = dynamic_cast<const RexOperator*>(operands.back().get());
1506  CHECK(other_condition && other_condition->getType().get_type() == kBOOLEAN);
1507  const bool notnull = old_condition->getType().get_notnull() &&
1508  other_condition->getType().get_notnull();
1509  auto new_condition = std::unique_ptr<const RexScalar>(
1510  new RexOperator(kAND, operands, SQLTypeInfo(kBOOLEAN, notnull)));
1511  folded_filter->setCondition(new_condition);
1512  replace_all_usages(filter, folded_filter, deconst_mapping, web);
1513  deconst_mapping.erase(filter.get());
1514  web.erase(filter.get());
1515  web[filter->getInput(0)].erase(filter.get());
1516  node.reset();
1517  }
1518  }
1519  }
1520 
1521  if (!nodes.empty()) {
1522  auto sink = nodes.back();
1523  for (auto node_it = std::next(nodes.rbegin()); node_it != nodes.rend(); ++node_it) {
1524  if (sink) {
1525  break;
1526  }
1527  sink = *node_it;
1528  }
1529  CHECK(sink);
1530  cleanup_dead_nodes(nodes);
1531  }
1532 }
1533 
1534 std::vector<const RexScalar*> find_hoistable_conditions(const RexScalar* condition,
1535  const RelAlgNode* source,
1536  const size_t first_col_idx,
1537  const size_t last_col_idx) {
1538  if (auto rex_op = dynamic_cast<const RexOperator*>(condition)) {
1539  switch (rex_op->getOperator()) {
1540  case kAND: {
1541  std::vector<const RexScalar*> subconditions;
1542  size_t complete_subcond_count = 0;
1543  for (size_t i = 0; i < rex_op->size(); ++i) {
1544  auto conds = find_hoistable_conditions(
1545  rex_op->getOperand(i), source, first_col_idx, last_col_idx);
1546  if (conds.size() == size_t(1)) {
1547  ++complete_subcond_count;
1548  }
1549  subconditions.insert(subconditions.end(), conds.begin(), conds.end());
1550  }
1551  if (complete_subcond_count == rex_op->size()) {
1552  return {rex_op};
1553  } else {
1554  return {subconditions};
1555  }
1556  break;
1557  }
1558  case kEQ: {
1559  const auto lhs_conds = find_hoistable_conditions(
1560  rex_op->getOperand(0), source, first_col_idx, last_col_idx);
1561  const auto rhs_conds = find_hoistable_conditions(
1562  rex_op->getOperand(1), source, first_col_idx, last_col_idx);
1563  const auto lhs_in = lhs_conds.size() == 1
1564  ? dynamic_cast<const RexInput*>(*lhs_conds.begin())
1565  : nullptr;
1566  const auto rhs_in = rhs_conds.size() == 1
1567  ? dynamic_cast<const RexInput*>(*rhs_conds.begin())
1568  : nullptr;
1569  if (lhs_in && rhs_in) {
1570  return {rex_op};
1571  }
1572  return {};
1573  break;
1574  }
1575  default:
1576  break;
1577  }
1578  return {};
1579  }
1580  if (auto rex_in = dynamic_cast<const RexInput*>(condition)) {
1581  if (rex_in->getSourceNode() == source) {
1582  const auto col_idx = rex_in->getIndex();
1583  return {col_idx >= first_col_idx && col_idx <= last_col_idx ? condition : nullptr};
1584  }
1585  return {};
1586  }
1587  return {};
1588 }
1589 
1591  public:
1592  JoinTargetRebaser(const RelJoin* join, const unsigned old_base)
1593  : join_(join)
1594  , old_base_(old_base)
1595  , src1_base_(join->getInput(0)->size())
1596  , target_count_(join->size()) {}
1597  RetType visitInput(const RexInput* input) const override {
1598  auto curr_idx = input->getIndex();
1599  CHECK_GE(curr_idx, old_base_);
1600  CHECK_LT(static_cast<size_t>(curr_idx), target_count_);
1601  curr_idx -= old_base_;
1602  if (curr_idx >= src1_base_) {
1603  return boost::make_unique<RexInput>(join_->getInput(1), curr_idx - src1_base_);
1604  } else {
1605  return boost::make_unique<RexInput>(join_->getInput(0), curr_idx);
1606  }
1607  }
1608 
1609  private:
1610  const RelJoin* join_;
1611  const unsigned old_base_;
1612  const size_t src1_base_;
1613  const size_t target_count_;
1614 };
1615 
1617  public:
1618  SubConditionRemover(const std::vector<const RexScalar*> sub_conds)
1619  : sub_conditions_(sub_conds.begin(), sub_conds.end()) {}
1620  RetType visitOperator(const RexOperator* rex_operator) const override {
1621  if (sub_conditions_.count(rex_operator)) {
1622  return boost::make_unique<RexLiteral>(
1623  true, kBOOLEAN, kBOOLEAN, unsigned(-2147483648), 1, unsigned(-2147483648), 1);
1624  }
1625  return RexDeepCopyVisitor::visitOperator(rex_operator);
1626  }
1627 
1628  private:
1629  std::unordered_set<const RexScalar*> sub_conditions_;
1630 };
1631 
1633  std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1634  std::unordered_set<const RelAlgNode*> visited;
1635  auto web = build_du_web(nodes);
1636  for (auto node : nodes) {
1637  if (visited.count(node.get())) {
1638  continue;
1639  }
1640  visited.insert(node.get());
1641  auto join = dynamic_cast<RelJoin*>(node.get());
1642  if (join && join->getJoinType() == JoinType::INNER) {
1643  // Only allow cross join for now.
1644  if (auto literal = dynamic_cast<const RexLiteral*>(join->getCondition())) {
1645  // Assume Calcite always generates an inner join on constant boolean true for
1646  // cross join.
1647  CHECK(literal->getType() == kBOOLEAN && literal->getVal<bool>());
1648  size_t first_col_idx = 0;
1649  const RelFilter* filter = nullptr;
1650  std::vector<const RelJoin*> join_seq{join};
1651  for (const RelJoin* curr_join = join; !filter;) {
1652  auto usrs_it = web.find(curr_join);
1653  CHECK(usrs_it != web.end());
1654  if (usrs_it->second.size() != size_t(1)) {
1655  break;
1656  }
1657  auto only_usr = *usrs_it->second.begin();
1658  if (auto usr_join = dynamic_cast<const RelJoin*>(only_usr)) {
1659  if (join == usr_join->getInput(1)) {
1660  const auto src1_offset = usr_join->getInput(0)->size();
1661  first_col_idx += src1_offset;
1662  }
1663  join_seq.push_back(usr_join);
1664  curr_join = usr_join;
1665  continue;
1666  }
1667 
1668  filter = dynamic_cast<const RelFilter*>(only_usr);
1669  break;
1670  }
1671  if (!filter) {
1672  visited.insert(join_seq.begin(), join_seq.end());
1673  continue;
1674  }
1675  const auto src_join = dynamic_cast<const RelJoin*>(filter->getInput(0));
1676  CHECK(src_join);
1677  auto modified_filter = const_cast<RelFilter*>(filter);
1678 
1679  if (src_join == join) {
1680  std::unique_ptr<const RexScalar> filter_condition(
1681  modified_filter->getAndReleaseCondition());
1682  std::unique_ptr<const RexScalar> true_condition =
1683  boost::make_unique<RexLiteral>(true,
1684  kBOOLEAN,
1685  kBOOLEAN,
1686  unsigned(-2147483648),
1687  1,
1688  unsigned(-2147483648),
1689  1);
1690  modified_filter->setCondition(true_condition);
1691  join->setCondition(filter_condition);
1692  continue;
1693  }
1694  const auto src1_base = src_join->getInput(0)->size();
1695  auto source =
1696  first_col_idx < src1_base ? src_join->getInput(0) : src_join->getInput(1);
1697  first_col_idx =
1698  first_col_idx < src1_base ? first_col_idx : first_col_idx - src1_base;
1699  auto join_conditions =
1701  source,
1702  first_col_idx,
1703  first_col_idx + join->size() - 1);
1704  if (join_conditions.empty()) {
1705  continue;
1706  }
1707 
1708  JoinTargetRebaser rebaser(join, first_col_idx);
1709  if (join_conditions.size() == 1) {
1710  auto new_join_condition = rebaser.visit(*join_conditions.begin());
1711  join->setCondition(new_join_condition);
1712  } else {
1713  std::vector<std::unique_ptr<const RexScalar>> operands;
1714  bool notnull = true;
1715  for (size_t i = 0; i < join_conditions.size(); ++i) {
1716  operands.emplace_back(rebaser.visit(join_conditions[i]));
1717  auto old_subcond = dynamic_cast<const RexOperator*>(join_conditions[i]);
1718  CHECK(old_subcond && old_subcond->getType().get_type() == kBOOLEAN);
1719  notnull = notnull && old_subcond->getType().get_notnull();
1720  }
1721  auto new_join_condition = std::unique_ptr<const RexScalar>(
1722  new RexOperator(kAND, operands, SQLTypeInfo(kBOOLEAN, notnull)));
1723  join->setCondition(new_join_condition);
1724  }
1725 
1726  SubConditionRemover remover(join_conditions);
1727  auto new_filter_condition = remover.visit(filter->getCondition());
1728  modified_filter->setCondition(new_filter_condition);
1729  }
1730  }
1731  }
1732 }
1733 
1734 void sync_field_names_if_necessary(std::shared_ptr<const RelProject> from_node,
1735  RelAlgNode* to_node) noexcept {
1736  auto from_fields = from_node->getFields();
1737  if (!from_fields.empty()) {
1738  if (auto proj_to = dynamic_cast<RelProject*>(to_node);
1739  proj_to && proj_to->getFields().size() == from_fields.size()) {
1740  proj_to->setFields(std::move(from_fields));
1741  } else if (auto agg_to = dynamic_cast<RelAggregate*>(to_node);
1742  agg_to && agg_to->getFields().size() == from_fields.size()) {
1743  agg_to->setFields(std::move(from_fields));
1744  } else if (auto compound_to = dynamic_cast<RelCompound*>(to_node);
1745  compound_to && compound_to->getFields().size() == from_fields.size()) {
1746  compound_to->setFields(std::move(from_fields));
1747  } else if (auto tf_to = dynamic_cast<RelTableFunction*>(to_node);
1748  tf_to && tf_to->getFields().size() == from_fields.size()) {
1749  tf_to->setFields(std::move(from_fields));
1750  }
1751  }
1752 }
1753 
1754 // For some reason, Calcite generates Sort, Project, Sort sequences where the
1755 // two Sort nodes are identical and the Project is identity. Simplify this
1756 // pattern by re-binding the input of the second sort to the input of the first.
1757 void simplify_sort(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1758  if (nodes.size() < 3) {
1759  return;
1760  }
1761  for (size_t i = 0; i <= nodes.size() - 3;) {
1762  auto first_sort = std::dynamic_pointer_cast<RelSort>(nodes[i]);
1763  const auto project = std::dynamic_pointer_cast<const RelProject>(nodes[i + 1]);
1764  auto second_sort = std::dynamic_pointer_cast<RelSort>(nodes[i + 2]);
1765  if (first_sort && second_sort && project && project->isIdentity() &&
1766  *first_sort == *second_sort) {
1767  sync_field_names_if_necessary(project, /* an input of the second sort */
1768  const_cast<RelAlgNode*>(first_sort->getInput(0)));
1769  second_sort->replaceInput(second_sort->getAndOwnInput(0),
1770  first_sort->getAndOwnInput(0));
1771  nodes[i].reset();
1772  nodes[i + 1].reset();
1773  i += 3;
1774  } else {
1775  ++i;
1776  }
1777  }
1778 
1779  std::vector<std::shared_ptr<RelAlgNode>> new_nodes;
1780  for (auto node : nodes) {
1781  if (!node) {
1782  continue;
1783  }
1784  new_nodes.push_back(node);
1785  }
1786  nodes.swap(new_nodes);
1787 }
DEVICE auto upper_bound(ARGS &&...args)
Definition: gpu_enabled.h:123
bool is_identical_copy(const RelProject *project, const std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web, const std::unordered_set< const RelProject * > &projects_to_remove, std::unordered_set< const RelProject * > &permutating_projects)
SubConditionReplacer(const std::unordered_map< size_t, std::unique_ptr< const RexScalar >> &idx_to_sub_condition)
std::vector< const RexScalar * > find_hoistable_conditions(const RexScalar *condition, const RelAlgNode *source, const size_t first_col_idx, const size_t last_col_idx)
std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * > > build_du_web(const std::vector< std::shared_ptr< RelAlgNode >> &nodes) noexcept
RetType visitInput(const RexInput *input) const override
#define CHECK_EQ(x, y)
Definition: Logger.h:219
const size_t target_count_
RexInputRedirector(const RelAlgNode *old_src, const RelAlgNode *new_src)
size_t get_actual_source_size(const RelProject *curr_project, const std::unordered_set< const RelProject * > &projects_to_remove)
size_t pick_always_live_col_idx(const RelAlgNode *node)
void redirect_inputs_of(std::shared_ptr< RelAlgNode > node, const std::unordered_set< const RelProject * > &projects, const std::unordered_set< const RelProject * > &permutating_projects, const std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web)
const std::unordered_map< const RelAlgNode *, std::unordered_map< size_t, size_t > > & node_to_input_renum_
void hoist_filter_cond_to_cross_join(std::vector< std::shared_ptr< RelAlgNode >> &nodes) noexcept
RexInputSinker(const std::unordered_map< size_t, size_t > &old_to_new_idx, const RelAlgNode *new_src)
AvailabilityChecker(const std::unordered_map< const RelAlgNode *, std::unordered_map< size_t, size_t >> &liveouts, const std::unordered_set< const RelAlgNode * > &intact_nodes)
size_t size() const override
void sink_projected_boolean_expr_to_join(std::vector< std::shared_ptr< RelAlgNode >> &nodes) noexcept
RetType visitInput(const RexInput *input) const override
void eliminate_identical_copy(std::vector< std::shared_ptr< RelAlgNode >> &nodes) noexcept
void setCondition(std::unique_ptr< const RexScalar > &condition)
#define LOG(tag)
Definition: Logger.h:205
SortDirection getSortDir() const
bool does_redef_cols(const RelAlgNode *node)
const RexScalar * getCondition() const
RetType visitOperator(const RexOperator *rex_operator) const override
Definition: RexVisitor.h:153
std::string join(T const &container, std::string const &delim)
void propagate_input_renumbering(std::unordered_map< const RelAlgNode *, std::unordered_map< size_t, size_t >> &liveout_renumbering, const std::vector< const RelAlgNode * > &ready_nodes, const std::unordered_map< const RelAlgNode *, std::unordered_set< size_t >> &old_liveouts, const std::unordered_set< const RelAlgNode * > &intact_nodes, const std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web, const std::unordered_map< const RelAlgNode *, size_t > &orig_node_sizes)
void * visitInput(const RexInput *rex_input) const override
DEVICE void sort(ARGS &&...args)
Definition: gpu_enabled.h:105
#define CHECK_GE(x, y)
Definition: Logger.h:224
size_t getField() const
RetType visitOperator(const RexOperator *rex_operator) const override
Definition: sqldefs.h:30
tuple root
Definition: setup.in.py:14
std::unordered_set< const RelProject * > get_visible_projects(const RelAlgNode *root)
#define CHECK_GT(x, y)
Definition: Logger.h:223
const std::unordered_set< const RelProject * > & crt_projects_
bool project_separates_sort(const RelProject *project, const RelAlgNode *next_node)
std::unordered_map< const RelAlgNode *, std::unordered_set< size_t > > mark_live_columns(std::vector< std::shared_ptr< RelAlgNode >> &nodes)
bool safe_to_redirect(const RelProject *project, const std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web)
void simplify_sort(std::vector< std::shared_ptr< RelAlgNode >> &nodes) noexcept
constexpr double a
Definition: Utm.h:32
virtual T visit(const RexScalar *rex_scalar) const
Definition: RexVisitor.h:27
const std::unordered_map< const RelAlgNode *, std::unordered_map< size_t, size_t > > & liveouts_
unsigned getIndex() const
std::vector< std::unordered_set< size_t > > get_live_ins(const RelAlgNode *node, const std::unordered_map< const RelAlgNode *, std::unordered_set< size_t >> &live_outs)
RetType visitInput(const RexInput *input) const override
void cleanup_dead_nodes(std::vector< std::shared_ptr< RelAlgNode >> &nodes)
RetType visitInput(const RexInput *input) const override
bool fast_logging_check(Channel)
Definition: Logger.h:185
#define CHECK_NE(x, y)
Definition: Logger.h:220
NullSortedPosition getNullsPosition() const
static Ids getLiveRexSubQueryIds(RelAlgNode const *)
const std::unordered_map< size_t, size_t > & old_to_new_in_idx_
const RelAlgNode * getInput(const size_t idx) const
Definition: sqldefs.h:37
bool isSimple() const
size_t g_max_log_length
Definition: Execute.cpp:150
RetType visitInput(const RexInput *input) const override
Definition: RexVisitor.h:141
virtual void replaceInput(std::shared_ptr< const RelAlgNode > old_input, std::shared_ptr< const RelAlgNode > input)
RetType aggregateResult(const RetType &aggregate, const RetType &next_result) const override
std::unique_ptr< RexInput > deepCopy() const
bool any_dead_col_in(const RelAlgNode *node, const std::unordered_set< size_t > &live_outs)
const std::unordered_set< const RelAlgNode * > & intact_nodes_
RexRebindInputsVisitor(const RelAlgNode *old_input, const RelAlgNode *new_input)
const RexScalar * getProjectAt(const size_t idx) const
#define CHECK_LT(x, y)
Definition: Logger.h:221
void sync_field_names_if_necessary(std::shared_ptr< const RelProject > from_node, RelAlgNode *to_node) noexcept
void setSourceNode(const RelAlgNode *node) const
DEVICE void iota(ARGS &&...args)
Definition: gpu_enabled.h:69
RetType visitInput(const RexInput *input) const override
virtual size_t size() const =0
const RelAlgNode * getSourceNode() const
RetType visitInput(const RexInput *input) const override
void try_insert_coalesceable_proj(std::vector< std::shared_ptr< RelAlgNode >> &nodes, std::unordered_map< const RelAlgNode *, std::unordered_set< size_t >> &liveouts, std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web)
std::vector< std::unique_ptr< const RexAgg > > renumber_rex_aggs(std::vector< std::unique_ptr< const RexAgg >> &agg_exprs, const std::unordered_map< size_t, size_t > &new_numbering)
SortField renumber_sort_field(const SortField &old_field, const std::unordered_map< size_t, size_t > &new_numbering)
virtual std::string toString() const =0
#define CHECK(condition)
Definition: Logger.h:211
SubConditionRemover(const std::vector< const RexScalar * > sub_conds)
std::unordered_set< const RexScalar * > sub_conditions_
const RelJoin * join_
void propagate_rex_input_renumber(const RelFilter *excluded_root, const std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web)
void add_new_indices_for(const RelAlgNode *node, std::unordered_map< const RelAlgNode *, std::unordered_map< size_t, size_t >> &new_liveouts, const std::unordered_set< size_t > &old_liveouts, const std::unordered_set< const RelAlgNode * > &intact_nodes, const std::unordered_map< const RelAlgNode *, size_t > &orig_node_sizes)
std::string get_field_name(const RelAlgNode *node, size_t index)
void fold_filters(std::vector< std::shared_ptr< RelAlgNode >> &nodes) noexcept
const std::unordered_map< size_t, std::unique_ptr< const RexScalar > > & idx_to_subcond_
const size_t inputCount() const
void eliminate_dead_subqueries(std::vector< std::shared_ptr< RexSubQuery >> &subqueries, RelAlgNode const *root)
void replace_all_usages(std::shared_ptr< const RelAlgNode > old_def_node, std::shared_ptr< const RelAlgNode > new_def_node, std::unordered_map< const RelAlgNode *, std::shared_ptr< RelAlgNode >> &deconst_mapping, std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web)
const unsigned old_base_
RexInputRenumberVisitor(const std::unordered_map< const RelAlgNode *, std::unordered_map< size_t, size_t >> &new_numbering)
bool is_distinct(const size_t input_idx, const RelAlgNode *node)
std::pair< std::unordered_map< const RelAlgNode *, std::unordered_map< size_t, size_t > >, std::vector< const RelAlgNode * > > sweep_dead_columns(const std::unordered_map< const RelAlgNode *, std::unordered_set< size_t >> &live_outs, const std::vector< std::shared_ptr< RelAlgNode >> &nodes, const std::unordered_set< const RelAlgNode * > &intact_nodes, const std::unordered_map< const RelAlgNode *, std::unordered_set< const RelAlgNode * >> &du_web, const std::unordered_map< const RelAlgNode *, size_t > &orig_node_sizes)
JoinTargetRebaser(const RelJoin *join, const unsigned old_base)
RexProjectInputRedirector(const std::unordered_set< const RelProject * > &crt_inputs)
DEVICE void swap(ARGS &&...args)
Definition: gpu_enabled.h:114
std::unique_ptr< const RexScalar > RetType
Definition: RexVisitor.h:139
#define VLOG(n)
Definition: Logger.h:305
std::pair< std::string_view, const char * > substring(const std::string &str, size_t substr_length)
return substring of str with postfix if str.size() &gt; substr_length
void eliminate_dead_columns(std::vector< std::shared_ptr< RelAlgNode >> &nodes) noexcept
RetType visitInput(const RexInput *input) const override