packed_func.h 26.6 KB
Newer Older
1
/*!
2
 *  Copyright (c) 2017 by Contributors
3
 * \file packed_func.h
4
 * \brief Type-erased function used across TVM API.
5
 */
6 7
#ifndef TVM_RUNTIME_PACKED_FUNC_H_
#define TVM_RUNTIME_PACKED_FUNC_H_
8

9
#include <dmlc/logging.h>
10 11
#include <functional>
#include <tuple>
12 13
#include <vector>
#include <string>
14 15 16
#include <limits>
#include <memory>
#include <type_traits>
17
#include "./c_runtime_api.h"
18
#include "./module.h"
19

20
namespace HalideIR {
21 22 23 24 25 26
// Forward declare type for extensions
// The header works fine without depending on this.
struct Type;
struct Expr;
}

27 28 29 30 31
// Whether use TVM runtime in header only mode.
#ifndef TVM_RUNTIME_HEADER_ONLY
#define TVM_RUNTIME_HEADER_ONLY 0
#endif

32
namespace tvm {
33 34 35 36 37 38
// Forward declare NodeRef and Node for extensions.
// This header works fine without depend on NodeRef
// as long as it is not used.
class Node;
class NodeRef;

39
namespace runtime {
40 41 42 43 44
// forward declarations
class TVMArgs;
class TVMArgValue;
class TVMRetValue;
class TVMArgsSetter;
45 46

/*!
47 48
 * \brief Packed function is a type-erased function.
 *  The arguments are passed by packed format.
49
 *
50 51 52
 *  This is an useful unified interface to call generated functions,
 *  It is the unified function function type of TVM.
 *  It corresponds to TVMFunctionHandle in C runtime API.
53 54 55
 */
class PackedFunc {
 public:
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  /*!
   * \brief The internal std::function
   * \param args The arguments to the function.
   * \param rv The return value.
   *
   * \code
   *   // Example code on how to implemented FType
   *   void MyPackedFunc(TVMArgs args, TVMRetValue* rv) {
   *     // automatically convert arguments to desired type.
   *     int a0 = args[0];
   *     float a1 = args[1];
   *     ...
   *     // automatically assign values to rv
   *     std::string my_return_value = "x";
   *     *rv = my_return_value;
   *   }
   * \endcode
   */
  using FType = std::function<void (TVMArgs args, TVMRetValue* rv)>;
75
  /*! \brief default constructor */
76
  PackedFunc() {}
77 78 79 80
  /*!
   * \brief constructing a packed function from a std::function.
   * \param body the internal container of packed function.
   */
81 82
  explicit PackedFunc(FType body) : body_(body) {}
  /*!
83
   * \brief Call packed function by directly passing in unpacked format.
84 85
   * \param args Arguments to be passed.
   * \tparam Args arguments to be passed.
86 87 88 89 90 91 92 93 94
   *
   * \code
   *   // Example code on how to call packed function
   *   void CallPacked(PackedFunc f) {
   *     // call like normal functions by pass in arguments
   *     // return value is automatically converted back
   *     int rvalue = f(1, 2.0);
   *   }
   * \endcode
95 96
   */
  template<typename... Args>
97
  inline TVMRetValue operator()(Args&& ...args) const;
98 99 100
  /*!
   * \brief Call the function in packed format.
   * \param args The arguments
101
   * \param rv The return value.
102
   */
103
  inline void CallPacked(TVMArgs args, TVMRetValue* rv) const;
104
  /*! \return the internal body function */
105
  inline FType body() const;
106 107 108 109 110 111 112 113
  /*! \return Whether the packed function is nullptr */
  bool operator==(std::nullptr_t null) const {
    return body_ == nullptr;
  }
  /*! \return Whether the packed function is not nullptr */
  bool operator!=(std::nullptr_t null) const {
    return body_ != nullptr;
  }
114 115 116 117 118 119

