|
| 1 | +/*! |
| 2 | + * Copyright (c) 2019 by Contributors |
| 3 | + * |
| 4 | + * \file eliminate_common_subexpr.cc |
| 5 | + * \brief Combine common subexpressions. |
| 6 | + * |
| 7 | + * This is an optimization pass that eliminates common subexpressions. During the pass, it tries |
| 8 | + * to replace an expression with a previously appeared expression with the same input and |
| 9 | + * attributes. The fskip callback argument allows us to skip specific expressions. |
| 10 | + */ |
| 11 | +#include <tvm/relay/pass.h> |
| 12 | +#include <tvm/relay/expr_functor.h> |
| 13 | +#include <unordered_map> |
| 14 | +#include "./pattern_util.h" |
| 15 | + |
| 16 | +namespace tvm { |
| 17 | +namespace relay { |
| 18 | + |
| 19 | +class CommonSubexprEliminator : public ExprMutator { |
| 20 | + public: |
| 21 | + explicit CommonSubexprEliminator(runtime::TypedPackedFunc<bool(Expr)> fskip): fskip_(fskip) {} |
| 22 | + |
| 23 | + Expr VisitExpr_(const CallNode* call) final { |
| 24 | + static auto op_stateful = Op::GetAttr<TOpIsStateful>("TOpIsStateful"); |
| 25 | + Expr new_expr = ExprMutator::VisitExpr_(call); |
| 26 | + const CallNode* new_call = new_expr.as<CallNode>(); |
| 27 | + CHECK(new_call); |
| 28 | + const OpNode* op = new_call->op.as<OpNode>(); |
| 29 | + AttrsEqual attrs_equal; |
| 30 | + |
| 31 | + if (new_call->args.size() == 0 || op == nullptr || op_stateful.get(GetRef<Op>(op), false)) { |
| 32 | + return new_expr; |
| 33 | + } |
| 34 | + if (fskip_ != nullptr && fskip_(new_expr)) { |
| 35 | + return new_expr; |
| 36 | + } |
| 37 | + |
| 38 | + auto it = expr_map_.find(new_call->args[0]); |
| 39 | + if (it != expr_map_.end()) { |
| 40 | + for (const CallNode* candidate : it->second) { |
| 41 | + bool is_equivalent = true; |
| 42 | + if (!new_call->op.same_as(candidate->op)) continue; |
| 43 | + for (size_t i = 0; i < new_call->args.size(); i++) { |
| 44 | + if (!new_call->args[i].same_as(candidate->args[i]) && |
| 45 | + !IsEqualScalar(new_call->args[i], candidate->args[i]) && |
| 46 | + !attrs_equal(new_call->attrs, candidate->attrs)) { |
| 47 | + is_equivalent = false; |
| 48 | + break; |
| 49 | + } |
| 50 | + } |
| 51 | + if (!is_equivalent) continue; |
| 52 | + return GetRef<Call>(candidate); |
| 53 | + } |
| 54 | + } |
| 55 | + expr_map_[new_call->args[0]].push_back(new_call); |
| 56 | + return new_expr; |
| 57 | + } |
| 58 | + |
| 59 | + std::unordered_map<Expr, std::vector<const CallNode*>, NodeHash, NodeEqual> expr_map_; |
| 60 | + runtime::TypedPackedFunc<bool(Expr)> fskip_; |
| 61 | +}; |
| 62 | + |
| 63 | +Expr EliminateCommonSubexpr(const Expr& expr, PackedFunc callback) { |
| 64 | + return CommonSubexprEliminator(callback)(expr); |
| 65 | +} |
| 66 | + |
| 67 | +TVM_REGISTER_API("relay._ir_pass.eliminate_common_subexpr") |
| 68 | +.set_body_typed<Expr(Expr, PackedFunc)>(EliminateCommonSubexpr); |
| 69 | + |
| 70 | +} // namespace relay |
| 71 | +} // namespace tvm |
0 commit comments