inline.cc 2.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

tqchen committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33
/*!
 *  Copyright (c) 2016 by Contributors
 * \file inline.cc
 */
#include <tvm/ir.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>

namespace tvm {
namespace ir {

// inliner to inline a function
// the result may not be SSA,
// ConvertSSA need to be applied after this pass
34
class IRInline final : public IRMutator {
tqchen committed
35 36 37 38
 public:
  IRInline(FunctionRef f, Array<Var> args, Expr body)
      : f_(f), args_(args), body_(body) {}

39 40 41 42 43 44
  Expr Mutate_(const Call* op, const Expr& e) final {
    Expr expr = IRMutator::Mutate_(op, e);
    op = expr.as<Call>();

    if (op->func == f_) {
      CHECK_EQ(op->value_index, 0);
45
      expr = body_;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
      CHECK_EQ(args_.size(), op->args.size());

      bool has_side_effect = false;
      for (size_t i = 0; i < op->args.size(); ++i) {
        if (HasSideEffect(op->args[i])) has_side_effect = true;
      }
      if (has_side_effect) {
        for (size_t i = 0; i < args_.size(); ++i) {
          expr = Let::make(args_[i], op->args[i], expr);
        }
      } else {
        Map<Var, Expr> vmap;
        for (size_t i = 0; i < args_.size(); ++i) {
          vmap.Set(args_[i], op->args[i]);
        }
        expr = Substitute(
            Evaluate::make(expr), vmap).as<Evaluate>()->value;
63
      }
tqchen committed
64
      return expr;
65
    } else {
66
      return expr;
tqchen committed
67 68 69 70 71 72 73 74 75
    }
  }

 private:
  FunctionRef f_;
  Array<Var> args_;
  Expr body_;
};

76 77
Stmt Inline(Stmt stmt,
            FunctionRef f,
tqchen committed
78
            Array<Var> args,
79
            Expr body) {
80 81
  CHECK_EQ(f->num_outputs(), 1)
      << "can only inline output single value operation";
82 83 84
  Stmt ret = IRInline(f, args, body).Mutate(stmt);
  if (ret.same_as(stmt)) return ret;
  return ConvertSSA(ret);
tqchen committed
85 86 87
}
}  // namespace ir
}  // namespace tvm