 private:
  /*! \brief internal container of packed function */
  FType body_;
};

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
/*! \brief Arguments into TVM functions. */
class TVMArgs {
 public:
  const TVMValue* values;
  const int* type_codes;
  int num_args;
  /*!
   * \brief constructor
   * \param values The argument values
   * \param type_codes The argument type codes
   * \param num_args number of arguments.
   */
  TVMArgs(const TVMValue* values,
          const int* type_codes,
          int num_args)
      : values(values),
        type_codes(type_codes),
        num_args(num_args) { }
  /*! \return size of the arguments */
  inline int size() const;
  /*!
   * \brief Get i-th argument
   * \param i the index.
   * \return the ith argument.
   */
  inline TVMArgValue operator[](int i) const;
};

/*!
 * \brief Convert type code to its name
 * \param type_code The type code .
 * \return The name of type code.
 */
inline const char* TypeCode2Str(int type_code);

/*!
 * \brief convert a string to TVM type.
 * \param s The string to be converted.
 * \return The corresponding tvm type.
 */
inline TVMType String2TVMType(std::string s);

162 163 164 165 166 167 168
/*!
 * \brief convert a TVM type to string.
 * \param t The type to be converted.
 * \return The corresponding tvm type in string.
 */
inline std::string TVMType2String(TVMType t);

169 170 171 172 173 174
// macro to check type code.
#define TVM_CHECK_TYPE_CODE(CODE, T)                           \
  CHECK_EQ(CODE, T) << " expected "                            \
  << TypeCode2Str(T) << " but get " << TypeCode2Str(CODE)      \

/*!
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
 * \brief Type traits to mark if a class is tvm extension type.
 *
 * To enable extension type in C++ must be register () ed via marco.
 * TVM_REGISTER_EXT_TYPE(TypeName) after defining this with this traits.
 *
 * Extension class can be passed and returned via PackedFunc in all tvm runtime.
 * Internally extension class is stored as T*.
 *
 * \tparam T the typename
 */
template<typename T>
struct extension_class_info {
  static const int code = 0;
};

/*!
191
 * \brief Runtime function table about extension type.
192
 */
193 194
class ExtTypeVTable {
 public:
195 196 197 198
  /*! \brief function to be called to delete a handle */
  void (*destroy)(void* handle);
  /*! \brief function to be called when clone a handle */
  void* (*clone)(void* handle);
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  /*!
   * \brief Register type
   * \tparam T The type to be register.
   * \return The registered vtable.
   */
  template <typename T>
  static inline ExtTypeVTable* Register_();
  /*!
   * \brief Get a vtable based on type code.
   * \param type_code The type code
   * \return The registered vtable.
   */
  TVM_DLL static ExtTypeVTable* Get(int type_code);

 private:
  // Internal registration function.
  TVM_DLL static ExtTypeVTable* RegisterInternal(int type_code, const ExtTypeVTable& vt);
216 217 218
};

/*!
219 220 221 222 223 224
 * \brief Internal base class to
 *  handle conversion to POD values.
 */
class TVMPODValue_ {
 public:
  operator double() const {
225
    TVM_CHECK_TYPE_CODE(type_code_, kDLFloat);
226 227 228
    return value_.v_float64;
  }
  operator int64_t() const {
229
    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
230 231 232
    return value_.v_int64;
  }
  operator uint64_t() const {
233
    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
234 235 236
    return value_.v_int64;
  }
  operator int() const {
237
    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
238 239 240 241 242
    CHECK_LE(value_.v_int64,
             std::numeric_limits<int>::max());
    return static_cast<int>(value_.v_int64);
  }
  operator bool() const {
243
    TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
244 245 246 247 248 249 250 251 252 253 254 255 256
    return value_.v_int64 != 0;
  }
  operator void*() const {
    if (type_code_ == kNull) return nullptr;
    if (type_code_ == kArrayHandle) return value_.v_handle;
    TVM_CHECK_TYPE_CODE(type_code_, kHandle);
    return value_.v_handle;
  }
  operator TVMArray*() const {
    if (type_code_ == kNull) return nullptr;
    TVM_CHECK_TYPE_CODE(type_code_, kArrayHandle);
    return static_cast<TVMArray*>(value_.v_handle);
  }
257 258 259 260
  operator TVMContext() const {
    TVM_CHECK_TYPE_CODE(type_code_, kTVMContext);
    return value_.v_ctx;
  }
261 262
  template<typename TExtension>
  const TExtension& AsExtension() const {
263 264
    CHECK_LT(type_code_, kExtEnd);
    return static_cast<TExtension*>(value_.v_handle)[0];
265
  }
266 267 268 269 270 271 272 273 274 275 276 277
  int type_code() const {
    return type_code_;
  }
  /*!
   * \brief return handle as specific pointer type.
   * \tparam T the data type.
   * \return The pointer type.
   */
  template<typename T>
  T* ptr() const {
    return static_cast<T*>(value_.v_handle);
  }
278 279 280 281 282 283 284 285

