make_api.cc 9.22 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
/*!
 *  Copyright (c) 2017 by Contributors
 * \file make_api.cc Build API function.
 */
24
#include <tvm/ir_pass.h>
25
#include <tvm/ir.h>
26
#include <tvm/ir_visitor.h>
27
#include <tvm/ir_mutator.h>
28
#include <tvm/buffer.h>
29
#include <tvm/runtime/device_api.h>
30 31 32 33
#include <vector>
#include <utility>
#include <unordered_set>

34 35
#include "ir_util.h"
#include "arg_binder.h"
36 37

namespace tvm {
38
namespace ir {
39 40

inline Stmt MakeAssertEQ(Expr lhs, Expr rhs, std::string msg) {
41
  return AssertStmt::make(lhs == rhs, msg, Evaluate::make(0));
42 43 44 45 46
}

LoweredFunc MakeAPI(Stmt body,
                    std::string name,
                    Array<NodeRef> api_args,
47 48
                    int num_unpacked_args,
                    bool is_restricted) {
49
  const Stmt nop = Evaluate::make(0);
50 51 52
  int num_args = static_cast<int>(api_args.size());
  CHECK_LE(num_unpacked_args, num_args);
  int num_packed_args = num_args - num_unpacked_args;
53 54 55 56 57 58 59
  // Data field definitions
  // The packed fields
  Var v_packed_args("args", Handle());
  Var v_packed_arg_type_ids("arg_type_ids", Handle());
  Var v_num_packed_args("num_args", Int(32));
  // The arguments of the function.
  Array<Var> args;
60 61
  // The device context
  Var device_type("dev_type"), device_id("dev_id");
62 63 64
  // seq_init gives sequence of initialization
  // seq_check gives sequence of later checks after iniit
  std::vector<Stmt> seq_init, seq_check;
65 66
  std::unordered_map<const Variable*, Expr> vmap;
  ArgBinder binder(&vmap);
67 68 69 70
  // ---------------------------
  // local function defintiions
  // load i-th argument as type t
  auto f_arg_value = [&](Type t, int i) {
71 72 73 74 75 76 77
    Array<Expr> call_args{v_packed_args,
                          IntImm::make(Int(32), i),
                          IntImm::make(Int(32), intrinsic::kTVMValueContent)};
    // load 64 bit version
    Type api_type = APIType(t);
    Expr res = Call::make(
        api_type, intrinsic::tvm_struct_get, call_args,
78
        Call::PureIntrinsic);
79 80 81 82 83
    // cast to the target version.
    if (api_type != t) {
      res = Cast::make(t, res);
    }
    return res;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  };
  // get declaration of argument i
  auto f_arg_decl = [&](int i) {
    std::ostringstream os;
    os << "arg" << i;
    const Variable* v = api_args[i].as<Variable>();
    return Var(os.str(), v ? v->type: Handle());
  };
  // ---------------------------
  // start of logics
  // add signiture for packed arguments.
  if (num_packed_args != 0) {
    args.push_back(v_packed_args);
    args.push_back(v_packed_arg_type_ids);
    args.push_back(v_num_packed_args);
    std::ostringstream os;
100 101

    os << name << ": num_args should be " << num_packed_args;
102 103 104
    seq_init.emplace_back(
        MakeAssertEQ(v_num_packed_args, num_packed_args, os.str()));
  }
105 106 107 108

  // Save the input variables and buffers that will be bound later.
  std::vector<std::pair<Var, Var> > var_defs;
  std::vector<std::pair<Buffer, Var> > buf_defs;
109
  for (int i = 0; i < static_cast<int>(api_args.size()); ++i) {
110
    Var v_arg = f_arg_decl(i);
111
    if (i < num_packed_args) {
112
      // Value loads
113 114
      seq_init.emplace_back(LetStmt::make(
          v_arg, f_arg_value(v_arg.type(), i), nop));
115 116 117 118
      // type code checks
      Var tcode(v_arg->name_hint + ".code", Int(32));
      seq_init.emplace_back(LetStmt::make(
          tcode, Load::make(
119 120
              Int(32), v_packed_arg_type_ids, IntImm::make(Int(32), i), const_true(1)),
          nop));
121 122 123
      Type t = v_arg.type();
      if (t.is_handle()) {
        std::ostringstream msg;
124
        msg << name << ": Expect arg[" << i << "] to be pointer";
125 126
        seq_check.emplace_back(
            AssertStmt::make(tcode == kHandle ||
127
                             tcode == kNDArrayContainer ||
128
                             tcode == kArrayHandle ||
129
                             tcode == kNull, msg.str(), nop));
130 131
      } else if (t.is_int() || t.is_uint()) {
        std::ostringstream msg;
132
        msg << name << ": Expect arg[" << i << "] to be int";
133
        seq_check.emplace_back(AssertStmt::make(tcode == kDLInt, msg.str(), nop));
134 135 136
      } else {
        CHECK(t.is_float());
        std::ostringstream msg;
137
        msg << name << ": Expect arg[" << i << "] to be float";
138 139
        seq_check.emplace_back(
            AssertStmt::make(tcode == kDLFloat, msg.str(), nop));
140
      }
141 142 143 144 145
    } else {
      args.push_back(v_arg);
    }
    // add checks for functions.
    if (api_args[i].as<Variable>()) {
146
      var_defs.emplace_back(std::make_pair(Downcast<Var>(api_args[i]), v_arg));
147 148 149 150
    } else {
      // Buffer checks
      CHECK(api_args[i].as<BufferNode>())
          << "api_args can only be Buffer or Var";
151
      buf_defs.emplace_back(std::make_pair(Downcast<Buffer>(api_args[i]), v_arg));
152 153 154
    }
  }

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  // Arg definitions are defined before buffer binding to avoid the use before
  // def errors.
  //
  // For example, for auto broadcasting, checks are required to guarantee that
  // either 0 or the original stride will be correctly used. Checks here have
  // to use the args that may have no let bining yet. Therefore, hoisting let
  // binding for args before buffer declaration is needed.
  for (const auto& arg : var_defs) {
    binder.Bind(arg.first, arg.second, arg.second->name_hint, true);
  }

  for (const auto& buf_arg : buf_defs) {
    binder.BindDLTensor(buf_arg.first, device_type, device_id,
                        buf_arg.second, buf_arg.second->name_hint);
  }

171
  NodePtr<LoweredFuncNode> n = make_node<LoweredFuncNode>();
172 173
  n->name = name;
  n->args = args;
174
  n->handle_data_type = binder.def_handle_dtype();
175
  n->is_packed_func = num_unpacked_args == 0;
176
  n->is_restricted = is_restricted;
Tianqi Chen committed
177 178 179
  body = AttrStmt::make(
      make_zero(Int(32)), attr::compute_scope,
      StringImm::make(name + "_compute_"), body);
180
  // Set device context
181
  if (vmap.count(device_id.get())) {
182
    Expr node = StringImm::make("default");
183 184
    CHECK(vmap.count(device_type.get()));
    seq_check.push_back(AttrStmt::make(
185
        node, attr::device_context_id, device_id, nop));
186
    seq_check.push_back(AttrStmt::make(
187
        node, attr::device_context_type, device_type, nop));
188
    Stmt set_device = IfThenElse::make(
189
        device_type != kDLCPU, Evaluate::make(Call::make(
190 191 192 193
            Int(32), intrinsic::tvm_call_packed,
            {StringImm::make(runtime::symbol::tvm_set_device),
             device_type, device_id}, Call::Intrinsic)));
    body = Block::make(set_device, body);
194
  }
195 196
  n->body = MergeNest(
      {seq_init, binder.init_nest(), seq_check, binder.asserts()}, body);
197
  LoweredFunc f(n);
198
  Array<Var> undefined = UndefinedVars(f->body, f->args);
199 200 201 202 203
  if (undefined.size() != 0) {
    std::ostringstream os;
    for (Var v : undefined) {
      os << " \'" << v->name_hint << "\' ";
    }
204
    os << " does not appear in api_args";
205 206 207 208
    LOG(FATAL) << "Not all Vars are passed in api_args: " << os.str();
  }
  return f;
}
209 210 211 212 213 214

class DeviceTypeBinder: public IRMutator {
 public:
  explicit DeviceTypeBinder(int device_type)
      : device_type_(device_type) {}

215
  Stmt Mutate_(const AttrStmt* op, const Stmt& s) final {
216 217
    if (op->attr_key == attr::device_context_type) {
      if (const Variable* var = op->value.as<Variable>()) {
218
        var_ = var;
219
        Expr value = make_const(op->value.type(), device_type_);
220 221
        Stmt body = IRMutator::Mutate_(op, s);
        var_ = nullptr;
222 223 224 225 226 227 228 229
        std::ostringstream os;
        os << "device_type need to be " << device_type_;
        return AssertStmt::make(op->value == value, os.str(), body);
      }
    }
    return IRMutator::Mutate_(op, s);
  }

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  Stmt Mutate_(const IfThenElse* op, const Stmt& s) final {
    // eager simplify if guard.
    Stmt res = IRMutator::Mutate_(op, s);
    op = res.as<IfThenElse>();
    if (is_zero(op->condition)) {
      if (op->else_case.defined()) return op->else_case;
      return Evaluate::make(0);
    }
    if (is_one(op->condition)) {
      return op->then_case;
    }
    return res;
  }

  Expr Mutate_(const NE* op, const Expr& e) final {
    // eager check NE for device check
    Expr res = IRMutator::Mutate_(op, e);
    op = res.as<NE>();
    if (ir::Equal(op->a, op->b)) {
      return make_const(op->type, false);
    }
    return res;
  }

  Expr Mutate_(const Variable* op, const Expr& e) final {
    if (op == var_) {
      return make_const(op->type, device_type_);
    } else {
      return e;
    }
  }

262
 public:
263
  const Variable* var_{nullptr};
264 265 266 267 268
  int device_type_;
};

LoweredFunc BindDeviceType(LoweredFunc f,
                           int device_type) {
269
  auto n = make_node<LoweredFuncNode>(*f.operator->());
270 271 272 273
  n->body = DeviceTypeBinder(device_type).Mutate(n->body);
  return LoweredFunc(n);
}

274
}  // namespace ir
275
}  // namespace tvm