OmniSciDB  72c90bc290
 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 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "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(RelRexToStringConfig::defaults());
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(RelRexToStringConfig::defaults());
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(RelRexToStringConfig::defaults());
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(RelRexToStringConfig::defaults());
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: "
1163  << node->toString(RelRexToStringConfig::defaults());
1164  }
1165 
1166  // Ignore empty live_out due to some invalid node
1167  if (does_redef_cols(node) || intact_nodes.count(node)) {
1168  continue;
1169  }
1170  auto live_pair = old_liveouts.find(node);
1171  CHECK(live_pair != old_liveouts.end());
1172  auto live_out = live_pair->second;
1174  node, liveout_renumbering, live_out, intact_nodes, orig_node_sizes);
1175  auto usrs_it = du_web.find(walker);
1176  CHECK(usrs_it != du_web.end());
1177  for (auto usr : usrs_it->second) {
1178  if (checker.hasAllSrcReady(usr)) {
1179  work_set.push_back(usr);
1180  }
1181  }
1182  }
1183 }
1184 
1185 } // namespace
1186 
1187 void eliminate_dead_columns(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1188  if (nodes.empty()) {
1189  return;
1190  }
1191  auto root = nodes.back().get();
1192  if (!root) {
1193  return;
1194  }
1195  CHECK(!dynamic_cast<const RelScan*>(root) && !dynamic_cast<const RelJoin*>(root));
1196  // Mark
1197  auto old_liveouts = mark_live_columns(nodes);
1198  std::unordered_set<const RelAlgNode*> intact_nodes;
1199  bool has_dead_cols = false;
1200  for (auto live_pair : old_liveouts) {
1201  auto node = live_pair.first;
1202  const auto& outs = live_pair.second;
1203  if (outs.empty()) {
1204  LOG(WARNING) << "RA node with no used column: "
1205  << node->toString(RelRexToStringConfig::defaults());
1206  // Ignore empty live_out due to some invalid node
1207  intact_nodes.insert(node);
1208  }
1209  if (any_dead_col_in(node, outs)) {
1210  has_dead_cols = true;
1211  } else {
1212  intact_nodes.insert(node);
1213  }
1214  }
1215  if (!has_dead_cols) {
1216  return;
1217  }
1218  auto web = build_du_web(nodes);
1219  try_insert_coalesceable_proj(nodes, old_liveouts, web);
1220 
1221  for (auto node : nodes) {
1222  if (intact_nodes.count(node.get()) || does_redef_cols(node.get())) {
1223  continue;
1224  }
1225  bool intact = true;
1226  for (size_t i = 0; i < node->inputCount(); ++i) {
1227  auto source = node->getInput(i);
1228  if (!dynamic_cast<const RelScan*>(source) && !intact_nodes.count(source)) {
1229  intact = false;
1230  break;
1231  }
1232  }
1233  if (intact) {
1234  intact_nodes.insert(node.get());
1235  }
1236  }
1237 
1238  std::unordered_map<const RelAlgNode*, size_t> orig_node_sizes;
1239  for (auto node : nodes) {
1240  orig_node_sizes.insert(std::make_pair(node.get(), node->size()));
1241  }
1242  // Sweep
1243  std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>
1244  liveout_renumbering;
1245  std::vector<const RelAlgNode*> ready_nodes;
1246  std::tie(liveout_renumbering, ready_nodes) =
1247  sweep_dead_columns(old_liveouts, nodes, intact_nodes, web, orig_node_sizes);
1248  // Propagate
1250  liveout_renumbering, ready_nodes, old_liveouts, intact_nodes, web, orig_node_sizes);
1251 }
1252 
1253 void eliminate_dead_subqueries(std::vector<std::shared_ptr<RexSubQuery>>& subqueries,
1254  RelAlgNode const* root) {
1255  if (!subqueries.empty()) {
1256  auto live_ids = RexSubQueryIdCollector::getLiveRexSubQueryIds(root);
1257  auto sort_live_ids_first = [&live_ids](auto& a, auto& b) {
1258  return live_ids.count(a->getId()) && !live_ids.count(b->getId());
1259  };
1260  std::stable_sort(subqueries.begin(), subqueries.end(), sort_live_ids_first);
1261  size_t n_dead_subqueries;
1262  if (live_ids.count(subqueries.front()->getId())) {
1263  auto first_dead_itr = std::upper_bound(subqueries.cbegin(),
1264  subqueries.cend(),
1265  subqueries.front(),
1266  sort_live_ids_first);
1267  n_dead_subqueries = subqueries.cend() - first_dead_itr;
1268  } else {
1269  n_dead_subqueries = subqueries.size();
1270  }
1271  if (n_dead_subqueries) {
1272  VLOG(1) << "Eliminating " << n_dead_subqueries
1273  << (n_dead_subqueries == 1 ? " subquery." : " subqueries.");
1274  subqueries.resize(subqueries.size() - n_dead_subqueries);
1275  subqueries.shrink_to_fit();
1276  }
1277  }
1278 }
1279 
1280 namespace {
1281 
1283  public:
1284  RexInputSinker(const std::unordered_map<size_t, size_t>& old_to_new_idx,
1285  const RelAlgNode* new_src)
1286  : old_to_new_in_idx_(old_to_new_idx), target_(new_src) {}
1287 
1288  RetType visitInput(const RexInput* input) const override {
1289  CHECK_EQ(target_->inputCount(), size_t(1));
1290  CHECK_EQ(target_->getInput(0), input->getSourceNode());
1291  auto idx_it = old_to_new_in_idx_.find(input->getIndex());
1292  CHECK(idx_it != old_to_new_in_idx_.end());
1293  return boost::make_unique<RexInput>(target_, idx_it->second);
1294  }
1295 
1296  private:
1297  const std::unordered_map<size_t, size_t>& old_to_new_in_idx_;
1299 };
1300 
1302  public:
1303  SubConditionReplacer(const std::unordered_map<size_t, std::unique_ptr<const RexScalar>>&
1304  idx_to_sub_condition)
1305  : idx_to_subcond_(idx_to_sub_condition) {}
1306  RetType visitInput(const RexInput* input) const override {
1307  auto subcond_it = idx_to_subcond_.find(input->getIndex());
1308  if (subcond_it != idx_to_subcond_.end()) {
1309  return RexDeepCopyVisitor::visit(subcond_it->second.get());
1310  }
1311  return RexDeepCopyVisitor::visitInput(input);
1312  }
1313 
1314  private:
1315  const std::unordered_map<size_t, std::unique_ptr<const RexScalar>>& idx_to_subcond_;
1316 };
1317 
1318 } // namespace
1319 
1321  std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1322  auto web = build_du_web(nodes);
1323  auto liveouts = mark_live_columns(nodes);
1324  for (auto node : nodes) {
1325  auto project = std::dynamic_pointer_cast<RelProject>(node);
1326  // TODO(miyu): relax RelScan limitation
1327  if (!project || project->isSimple() ||
1328  !dynamic_cast<const RelScan*>(project->getInput(0))) {
1329  continue;
1330  }
1331  auto usrs_it = web.find(project.get());
1332  CHECK(usrs_it != web.end());
1333  auto& usrs = usrs_it->second;
1334  if (usrs.size() != 1) {
1335  continue;
1336  }
1337  auto join = dynamic_cast<RelJoin*>(const_cast<RelAlgNode*>(*usrs.begin()));
1338  if (!join) {
1339  continue;
1340  }
1341  auto outs_it = liveouts.find(join);
1342  CHECK(outs_it != liveouts.end());
1343  std::unordered_map<size_t, size_t> in_to_out_index;
1344  std::unordered_set<size_t> boolean_expr_indicies;
1345  bool discarded = false;
1346  for (size_t i = 0; i < project->size(); ++i) {
1347  auto oper = dynamic_cast<const RexOperator*>(project->getProjectAt(i));
1348  if (oper && oper->getType().get_type() == kBOOLEAN) {
1349  boolean_expr_indicies.insert(i);
1350  } else {
1351  // TODO(miyu): relax?
1352  if (auto input = dynamic_cast<const RexInput*>(project->getProjectAt(i))) {
1353  in_to_out_index.insert(std::make_pair(input->getIndex(), i));
1354  } else {
1355  discarded = true;
1356  }
1357  }
1358  }
1359  if (discarded || boolean_expr_indicies.empty()) {
1360  continue;
1361  }
1362  const size_t index_base =
1363  join->getInput(0) == project.get() ? 0 : join->getInput(0)->size();
1364  for (auto i : boolean_expr_indicies) {
1365  auto join_idx = index_base + i;
1366  if (outs_it->second.count(join_idx)) {
1367  discarded = true;
1368  break;
1369  }
1370  }
1371  if (discarded) {
1372  continue;
1373  }
1374  RexInputCollector collector(project.get());
1375  std::vector<size_t> unloaded_input_indices;
1376  std::unordered_map<size_t, std::unique_ptr<const RexScalar>> in_idx_to_new_subcond;
1377  // Given all are dead right after join, safe to sink
1378  for (auto i : boolean_expr_indicies) {
1379  auto rex_ins = collector.visit(project->getProjectAt(i));
1380  for (auto& in : rex_ins) {
1381  CHECK_EQ(in.getSourceNode(), project->getInput(0));
1382  if (!in_to_out_index.count(in.getIndex())) {
1383  auto curr_out_index = project->size() + unloaded_input_indices.size();
1384  in_to_out_index.insert(std::make_pair(in.getIndex(), curr_out_index));
1385  unloaded_input_indices.push_back(in.getIndex());
1386  }
1387  RexInputSinker sinker(in_to_out_index, project.get());
1388  in_idx_to_new_subcond.insert(
1389  std::make_pair(i, sinker.visit(project->getProjectAt(i))));
1390  }
1391  }
1392  if (in_idx_to_new_subcond.empty()) {
1393  continue;
1394  }
1395  std::vector<std::unique_ptr<const RexScalar>> new_projections;
1396  for (size_t i = 0; i < project->size(); ++i) {
1397  if (boolean_expr_indicies.count(i)) {
1398  new_projections.push_back(boost::make_unique<RexInput>(project->getInput(0), 0));
1399  } else {
1400  auto rex_input = dynamic_cast<const RexInput*>(project->getProjectAt(i));
1401  CHECK(rex_input != nullptr);
1402  new_projections.push_back(rex_input->deepCopy());
1403  }
1404  }
1405  for (auto i : unloaded_input_indices) {
1406  new_projections.push_back(boost::make_unique<RexInput>(project->getInput(0), i));
1407  }
1408  project->setExpressions(new_projections);
1409 
1410  SubConditionReplacer replacer(in_idx_to_new_subcond);
1411  auto new_condition = replacer.visit(join->getCondition());
1412  join->setCondition(new_condition);
1413  }
1414 }
1415 
1416 namespace {
1417 
1419  public:
1420  RexInputRedirector(const RelAlgNode* old_src, const RelAlgNode* new_src)
1421  : old_src_(old_src), new_src_(new_src) {}
1422 
1423  RetType visitInput(const RexInput* input) const override {
1424  CHECK_EQ(old_src_, input->getSourceNode());
1425  CHECK_NE(old_src_, new_src_);
1426  auto actual_new_src = new_src_;
1427  if (auto join = dynamic_cast<const RelJoin*>(new_src_)) {
1428  actual_new_src = join->getInput(0);
1429  CHECK_EQ(join->inputCount(), size_t(2));
1430  auto src2_input_base = actual_new_src->size();
1431  if (input->getIndex() >= src2_input_base) {
1432  actual_new_src = join->getInput(1);
1433  return boost::make_unique<RexInput>(actual_new_src,
1434  input->getIndex() - src2_input_base);
1435  }
1436  }
1437 
1438  return boost::make_unique<RexInput>(actual_new_src, input->getIndex());
1439  }
1440 
1441  private:
1444 };
1445 
1447  std::shared_ptr<const RelAlgNode> old_def_node,
1448  std::shared_ptr<const RelAlgNode> new_def_node,
1449  std::unordered_map<const RelAlgNode*, std::shared_ptr<RelAlgNode>>& deconst_mapping,
1450  std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
1451  du_web) {
1452  auto usrs_it = du_web.find(old_def_node.get());
1453  RexInputRedirector redirector(new_def_node.get(), old_def_node.get());
1454  CHECK(usrs_it != du_web.end());
1455  for (auto usr : usrs_it->second) {
1456  auto usr_it = deconst_mapping.find(usr);
1457  CHECK(usr_it != deconst_mapping.end());
1458  usr_it->second->replaceInput(old_def_node, new_def_node);
1459  }
1460  auto new_usrs_it = du_web.find(new_def_node.get());
1461  CHECK(new_usrs_it != du_web.end());
1462  new_usrs_it->second.insert(usrs_it->second.begin(), usrs_it->second.end());
1463  usrs_it->second.clear();
1464 }
1465 
1466 } // namespace
1467 
1468 void fold_filters(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1469  std::unordered_map<const RelAlgNode*, std::shared_ptr<RelAlgNode>> deconst_mapping;
1470  for (auto node : nodes) {
1471  deconst_mapping.insert(std::make_pair(node.get(), node));
1472  }
1473 
1474  auto web = build_du_web(nodes);
1475  for (auto node_it = nodes.rbegin(); node_it != nodes.rend(); ++node_it) {
1476  auto& node = *node_it;
1477  if (auto filter = std::dynamic_pointer_cast<RelFilter>(node)) {
1478  CHECK_EQ(filter->inputCount(), size_t(1));
1479  auto src_filter = dynamic_cast<const RelFilter*>(filter->getInput(0));
1480  if (!src_filter) {
1481  continue;
1482  }
1483  auto siblings_it = web.find(src_filter);
1484  if (siblings_it == web.end() || siblings_it->second.size() != size_t(1)) {
1485  continue;
1486  }
1487  auto src_it = deconst_mapping.find(src_filter);
1488  CHECK(src_it != deconst_mapping.end());
1489  auto folded_filter = std::dynamic_pointer_cast<RelFilter>(src_it->second);
1490  CHECK(folded_filter);
1491  // TODO(miyu) : drop filter w/ only expression valued constant TRUE?
1492  if (auto rex_operator = dynamic_cast<const RexOperator*>(filter->getCondition())) {
1493  VLOG(1) << "Node ID=" << filter->getId() << " folded into "
1494  << "ID=" << folded_filter->getId();
1496  auto node_str = folded_filter->toString(RelRexToStringConfig::defaults());
1497  auto [node_substr, post_fix] = ::substring(node_str, g_max_log_length);
1498  VLOG(2) << "Folded Node (ID: " << folded_filter->getId()
1499  << ") contents: " << node_substr << post_fix;
1500  }
1501  std::vector<std::unique_ptr<const RexScalar>> operands;
1502  operands.emplace_back(folded_filter->getAndReleaseCondition());
1503  auto old_condition = dynamic_cast<const RexOperator*>(operands.back().get());
1504  CHECK(old_condition && old_condition->getType().get_type() == kBOOLEAN);
1505  RexInputRedirector redirector(folded_filter.get(), folded_filter->getInput(0));
1506  operands.push_back(redirector.visit(rex_operator));
1507  auto other_condition = dynamic_cast<const RexOperator*>(operands.back().get());
1508  CHECK(other_condition && other_condition->getType().get_type() == kBOOLEAN);
1509  const bool notnull = old_condition->getType().get_notnull() &&
1510  other_condition->getType().get_notnull();
1511  auto new_condition = std::unique_ptr<const RexScalar>(
1512  new RexOperator(kAND, operands, SQLTypeInfo(kBOOLEAN, notnull)));
1513  folded_filter->setCondition(new_condition);
1514  replace_all_usages(filter, folded_filter, deconst_mapping, web);
1515  deconst_mapping.erase(filter.get());
1516  web.erase(filter.get());
1517  web[filter->getInput(0)].erase(filter.get());
1518  node.reset();
1519  }
1520  }
1521  }
1522 
1523  if (!nodes.empty()) {
1524  auto sink = nodes.back();
1525  for (auto node_it = std::next(nodes.rbegin()); node_it != nodes.rend(); ++node_it) {
1526  if (sink) {
1527  break;
1528  }
1529  sink = *node_it;
1530  }
1531  CHECK(sink);
1532  cleanup_dead_nodes(nodes);
1533  }
1534 }
1535 
1536 std::vector<const RexScalar*> find_hoistable_conditions(const RexScalar* condition,
1537  const RelAlgNode* source,
1538  const size_t first_col_idx,
1539  const size_t last_col_idx) {
1540  if (auto rex_op = dynamic_cast<const RexOperator*>(condition)) {
1541  switch (rex_op->getOperator()) {
1542  case kAND: {
1543  std::vector<const RexScalar*> subconditions;
1544  size_t complete_subcond_count = 0;
1545  for (size_t i = 0; i < rex_op->size(); ++i) {
1546  auto conds = find_hoistable_conditions(
1547  rex_op->getOperand(i), source, first_col_idx, last_col_idx);
1548  if (conds.size() == size_t(1)) {
1549  ++complete_subcond_count;
1550  }
1551  subconditions.insert(subconditions.end(), conds.begin(), conds.end());
1552  }
1553  if (complete_subcond_count == rex_op->size()) {
1554  return {rex_op};
1555  } else {
1556  return {subconditions};
1557  }
1558  break;
1559  }
1560  case kEQ: {
1561  const auto lhs_conds = find_hoistable_conditions(
1562  rex_op->getOperand(0), source, first_col_idx, last_col_idx);
1563  const auto rhs_conds = find_hoistable_conditions(
1564  rex_op->getOperand(1), source, first_col_idx, last_col_idx);
1565  const auto lhs_in = lhs_conds.size() == 1
1566  ? dynamic_cast<const RexInput*>(*lhs_conds.begin())
1567  : nullptr;
1568  const auto rhs_in = rhs_conds.size() == 1
1569  ? dynamic_cast<const RexInput*>(*rhs_conds.begin())
1570  : nullptr;
1571  if (lhs_in && rhs_in) {
1572  return {rex_op};
1573  }
1574  return {};
1575  break;
1576  }
1577  default:
1578  break;
1579  }
1580  return {};
1581  }
1582  if (auto rex_in = dynamic_cast<const RexInput*>(condition)) {
1583  if (rex_in->getSourceNode() == source) {
1584  const auto col_idx = rex_in->getIndex();
1585  return {col_idx >= first_col_idx && col_idx <= last_col_idx ? condition : nullptr};
1586  }
1587  return {};
1588  }
1589  return {};
1590 }
1591 
1593  public:
1594  JoinTargetRebaser(const RelJoin* join, const unsigned old_base)
1595  : join_(join)
1596  , old_base_(old_base)
1597  , src1_base_(join->getInput(0)->size())
1598  , target_count_(join->size()) {}
1599  RetType visitInput(const RexInput* input) const override {
1600  auto curr_idx = input->getIndex();
1601  CHECK_GE(curr_idx, old_base_);
1602  CHECK_LT(static_cast<size_t>(curr_idx), target_count_);
1603  curr_idx -= old_base_;
1604  if (curr_idx >= src1_base_) {
1605  return boost::make_unique<RexInput>(join_->getInput(1), curr_idx - src1_base_);
1606  } else {
1607  return boost::make_unique<RexInput>(join_->getInput(0), curr_idx);
1608  }
1609  }
1610 
1611  private:
1612  const RelJoin* join_;
1613  const unsigned old_base_;
1614  const size_t src1_base_;
1615  const size_t target_count_;
1616 };
1617 
1619  public:
1620  SubConditionRemover(const std::vector<const RexScalar*> sub_conds)
1621  : sub_conditions_(sub_conds.begin(), sub_conds.end()) {}
1622  RetType visitOperator(const RexOperator* rex_operator) const override {
1623  if (sub_conditions_.count(rex_operator)) {
1624  return boost::make_unique<RexLiteral>(
1625  true, kBOOLEAN, kBOOLEAN, unsigned(-2147483648), 1, unsigned(-2147483648), 1);
1626  }
1627  return RexDeepCopyVisitor::visitOperator(rex_operator);
1628  }
1629 
1630  private:
1631  std::unordered_set<const RexScalar*> sub_conditions_;
1632 };
1633 
1635  std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1636  std::unordered_set<const RelAlgNode*> visited;
1637  auto web = build_du_web(nodes);
1638  for (auto node : nodes) {
1639  if (visited.count(node.get())) {
1640  continue;
1641  }
1642  visited.insert(node.get());
1643  auto join = dynamic_cast<RelJoin*>(node.get());
1644  if (join && join->getJoinType() == JoinType::INNER) {
1645  // Only allow cross join for now.
1646  if (auto literal = dynamic_cast<const RexLiteral*>(join->getCondition())) {
1647  // Assume Calcite always generates an inner join on constant boolean true for
1648  // cross join.
1649  CHECK(literal->getType() == kBOOLEAN && literal->getVal<bool>());
1650  size_t first_col_idx = 0;
1651  const RelFilter* filter = nullptr;
1652  std::vector<const RelJoin*> join_seq{join};
1653  for (const RelJoin* curr_join = join; !filter;) {
1654  auto usrs_it = web.find(curr_join);
1655  CHECK(usrs_it != web.end());
1656  if (usrs_it->second.size() != size_t(1)) {
1657  break;
1658  }
1659  auto only_usr = *usrs_it->second.begin();
1660  if (auto usr_join = dynamic_cast<const RelJoin*>(only_usr)) {
1661  if (join == usr_join->getInput(1)) {
1662  const auto src1_offset = usr_join->getInput(0)->size();
1663  first_col_idx += src1_offset;
1664  }
1665  join_seq.push_back(usr_join);
1666  curr_join = usr_join;
1667  continue;
1668  }
1669 
1670  filter = dynamic_cast<const RelFilter*>(only_usr);
1671  break;
1672  }
1673  if (!filter) {
1674  visited.insert(join_seq.begin(), join_seq.end());
1675  continue;
1676  }
1677  const auto src_join = dynamic_cast<const RelJoin*>(filter->getInput(0));
1678  CHECK(src_join);
1679  auto modified_filter = const_cast<RelFilter*>(filter);
1680 
1681  if (src_join == join) {
1682  std::unique_ptr<const RexScalar> filter_condition(
1683  modified_filter->getAndReleaseCondition());
1684  std::unique_ptr<const RexScalar> true_condition =
1685  boost::make_unique<RexLiteral>(true,
1686  kBOOLEAN,
1687  kBOOLEAN,
1688  unsigned(-2147483648),
1689  1,
1690  unsigned(-2147483648),
1691  1);
1692  modified_filter->setCondition(true_condition);
1693  join->setCondition(filter_condition);
1694  continue;
1695  }
1696  const auto src1_base = src_join->getInput(0)->size();
1697  auto source =
1698  first_col_idx < src1_base ? src_join->getInput(0) : src_join->getInput(1);
1699  first_col_idx =
1700  first_col_idx < src1_base ? first_col_idx : first_col_idx - src1_base;
1701  auto join_conditions =
1703  source,
1704  first_col_idx,
1705  first_col_idx + join->size() - 1);
1706  if (join_conditions.empty()) {
1707  continue;
1708  }
1709 
1710  JoinTargetRebaser rebaser(join, first_col_idx);
1711  if (join_conditions.size() == 1) {
1712  auto new_join_condition = rebaser.visit(*join_conditions.begin());
1713  join->setCondition(new_join_condition);
1714  } else {
1715  std::vector<std::unique_ptr<const RexScalar>> operands;
1716  bool notnull = true;
1717  for (size_t i = 0; i < join_conditions.size(); ++i) {
1718  operands.emplace_back(rebaser.visit(join_conditions[i]));
1719  auto old_subcond = dynamic_cast<const RexOperator*>(join_conditions[i]);
1720  CHECK(old_subcond && old_subcond->getType().get_type() == kBOOLEAN);
1721  notnull = notnull && old_subcond->getType().get_notnull();
1722  }
1723  auto new_join_condition = std::unique_ptr<const RexScalar>(
1724  new RexOperator(kAND, operands, SQLTypeInfo(kBOOLEAN, notnull)));
1725  join->setCondition(new_join_condition);
1726  }
1727 
1728  SubConditionRemover remover(join_conditions);
1729  auto new_filter_condition = remover.visit(filter->getCondition());
1730  modified_filter->setCondition(new_filter_condition);
1731  }
1732  }
1733  }
1734 }
1735 
1736 void sync_field_names_if_necessary(std::shared_ptr<const RelProject> from_node,
1737  RelAlgNode* to_node) noexcept {
1738  auto from_fields = from_node->getFields();
1739  if (!from_fields.empty()) {
1740  if (auto proj_to = dynamic_cast<RelProject*>(to_node);
1741  proj_to && proj_to->getFields().size() == from_fields.size()) {
1742  proj_to->setFields(std::move(from_fields));
1743  } else if (auto agg_to = dynamic_cast<RelAggregate*>(to_node);
1744  agg_to && agg_to->getFields().size() == from_fields.size()) {
1745  agg_to->setFields(std::move(from_fields));
1746  } else if (auto compound_to = dynamic_cast<RelCompound*>(to_node);
1747  compound_to && compound_to->getFields().size() == from_fields.size()) {
1748  compound_to->setFields(std::move(from_fields));
1749  } else if (auto tf_to = dynamic_cast<RelTableFunction*>(to_node);
1750  tf_to && tf_to->getFields().size() == from_fields.size()) {
1751  tf_to->setFields(std::move(from_fields));
1752  }
1753  }
1754 }
1755 
1756 // For some reason, Calcite generates Sort, Project, Sort sequences where the
1757 // two Sort nodes are identical and the Project is identity. Simplify this
1758 // pattern by re-binding the input of the second sort to the input of the first.
1759 void simplify_sort(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
1760  if (nodes.size() < 3) {
1761  return;
1762  }
1763  for (size_t i = 0; i <= nodes.size() - 3;) {
1764  auto first_sort = std::dynamic_pointer_cast<RelSort>(nodes[i]);
1765  const auto project = std::dynamic_pointer_cast<const RelProject>(nodes[i + 1]);
1766  auto second_sort = std::dynamic_pointer_cast<RelSort>(nodes[i + 2]);
1767  if (first_sort && second_sort && project && project->isIdentity() &&
1768  *first_sort == *second_sort) {
1769  sync_field_names_if_necessary(project, /* an input of the second sort */
1770  const_cast<RelAlgNode*>(first_sort->getInput(0)));
1771  second_sort->replaceInput(second_sort->getAndOwnInput(0),
1772  first_sort->getAndOwnInput(0));
1773  nodes[i].reset();
1774  nodes[i + 1].reset();
1775  i += 3;
1776  } else {
1777  ++i;
1778  }
1779  }
1780 
1781  std::vector<std::shared_ptr<RelAlgNode>> new_nodes;
1782  for (auto node : nodes) {
1783  if (!node) {
1784  continue;
1785  }
1786  new_nodes.push_back(node);
1787  }
1788  nodes.swap(new_nodes);
1789 }
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:301
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
Definition: RelAlgDag.h:1320
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)
Definition: RelAlgDag.h:1902
#define LOG(tag)
Definition: Logger.h:285
SortDirection getSortDir() const
Definition: RelAlgDag.h:549
bool does_redef_cols(const RelAlgNode *node)
const RexScalar * getCondition() const
Definition: RelAlgDag.h:1898
RetType visitOperator(const RexOperator *rex_operator) const override
Definition: RexVisitor.h:154
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:306
size_t getField() const
Definition: RelAlgDag.h:547
RetType visitOperator(const RexOperator *rex_operator) const override
Definition: sqldefs.h:29
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:305
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
Definition: RelAlgDag.h:174
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:265
#define CHECK_NE(x, y)
Definition: Logger.h:302
NullSortedPosition getNullsPosition() const
Definition: RelAlgDag.h:551
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: RelAlgDag.h:877
Definition: sqldefs.h:36
bool isSimple() const
Definition: RelAlgDag.h:1307
size_t g_max_log_length
Definition: Execute.cpp:172
RetType visitInput(const RexInput *input) const override
Definition: RexVisitor.h:142
virtual void replaceInput(std::shared_ptr< const RelAlgNode > old_input, std::shared_ptr< const RelAlgNode > input)
Definition: RelAlgDag.h:908
RetType aggregateResult(const RetType &aggregate, const RetType &next_result) const override
std::unique_ptr< RexInput > deepCopy() const
Definition: RelAlgDag.h:1070
bool any_dead_col_in(const RelAlgNode *node, const std::unordered_set< size_t > &live_outs)
virtual std::string toString(RelRexToStringConfig config=RelRexToStringConfig::defaults()) const =0
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
Definition: RelAlgDag.h:1352
#define CHECK_LT(x, y)
Definition: Logger.h:303
void sync_field_names_if_necessary(std::shared_ptr< const RelProject > from_node, RelAlgNode *to_node) noexcept
static RelRexToStringConfig defaults()
Definition: RelAlgDag.h:78
void setSourceNode(const RelAlgNode *node) const
Definition: RelAlgDag.h:1061
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
Definition: RelAlgDag.h:1056
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)
#define CHECK(condition)
Definition: Logger.h:291
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)
RexSubQueryIdCollector is a visitor class that collects all RexSubQuery::getId() values for all RexSu...
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
Definition: RelAlgDag.h:875
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:140
#define VLOG(n)
Definition: Logger.h:388
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