 protected:
  friend class TVMArgsSetter;
  friend class TVMRetValue;
  TVMPODValue_() : type_code_(kNull) {}
  TVMPODValue_(TVMValue value, int type_code)
      : value_(value), type_code_(type_code) {}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  /*! \brief The value */
  TVMValue value_;
  /*! \brief the type code */
  int type_code_;
};

/*!
 * \brief A single argument value to PackedFunc.
 *  Containing both type_code and TVMValue
 *
 *  Provides utilities to do type cast into other types.
 */
class TVMArgValue : public TVMPODValue_ {
 public:
  /*!
   * \brief constructor
   * \param value of the function
   * \param type_code The type code.
   */
  TVMArgValue(TVMValue value, int type_code)
      : TVMPODValue_(value, type_code) {
  }
  // reuse converter from parent
  using TVMPODValue_::operator double;
  using TVMPODValue_::operator int64_t;
  using TVMPODValue_::operator uint64_t;
  using TVMPODValue_::operator int;
  using TVMPODValue_::operator bool;
  using TVMPODValue_::operator void*;
  using TVMPODValue_::operator TVMArray*;
316
  using TVMPODValue_::operator TVMContext;
317 318
  // conversion operator.
  operator std::string() const {
319 320
    if (type_code_ == kTVMType) {
      return TVMType2String(operator TVMType());
321 322 323 324 325 326
    } else if (type_code_ == kBytes) {
      TVMByteArray* arr = static_cast<TVMByteArray*>(value_.v_handle);
      return std::string(arr->data, arr->size);
    } else {
      TVM_CHECK_TYPE_CODE(type_code_, kStr);
      return std::string(value_.v_str);
327
    }
328 329 330 331 332 333 334 335 336
  }
  operator TVMType() const {
    if (type_code_ == kStr) {
      return String2TVMType(operator std::string());
    }
    TVM_CHECK_TYPE_CODE(type_code_, kTVMType);
    return value_.v_type;
  }
  operator PackedFunc() const {
337
    if (type_code_ == kNull) return PackedFunc();
338 339 340
    TVM_CHECK_TYPE_CODE(type_code_, kFuncHandle);
    return *ptr<PackedFunc>();
  }
341 342 343 344
  operator Module() const {
    TVM_CHECK_TYPE_CODE(type_code_, kModuleHandle);
    return *ptr<Module>();
  }
345 346 347
  const TVMValue& value() const {
    return value_;
  }
348 349 350 351
  // Deferred extension handler.
  template<typename TNodeRef>
  inline TNodeRef AsNodeRef() const;
  template<typename T,
352
           typename = typename std::enable_if<
353 354
             std::is_class<T>::value>::type>
  inline operator T() const;
355 356 357 358
  template<typename TNodeRef,
           typename = typename std::enable_if<
             std::is_class<TNodeRef>::value>::type>
  inline bool IsNodeType() const;
359 360
  inline operator HalideIR::Type() const;
  inline operator HalideIR::Expr() const;
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
  // get internal node ptr, if it is node
  inline std::shared_ptr<Node>& node_sptr();
};

/*!
 * \brief Return Value container,
 *  Unlike TVMArgValue, which only holds reference and do not delete
 *  the underlying container during destruction.
 *
 *  TVMRetValue holds value and will manage the underlying containers
 *  when it stores a complicated data type.
 */
class TVMRetValue : public TVMPODValue_ {
 public:
  /*! \brief default constructor */
  TVMRetValue() {}
  /*!
   * \brief move constructor from anoter return value.
   * \param other The other return value.
   */
  TVMRetValue(TVMRetValue&& other)
      : TVMPODValue_(other.value_, other.type_code_) {
383 384
    other.value_.v_handle = nullptr;
    other.type_code_ = kNull;
385 386 387 388 389 390 391 392 393 394 395 396 397
  }
  /*! \brief destructor */
  ~TVMRetValue() {
    this->Clear();
  }
  // reuse converter from parent
  using TVMPODValue_::operator double;
  using TVMPODValue_::operator int64_t;
  using TVMPODValue_::operator uint64_t;
  using TVMPODValue_::operator int;
  using TVMPODValue_::operator bool;
  using TVMPODValue_::operator void*;
  using TVMPODValue_::operator TVMArray*;
398
  using TVMPODValue_::operator TVMContext;
399 400 401 402 403 404
  // Disable copy and assign from another value, but allow move.
  TVMRetValue(const TVMRetValue& other) {
    this->Assign(other);
  }
  // conversion operators
  operator std::string() const {
405 406
    if (type_code_ == kTVMType) {
      return TVMType2String(operator TVMType());
407 408
    } else if (type_code_ == kBytes) {
      return *ptr<std::string>();
409
    }
410 411 412 413 414 415 416 417 418 419 420
    TVM_CHECK_TYPE_CODE(type_code_, kStr);
    return *ptr<std::string>();
  }
  operator TVMType() const {
    if (type_code_ == kStr) {
      return String2TVMType(operator std::string());
    }
    TVM_CHECK_TYPE_CODE(type_code_, kTVMType);
    return value_.v_type;
  }
  operator PackedFunc() const {
421
    if (type_code_ == kNull) return PackedFunc();
422 423 424
    TVM_CHECK_TYPE_CODE(type_code_, kFuncHandle);
    return *ptr<PackedFunc>();
  }
425 426 427 428
  operator Module() const {
    TVM_CHECK_TYPE_CODE(type_code_, kModuleHandle);
    return *ptr<Module>();
  }
429 430 431 432 433 434 435 436 437
  // Assign operators
  TVMRetValue& operator=(TVMRetValue&& other) {
    this->Clear();
    value_ = other.value_;
    type_code_ = other.type_code_;
    other.type_code_ = kNull;
    return *this;
  }
  TVMRetValue& operator=(double value) {
438
    this->SwitchToPOD(kDLFloat);
439 440 441 442 443 444 445 446 447 448 449 450 451 452
    value_.v_float64 = value;
    return *this;
  }
  TVMRetValue& operator=(std::nullptr_t value) {
    this->SwitchToPOD(kNull);
    value_.v_handle = value;
    return *this;
  }
  TVMRetValue& operator=(void* value) {
    this->SwitchToPOD(kHandle);
    value_.v_handle = value;
    return *this;
  }
  TVMRetValue& operator=(int64_t value) {
453
    this->SwitchToPOD(kDLInt);
454 455 456 457
    value_.v_int64 = value;
    return *this;
  }
  TVMRetValue& operator=(int value) {
458
    this->SwitchToPOD(kDLInt);
459 460 461 462 463 464 465 466 467
    value_.v_int64 = value;
    return *this;
  }
  TVMRetValue& operator=(TVMType t) {
    this->SwitchToPOD(kTVMType);
    value_.v_type = t;
    return *this;
  }
  TVMRetValue& operator=(bool value) {
468
    this->SwitchToPOD(kDLInt);
469 470 471 472 473 474 475
    value_.v_int64 = value;
    return *this;
  }
  TVMRetValue& operator=(std::string value) {
    this->SwitchToClass(kStr, value);
    return *this;
  }
476 477 478 479
  TVMRetValue& operator=(TVMByteArray value) {
    this->SwitchToClass(kBytes, std::string(value.data, value.size));
    return *this;
  }
480 481 482 483
  TVMRetValue& operator=(PackedFunc f) {
    this->SwitchToClass(kFuncHandle, f);
    return *this;
  }
484 485 486 487
  TVMRetValue& operator=(Module m) {
    this->SwitchToClass(kModuleHandle, m);
    return *this;
  }
488 489 490 491
  TVMRetValue& operator=(const TVMRetValue& other) {  // NOLINT(*0
    this->Assign(other);
    return *this;
  }
492
  TVMRetValue& operator=(const TVMArgValue& other) {
493 494 495
    this->Assign(other);
    return *this;
  }
496 497 498 499 500 501 502 503
  template<typename T,
           typename = typename std::enable_if<
             extension_class_info<T>::code != 0>::type>
  TVMRetValue& operator=(const T& other) {
    this->SwitchToClass<T>(
        extension_class_info<T>::code, other);
    return *this;
  }
504 505 506 507 508 509 510 511 512 513 514 515
  /*!
   * \brief Move the value back to front-end via C API.
   *  This marks the current container as null.
   *  The managed resources is moved to front-end and
   *  the front end should take charge in managing them.
   *
   * \param ret_value The return value.
   * \param ret_type_code The return type code.
   */
  void MoveToCHost(TVMValue* ret_value,
                   int* ret_type_code) {
    // cannot move str; need specially handle.
516
    CHECK(type_code_ != kStr && type_code_ != kBytes);
517 518 519 520
    *ret_value = value_;
    *ret_type_code = type_code_;
    type_code_ = kNull;
  }
521 522 523 524
  /*! \return The value field, if the data is POD */
  const TVMValue& value() const {
    CHECK(type_code_ != kNodeHandle &&
          type_code_ != kFuncHandle &&
525
          type_code_ != kModuleHandle &&
526 527 528
          type_code_ != kStr) << "TVMRetValue.value can only be used for POD data";
    return value_;
  }
529
  // NodeRef related extenstions: in tvm/packed_func_ext.h
530 531 532 533 534 535
  template<typename T,
           typename = typename std::enable_if<
             std::is_class<T>::value>::type>
  inline operator T() const;
  template<typename TNodeRef>
  inline TNodeRef AsNodeRef() const;
536 537 538
  inline TVMRetValue& operator=(const NodeRef& other);
  inline TVMRetValue& operator=(const std::shared_ptr<Node>& other);
  // type related
539 540
  inline operator HalideIR::Type() const;
  inline TVMRetValue& operator=(const HalideIR::Type& other);
541 542 543 544 545

