split_host_device.cc 7.65 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * 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
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16 17 18 19
 * 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.
 */

20 21 22 23 24
/*!
 * \file split_host_device.cc
 * \brief Split device function from host.
 */
#include <tvm/ir.h>
25
#include <tvm/lowered_func.h>
Tianqi Chen committed
26
#include <tvm/channel.h>
27 28
#include <tvm/ir_pass.h>
#include <tvm/ir_mutator.h>
29
#include <tvm/runtime/module.h>
30 31 32
#include <unordered_map>

namespace tvm {
33
namespace ir {
34 35 36 37 38

// use/def analysis, also delete unreferenced lets
class IRUseDefAnalysis : public IRMutator {
 public:
  Stmt Mutate_(const AttrStmt *op, const Stmt& s) final {
39
    if (op->attr_key == attr::thread_extent) {
40
      IterVar iv = Downcast<IterVar>(op->node);
41 42 43 44 45 46 47 48 49 50 51 52 53 54
      CHECK_NE(iv->thread_tag.length(), 0U);
      // thread_extent can appear multiple times
      // use the first appearance as def.
      if (!use_count_.count(iv->var.get())) {
        this->HandleDef(iv->var.get());
        thread_axis_.push_back(iv);
        thread_extent_.push_back(op->value);
      }

      Expr value = op->value;
      if (visit_thread_extent_) {
        value = this->Mutate(value);
      }
      Stmt body = this->Mutate(op->body);
55
      if (value.same_as(op->value) && body.same_as(op->body)) return s;
56 57 58
      return AttrStmt::make(op->node, op->attr_key, value, body);
    } else if (op->attr_key == attr::channel_write_scope ||
               op->attr_key == attr::channel_read_scope) {
59
      Channel ch = Downcast<Channel>(op->node);
Tianqi Chen committed
60 61 62 63
      if (!use_count_.count(ch->handle_var.get())) {
        this->HandleDef(ch->handle_var.get());
      }
      return IRMutator::Mutate_(op, s);
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    } else {
      return IRMutator::Mutate_(op, s);
    }
  }

  Stmt Mutate_(const LetStmt *op, const Stmt& s) final {
    this->HandleDef(op->var.get());
    Stmt body = this->Mutate(op->body);
    // eliminate unreferenced let
    if (use_count_.at(op->var.get()) == 0 &&
        !HasSideEffect(op->value)) {
      return body;
    } else {
      Expr value = this->Mutate(op->value);
      if (body.same_as(op->body) &&
          value.same_as(op->value)) {
        return s;
      } else {
        return LetStmt::make(op->var, value, body);
      }
    }
  }

  Stmt Mutate_(const For *op, const Stmt& s) final {
    this->HandleDef(op->loop_var.get());
    return IRMutator::Mutate_(op, s);
  }

  Stmt Mutate_(const Allocate *op, const Stmt& s) final {
    this->HandleDef(op->buffer_var.get());
    return IRMutator::Mutate_(op, s);
  }

  Stmt Mutate_(const Store *op, const Stmt& s) final {
    this->HandleUse(op->buffer_var);
    return IRMutator::Mutate_(op, s);
  }

  Expr Mutate_(const Let *op, const Expr& e) final {
    this->HandleDef(op->var.get());
    Expr body = this->Mutate(op->body);
    // eliminate unreferenced let
    if (use_count_.at(op->var.get()) == 0 &&
        !HasSideEffect(op->value)) {
      return body;
    } else {
      Expr value = this->Mutate(op->value);
      if (body.same_as(op->body) &&
          value.same_as(op->value)) {
        return e;
      } else {
        return Let::make(op->var, value, body);
      }
    }
  }

  Expr Mutate_(const Variable *op, const Expr& e) final {
    this->HandleUse(e);
    return IRMutator::Mutate_(op, e);
  }

  Expr Mutate_(const Load *op, const Expr& e) final {
    this->HandleUse(op->buffer_var);
    return IRMutator::Mutate_(op, e);
  }

  void HandleDef(const Variable* v) {
131 132 133
    CHECK(!def_count_.count(v))
        << "variable " << v->name_hint
        << " has already been defined, the Stmt is not SSA";
134
    CHECK(!use_count_.count(v))
135 136
        << "variable " << v->name_hint
        << " has been used before definition!";
137
    use_count_[v] = 0;
138
    def_count_[v] = 1;
139 140 141 142
  }

