private static boolean compareAndGatherOps(ParseContext pctx,
      SharedWorkOptimizerCache optimizerCache,
      Operator<?> op1,
      Operator<?> op2,
      List<Operator<?>> result,
      boolean gather) throws SemanticException {
    if (!compareOperator(pctx, op1, op2)) {
      LOG.debug("Operators not equal: {} and {}", op1, op2);
      return false;
    }

    if (op1 instanceof TableScanOperator) {
      Boolean areMergeable =
          areMergeableExtendedCheck(pctx, optimizerCache, (TableScanOperator) op1, (TableScanOperator) op2);
      if (!areMergeable) {
        LOG.debug("Operators have different DPP parent: {} and {}", op1, op2);
        return false;
      }
    }

    if (gather && op2.getChildOperators().size() > 1) {
      // If the second operator has more than one child, we stop gathering
      gather = false;
    }

    if (gather) {
      result.add(op2);
    }

    List<Operator<? extends OperatorDesc>> op1ParentOperators = op1.getParentOperators();
    List<Operator<? extends OperatorDesc>> op2ParentOperators = op2.getParentOperators();
    if (op1ParentOperators != null && op2ParentOperators != null) {
      if (op1ParentOperators.size() != op2ParentOperators.size()) {
        return false;
      }
      for (int i = 0; i < op1ParentOperators.size(); i++) {
        Operator<?> op1ParentOp = op1ParentOperators.get(i);
        Operator<?> op2ParentOp = op2ParentOperators.get(i);
        boolean mergeable =
            compareAndGatherOps(pctx, optimizerCache, op1ParentOp, op2ParentOp, result, gather);
        if (!mergeable) {
          return false;
        }
      }
    } else if (op1ParentOperators != null || op2ParentOperators != null) {
      return false;
    }

    return true;
  }
Orders TS operators in decreasing order by "weight".
ql/src/java/org/apache/hadoop/hive/ql/optimizer/SharedWorkOptimizer.java