 private:
  template<typename T>
  void Assign(const T& other) {
    switch (other.type_code()) {
546
      case kStr: {
547 548 549
        SwitchToClass<std::string>(kStr, other);
        break;
      }
550 551 552 553
      case kBytes: {
        SwitchToClass<std::string>(kBytes, other);
        break;
      }
554 555 556 557
      case kFuncHandle: {
        SwitchToClass<PackedFunc>(kFuncHandle, other);
        break;
      }
558
      case kModuleHandle: {
559
        SwitchToClass<Module>(kModuleHandle, other);
560 561
        break;
      }
562 563 564 565 566 567
      case kNodeHandle: {
        SwitchToClass<std::shared_ptr<Node> >(
            kNodeHandle, *other.template ptr<std::shared_ptr<Node> >());
        break;
      }
      default: {
568 569 570 571
        if (other.type_code() < kExtBegin) {
          SwitchToPOD(other.type_code());
          value_ = other.value_;
        } else {
572 573 574
#if TVM_RUNTIME_HEADER_ONLY
          LOG(FATAL) << "Header only mode do not support ext type";
#else
575 576 577 578 579
          this->Clear();
          type_code_ = other.type_code();
          value_.v_handle =
              (*(ExtTypeVTable::Get(other.type_code())->clone))(
                  other.value().v_handle);
580
#endif
581
        }
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        break;
      }
    }
  }
  // get the internal container.
  void SwitchToPOD(int type_code) {
    if (type_code_ != type_code) {
      this->Clear();
      type_code_ = type_code;
    }
  }
  template<typename T>
  void SwitchToClass(int type_code, T v) {
    if (type_code_ != type_code) {
      this->Clear();
      type_code_ = type_code;
      value_.v_handle = new T(v);
    } else {
      *static_cast<T*>(value_.v_handle) = v;
    }
  }
  void Clear() {
    if (type_code_ == kNull) return;
    switch (type_code_) {
      case kStr: delete ptr<std::string>(); break;
      case kFuncHandle: delete ptr<PackedFunc>(); break;
608
      case kModuleHandle: delete ptr<Module>(); break;
609 610
      case kNodeHandle: delete ptr<std::shared_ptr<Node> >(); break;
    }
611
    if (type_code_ > kExtBegin) {
612 613 614
#if TVM_RUNTIME_HEADER_ONLY
          LOG(FATAL) << "Header only mode do not support ext type";
#else
615
      (*(ExtTypeVTable::Get(type_code_)->destroy))(value_.v_handle);
616
#endif
617
    }
618 619 620 621 622 623 624
    type_code_ = kNull;
  }
};

// implementation details
inline const char* TypeCode2Str(int type_code) {
  switch (type_code) {
625 626 627
    case kDLInt: return "int";
    case kDLUInt: return "uint";
    case kDLFloat: return "float";
628
    case kStr: return "str";
629
    case kBytes: return "bytes";
630
    case kHandle: return "handle";
631 632 633 634
    case kNull: return "NULL";
    case kNodeHandle: return "NodeHandle";
    case kArrayHandle: return "ArrayHandle";
    case kTVMType: return "TVMType";
635
    case kTVMContext: return "TVMContext";
636
    case kFuncHandle: return "FunctionHandle";
637
    case kModuleHandle: return "ModuleHandle";
638 639 640 641 642
    default: LOG(FATAL) << "unknown type_code="
                        << static_cast<int>(type_code); return "";
  }
}

nhynes committed
643
#ifndef _LIBCPP_SGX_NO_IOSTREAMS
644
inline std::ostream& operator<<(std::ostream& os, TVMType t) {  // NOLINT(*)
645 646 647
  os << TypeCode2Str(t.code);
  if (t.code == kHandle) return os;
  os << static_cast<int>(t.bits);
648 649 650 651 652
  if (t.lanes != 1) {
    os << 'x' << static_cast<int>(t.lanes);
  }
  return os;
}
nhynes committed
653
#endif
654 655

inline std::string TVMType2String(TVMType t) {
nhynes committed
656
#ifndef _LIBCPP_SGX_NO_IOSTREAMS
657 658 659
  std::ostringstream os;
  os << t;
  return os.str();
nhynes committed
660 661 662 663 664 665 666 667 668 669
#else
  std::string repr = "";
  repr += TypeCode2Str(t.code);
  if (t.code == kHandle) return repr;
  repr += std::to_string(static_cast<int>(t.bits));
  if (t.lanes != 1) {
    repr += "x" + std::to_string(static_cast<int>(t.lanes));
  }
  return repr;
#endif
670 671
}

672 673 674 675 676
inline TVMType String2TVMType(std::string s) {
  TVMType t;
  t.bits = 32; t.lanes = 1;
  const char* scan;
  if (s.substr(0, 3) == "int") {
677
    t.code = kDLInt;  scan = s.c_str() + 3;
678
  } else if (s.substr(0, 4) == "uint") {
679
    t.code = kDLUInt; scan = s.c_str() + 4;
680
  } else if (s.substr(0, 5) == "float") {
681
    t.code = kDLFloat; scan = s.c_str() + 5;
682
  } else if (s.substr(0, 6) == "handle") {
683 684 685 686 687 688 689
    t.code = kHandle;
    t.bits = 64;  // handle uses 64 bit by default.
    scan = s.c_str() + 6;
  } else {
    scan = s.c_str();
    LOG(FATAL) << "unknown type " << s;
  }
nhynes committed
690
  char* xdelim;  // emulate sscanf("%ux%u", bits, lanes)
691 692
  uint8_t bits = static_cast<uint8_t>(strtoul(scan, &xdelim, 10));
  if (bits != 0) t.bits = bits;
nhynes committed
693
  if (*xdelim == 'x') {
694
    t.lanes = static_cast<uint16_t>(strtoul(xdelim + 1, nullptr, 10));
nhynes committed
695
  }
696 697 698 699 700 701 702
  return t;
}

inline TVMArgValue TVMArgs::operator[](int i) const {
  CHECK_LT(i, num_args)
      << "not enough argument passed, "
      << num_args << " passed"
703
      << " but request arg[" << i << "].";
704 705 706 707 708 709 710 711 712
  return TVMArgValue(values[i], type_codes[i]);
}

inline int TVMArgs::size() const {
  return num_args;
}

inline void PackedFunc::CallPacked(TVMArgs args, TVMRetValue* rv) const {
  body_(args, rv);
713 714
}

715 716 717 718
inline PackedFunc::FType PackedFunc::body() const {
  return body_;
}

719 720
// internal namespace
namespace detail {
721 722

template<bool stop, std::size_t I, typename F>
723
struct for_each_dispatcher {
724 725 726 727 728
  template<typename T, typename ...Args>
  static void run(const F& f, T&& value, Args&&... args) {  // NOLINT(*)
    f(I, std::forward<T>(value));
    for_each_dispatcher<sizeof...(Args) == 0, (I+1), F>
        ::run(f, std::forward<Args>(args)...);
729 730 731
  }
};

732 733 734
template<std::size_t I, typename F>
struct for_each_dispatcher<true, I, F>  {
  static void run(const F& f) {}  // NOLINT(*)
735 736 737
};

template<typename F, typename ...Args>
738 739 740
inline void for_each(const F& f, Args&&... args) {  // NOLINT(*)
  for_each_dispatcher<sizeof...(Args) == 0, 0, F>
      ::run(f, std::forward<Args>(args)...);
741
}
742
}  // namespace detail
743

744 745 746
/* \brief argument settter to PackedFunc */
class TVMArgsSetter {
 public:
747 748
  TVMArgsSetter(TVMValue* values, int* type_codes)
      : values_(values), type_codes_(type_codes) {}
749 750
  // setters for POD types
  template<typename T,
751 752
           typename = typename std::enable_if<
             std::is_integral<T>::value>::type>
753 754
  void operator()(size_t i, T value) const {
    values_[i].v_int64 = static_cast<int64_t>(value);
755
    type_codes_[i] = kDLInt;
756 757 758 759 760
  }
  void operator()(size_t i, uint64_t value) const {
    values_[i].v_int64 = static_cast<int64_t>(value);
    CHECK_LE(value,
             static_cast<uint64_t>(std::numeric_limits<int64_t>::max()));
761
    type_codes_[i] = kDLInt;
762 763 764
  }
  void operator()(size_t i, double value) const {
    values_[i].v_float64 = value;
765
    type_codes_[i] = kDLFloat;
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
  }
  void operator()(size_t i, std::nullptr_t value) const {
    values_[i].v_handle = value;
    type_codes_[i] = kNull;
  }
  void operator()(size_t i, const TVMArgValue& value) const {
    values_[i] = value.value_;
    type_codes_[i] = value.type_code_;
  }
  void operator()(size_t i, void* value) const {
    values_[i].v_handle = value;
    type_codes_[i] = kHandle;
  }
  void operator()(size_t i, TVMArray* value) const {
    values_[i].v_handle = value;
    type_codes_[i] = kArrayHandle;
  }
783 784 785 786
  void operator()(size_t i, TVMContext value) const {
    values_[i].v_ctx = value;
    type_codes_[i] = kTVMContext;
  }
787 788 789 790 791 792 793 794 795 796 797
  void operator()(size_t i, TVMType value) const {
    values_[i].v_type = value;
    type_codes_[i] = kTVMType;
  }
  void operator()(size_t i, const char* value) const {
    values_[i].v_str = value;
    type_codes_[i] = kStr;
  }
  // setters for container type
  // They must be reference(instead of const ref)
  // to make sure they are alive in the tuple(instead of getting converted)
798
  void operator()(size_t i, const std::string& value) const {  // NOLINT(*)
799 800 801
    values_[i].v_str = value.c_str();
    type_codes_[i] = kStr;
  }
802 803
  void operator()(size_t i, const TVMByteArray& value) const {  // NOLINT(*)
    values_[i].v_handle = const_cast<TVMByteArray*>(&value);
804 805
    type_codes_[i] = kBytes;
  }
806 807
  void operator()(size_t i, const PackedFunc& value) const {  // NOLINT(*)
    values_[i].v_handle = const_cast<PackedFunc*>(&value);
808 809
    type_codes_[i] = kFuncHandle;
  }
810 811
  void operator()(size_t i, const Module& value) const {  // NOLINT(*)
    values_[i].v_handle = const_cast<Module*>(&value);
812 813
    type_codes_[i] = kModuleHandle;
  }
814
  void operator()(size_t i, const TVMRetValue& value) const {  // NOLINT(*)
815 816 817 818
    if (value.type_code() == kStr) {
      values_[i].v_str = value.ptr<std::string>()->c_str();
      type_codes_[i] = kStr;
    } else {
819
      CHECK_NE(value.type_code(), kBytes) << "not handled.";
820 821 822 823
      values_[i] = value.value_;
      type_codes_[i] = value.type_code();
    }
  }
824 825 826 827 828
  // extension
  template<typename T,
           typename = typename std::enable_if<
             extension_class_info<T>::code != 0>::type>
  inline void operator()(size_t i, const T& value) const;
829
  // NodeRef related extenstions: in tvm/packed_func_ext.h
830
  inline void operator()(size_t i, const NodeRef& other) const;  // NOLINT(*)
831
  inline void operator()(size_t i, const HalideIR::Type& t) const;
832 833 834 835 836 837 838 839