  void HandleUse(const Expr& v) {
    CHECK(v.as<Variable>());
143
    Var var = Downcast<Var>(v);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    auto it = use_count_.find(var.get());
    if (it != use_count_.end()) {
      if (it->second >= 0) {
        ++it->second;
      }
    } else {
      undefined_.push_back(var);
      use_count_[var.get()] = -1;
    }
  }

  // The fields are publically readible to
  // be accessible to the users.
  bool visit_thread_extent_{true};
  Array<Var> undefined_;
  Array<IterVar> thread_axis_;
  Array<Expr> thread_extent_;
  std::unordered_map<const Variable*, int> use_count_;
162
  std::unordered_map<const Variable*, int> def_count_;
163 164 165 166
};

class HostDeviceSplitter : public IRMutator {
 public:
167 168 169 170 171
  Stmt Mutate_(const Allocate* op, const Stmt& s) final {
    handle_data_type_[op->buffer_var.get()] = make_const(op->type, 0);
    return IRMutator::Mutate_(op, s);
  }

172
  Stmt Mutate_(const AttrStmt *op, const Stmt& s) final {
173
    if (op->attr_key == attr::thread_extent ||
174 175
        op->attr_key == attr::pipeline_exec_scope ||
        op->attr_key == attr::device_scope) {
176 177 178 179 180 181
      return SplitDeviceFunc(s);
    }
    return IRMutator::Mutate_(op, s);
  }

  Array<LoweredFunc> Split(LoweredFunc f) {
182
    CHECK_EQ(f->func_type, kMixedFunc);
183 184 185 186
    for (auto kv : f->handle_data_type) {
      handle_data_type_[kv.first.get()] = kv.second;
    }
    name_ = f->name;
187 188
    NodePtr<LoweredFuncNode> n =
        make_node<LoweredFuncNode>(*f.operator->());
189
    n->body = this->Mutate(f->body);
190
    n->func_type = kHostFunc;
191 192 193 194 195 196 197 198 199 200
    Array<LoweredFunc> ret{LoweredFunc(n)};
    for (LoweredFunc x : device_funcs_) {
      ret.push_back(x);
    }
    return ret;
  }

 private:
  Stmt SplitDeviceFunc(Stmt body) {
    std::ostringstream os;
201
    os << name_ << "_kernel" << device_funcs_.size();
202
    NodePtr<LoweredFuncNode> n = make_node<LoweredFuncNode>();
203 204 205 206 207
    // isolate the device function.
    IRUseDefAnalysis m;
    m.visit_thread_extent_ = false;
    n->body = m.Mutate(body);
    n->name = os.str();
208
    n->func_type = kDeviceFunc;
209
    n->thread_axis = m.thread_axis_;
210 211 212 213 214 215 216 217 218 219 220 221 222 223
    // Strictly order the arguments: Var pointers, positional arguments.
    for (Var v : m.undefined_) {
      if (v.type().is_handle()) {
        n->args.push_back(v);
        // mark handle data type.
        auto it = handle_data_type_.find(v.get());
        if (it != handle_data_type_.end()) {
          n->handle_data_type.Set(v, it->second);
        }
      }
    }
    for (Var v : m.undefined_) {
      if (!v.type().is_handle()) {
        n->args.push_back(v);
224 225 226 227
      }
    }
    LoweredFunc f_device(n);
    Array<Expr> call_args;
228
    call_args.push_back(StringImm::make(f_device->name));
229 230 231 232 233 234 235 236
    for (Var arg : n->args) {
      call_args.push_back(arg);
    }
    for (Expr ext : m.thread_extent_) {
      call_args.push_back(ext);
    }
    device_funcs_.emplace_back(f_device);
    return Evaluate::make(Call::make(
237
        Int(32), intrinsic::tvm_call_packed,
238
        call_args, Call::Intrinsic));
239 240 241 242 243 244 245 246 247 248
  }

  // function name
  std::string name_;
  // the device functions
  std::vector<LoweredFunc> device_funcs_;
  std::unordered_map<const Variable*, Expr> handle_data_type_;
};


249
Array<Var> UndefinedVars(const Stmt& stmt, const Array<Var>& args) {
250
  IRUseDefAnalysis m;
251
  for (Var arg : args) {
252 253
    m.use_count_[arg.get()] = 0;
  }
254
  m.Mutate(stmt);
255 256 257 258 259 260 261
  return m.undefined_;
}

Array<LoweredFunc> SplitHostDevice(LoweredFunc func) {
  return HostDeviceSplitter().Split(func);
}

262
}  // namespace ir
263
}  // namespace tvm