 private:
  /*! \brief The values fields */
  TVMValue* values_;
  /*! \brief The type code fields */
  int* type_codes_;
};

840
template<typename... Args>
841
inline TVMRetValue PackedFunc::operator()(Args&& ...args) const {
842
  const int kNumArgs = sizeof...(Args);
843 844 845
  const int kArraySize = kNumArgs > 0 ? kNumArgs : 1;
  TVMValue values[kArraySize];
  int type_codes[kArraySize];
846
  detail::for_each(TVMArgsSetter(values, type_codes),
847
                   std::forward<Args>(args)...);
848 849 850
  TVMRetValue rv;
  body_(TVMArgs(values, type_codes, kNumArgs), &rv);
  return rv;
851
}
852

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
// extension and node type handling
namespace detail {
template<typename T, typename TSrc, bool is_ext>
struct TVMValueCast {
  static T Apply(const TSrc* self) {
    return self->template AsNodeRef<T>();
  }
};

template<typename T, typename TSrc>
struct TVMValueCast<T, TSrc, true> {
  static T Apply(const TSrc* self) {
    return self->template AsExtension<T>();
  }
};
}  // namespace detail

template<typename T, typename>
inline TVMArgValue::operator T() const {
  return detail::
      TVMValueCast<T, TVMArgValue, extension_class_info<T>::code != 0>
      ::Apply(this);
}

template<typename T, typename>
inline TVMRetValue::operator T() const {
  return detail::
      TVMValueCast<T, TVMRetValue, extension_class_info<T>::code != 0>
      ::Apply(this);
}

884 885 886 887 888 889 890 891
template<typename T, typename>
inline void TVMArgsSetter::operator()(size_t i, const T& value) const {
  static_assert(extension_class_info<T>::code != 0,
                "Need to have extesion code");
  type_codes_[i] = extension_class_info<T>::code;
  values_[i].v_handle = const_cast<T*>(&value);
}

892 893 894 895 896 897 898 899 900 901 902
// extension type handling
template<typename T>
struct ExtTypeInfo {
  static void destroy(void* handle) {
    delete static_cast<T*>(handle);
  }
  static void* clone(void* handle) {
    return new T(*static_cast<T*>(handle));
  }
};

903 904 905 906 907 908 909 910 911
template<typename T>
inline ExtTypeVTable* ExtTypeVTable::Register_() {
  const int code = extension_class_info<T>::code;
  static_assert(code != 0,
                "require extension_class_info traits to be declared with non-zero code");
  ExtTypeVTable vt;
  vt.clone = ExtTypeInfo<T>::clone;
  vt.destroy = ExtTypeInfo<T>::destroy;
  return ExtTypeVTable::RegisterInternal(code, vt);
912
}
913 914 915 916 917 918 919 920 921 922 923 924 925 926

// Implement Module::GetFunction
// Put implementation in this file so we have seen the PackedFunc
inline PackedFunc Module::GetFunction(const std::string& name, bool query_imports) {
  PackedFunc pf = node_->GetFunction(name, node_);
  if (pf != nullptr) return pf;
  if (query_imports) {
    for (const Module& m : node_->imports_) {
      pf = m.node_->GetFunction(name, m.node_);
      if (pf != nullptr) return pf;
    }
  }
  return pf;
}
927 928
}  // namespace runtime
}  // namespace tvm
929
#endif  // TVM_RUNTIME_PACKED_FUNC_H_