tvm
base_expr.h
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
24 #ifndef TVM_IR_BASE_EXPR_H_
25 #define TVM_IR_BASE_EXPR_H_
26 
27 #include <tvm/ffi/cast.h>
28 #include <tvm/ffi/dtype.h>
29 #include <tvm/ffi/reflection/registry.h>
30 #include <tvm/ffi/string.h>
31 #include <tvm/ir/source_map.h>
32 
33 #include <cstddef>
34 #include <cstdint>
35 #include <optional>
36 #include <type_traits>
37 
38 namespace tvm {
39 
52 class TypeNode : public ffi::Object {
53  public:
58  mutable Span span;
59 
60  static void RegisterReflection() {
61  namespace refl = tvm::ffi::reflection;
62  // span do not participate in structural equal and hash.
63  refl::ObjectDef<TypeNode>().def_ro("span", &TypeNode::span, refl::DefaultValue(Span()),
64  refl::AttachFieldFlag::SEqHashIgnore());
65  }
66 
67  static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
68 
69  static constexpr const uint32_t _type_child_slots = 14;
70  TVM_FFI_DECLARE_OBJECT_INFO("ir.Type", TypeNode, ffi::Object);
71 };
72 
77 class Type : public ffi::ObjectRef {
78  public:
80  TVM_DLL static Type Missing();
81 
83  TVM_DLL bool IsMissing() const;
84 
86 };
87 
95 class PrimTypeNode final : public TypeNode {
96  public:
100  DLDataType dtype;
101 
102  static void RegisterReflection() {
103  namespace refl = tvm::ffi::reflection;
104  refl::ObjectDef<PrimTypeNode>().def_ro("dtype", &PrimTypeNode::dtype);
105  }
107 };
108 
109 /*
110  * \brief Managed reference to PrimTypeNode.
111  * \sa PrimTypeNode
112  */
113 class PrimType final : public Type {
114  public:
119  TVM_DLL explicit PrimType(DLDataType dtype);
120 
127  TVM_DLL PrimType(DLDataTypeCode code, int bits, int lanes = 1);
128 
130  TVM_DLL static PrimType Int(int bits, int lanes = 1);
132  TVM_DLL static PrimType UInt(int bits, int lanes = 1);
134  TVM_DLL static PrimType Float(int bits, int lanes = 1);
136  TVM_DLL static PrimType BFloat(int bits, int lanes = 1);
138  TVM_DLL static PrimType Bool(int lanes = 1);
140  TVM_DLL static PrimType Void();
147  TVM_DLL static PrimType ScalableVector(DLDataTypeCode code, int bits, int lanes);
148 
150  TVM_FFI_INLINE DLDataTypeCode code() const {
151  return static_cast<DLDataTypeCode>(static_cast<int>(get()->dtype.code));
152  }
153 
155  TVM_FFI_INLINE int32_t bits() const { return get()->dtype.bits; }
156 
161  TVM_FFI_INLINE int32_t lanes() const {
162  int16_t encoded_lanes = static_cast<int16_t>(get()->dtype.lanes);
163  if (TVM_FFI_PREDICT_FALSE(encoded_lanes < 0)) {
164  TVM_FFI_THROW(InternalError)
165  << "Can't fetch the lanes of a scalable vector at a compile time.";
166  }
167  return encoded_lanes;
168  }
169 
174  TVM_FFI_INLINE bool MatchesElementType(DLDataTypeCode code, int bits) const {
175  DLDataType dtype = get()->dtype;
176  return dtype.code == static_cast<uint8_t>(code) && dtype.bits == bits;
177  }
178 
183  template <typename... Codes>
184  TVM_FFI_INLINE bool MatchesCode(Codes... codes) const {
185  uint8_t dtype_code = get()->dtype.code;
186  return ((dtype_code == static_cast<uint8_t>(codes)) || ...);
187  }
188 
190  TVM_FFI_INLINE bool IsScalar() const {
191  int16_t encoded_lanes = static_cast<int16_t>(get()->dtype.lanes);
192  return encoded_lanes == 1;
193  }
194 
196  TVM_FFI_INLINE bool IsVoid() const {
197  DLDataType dtype = get()->dtype;
198  return dtype.code == static_cast<uint8_t>(DLDataTypeCode::kDLOpaqueHandle) && dtype.bits == 0 &&
199  static_cast<int16_t>(dtype.lanes) == 0;
200  }
201 
203  TVM_FFI_INLINE bool IsScalableVector() const {
204  return static_cast<int16_t>(get()->dtype.lanes) < -1;
205  }
206 
208  TVM_FFI_INLINE bool IsFixedLengthVector() const {
209  return static_cast<int16_t>(get()->dtype.lanes) > 1;
210  }
211 
218  TVM_FFI_INLINE size_t StorageBytes() const {
219  DLDataType dtype = get()->dtype;
220  int16_t encoded_lanes = static_cast<int16_t>(dtype.lanes);
221  if (TVM_FFI_PREDICT_FALSE(encoded_lanes < 0)) {
222  TVM_FFI_THROW(InternalError)
223  << "Cannot compute compile-time storage bytes for non-fixed vector type " << dtype;
224  }
225  return static_cast<size_t>(
226  (static_cast<uint64_t>(dtype.bits) * static_cast<uint64_t>(dtype.lanes) + 7) / 8);
227  }
228 
230  TVM_FFI_INLINE PrimType WithCode(DLDataTypeCode code) const {
231  DLDataType dtype = get()->dtype;
232  int16_t encoded_lanes = static_cast<int16_t>(dtype.lanes);
233  if (encoded_lanes < -1) {
234  return ScalableVector(code, dtype.bits, -encoded_lanes);
235  }
236  return PrimType(code, dtype.bits, encoded_lanes);
237  }
238 
240  TVM_FFI_INLINE PrimType WithBits(int bits) const {
241  DLDataType dtype = get()->dtype;
242  int16_t encoded_lanes = static_cast<int16_t>(dtype.lanes);
243  if (encoded_lanes < -1) {
244  return ScalableVector(this->code(), bits, -encoded_lanes);
245  }
246  return PrimType(this->code(), bits, encoded_lanes);
247  }
248 
250  TVM_FFI_INLINE PrimType WithLanes(int lanes) const {
251  return PrimType(this->code(), this->bits(), lanes);
252  }
253 
255  TVM_FFI_INLINE int32_t VScaleFactor() const {
256  int16_t encoded_lanes = static_cast<int16_t>(get()->dtype.lanes);
257  if (encoded_lanes >= -1) {
258  TVM_FFI_THROW(InternalError) << "A fixed length vector doesn't have a vscale factor.";
259  }
260  return -encoded_lanes;
261  }
262 
264 };
265 
266 inline bool operator==(const PrimType& lhs, const PrimType& rhs) {
267  return lhs->dtype == rhs->dtype;
268 }
269 
270 inline bool operator!=(const PrimType& lhs, const PrimType& rhs) { return !(lhs == rhs); }
271 
276 class ExprNode : public ffi::Object {
277  public:
282  mutable Span span;
283 
290  mutable Type ty = Type::Missing();
291 
292  static void RegisterReflection() {
293  namespace refl = tvm::ffi::reflection;
294  // span does not participate in structural equal and hash.
295  refl::ObjectDef<ExprNode>()
296  .def_ro("span", &ExprNode::span, refl::DefaultValue(Span()),
297  refl::AttachFieldFlag::SEqHashIgnore())
298  .def_ro("ty", &ExprNode::ty, refl::DefaultValue(Type::Missing()));
299  }
300 
301  static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
302 
303  static constexpr const uint32_t _type_child_slots = 64;
304  TVM_FFI_DECLARE_OBJECT_INFO("ir.Expr", ExprNode, ffi::Object);
305 };
306 
311 class Expr : public ffi::ObjectRef {
312  public:
313  // Expressions do not implicitly compare by object identity or address. Callers must name
314  // whether they intend object identity, structural equality, or primitive symbolic comparison.
315  bool operator==(const Expr& other) const = delete;
316  bool operator!=(const Expr& other) const = delete;
317  bool operator<(const Expr& other) const = delete;
318 
320 };
321 
322 class Call;
323 
329 template <typename ExpectedType>
330 class TypedExpr : public Expr {
331  public:
333  ExpectedType ty() const {
334  const auto* node = get();
335  TVM_FFI_DCHECK(node != nullptr);
336  const auto* ty_node = node->ExprNode::ty.template as<typename ExpectedType::ContainerType>();
337  TVM_FFI_DCHECK(ty_node != nullptr);
338  return ffi::GetRef<ExpectedType>(ty_node);
339  }
340 
342  static constexpr bool _type_container_is_exact = false;
343 };
344 
354 class PrimExpr : public TypedExpr<PrimType> {
355  public:
357 
363  TVM_DLL PrimExpr(Call call); // NOLINT(*)
364 
369  TVM_DLL PrimExpr(int32_t value); // NOLINT(*)
374  TVM_DLL PrimExpr(float value); // NOLINT(*)
375 
377  static constexpr bool _type_container_is_exact = false;
378 
383  TVM_DLL static PrimExpr ConvertFallbackValue(ffi::String value); // NOLINT(*)
384 };
385 
391 class PrimExprConvertibleNode : public ffi::Object {
392  public:
394  virtual PrimExpr ToPrimExpr() const = 0;
395  TVM_FFI_DECLARE_OBJECT_INFO("ir.PrimExprConvertible", PrimExprConvertibleNode, ffi::Object);
396 };
397 
402 class PrimExprConvertible : public ffi::ObjectRef {
403  public:
406 };
407 
408 namespace ffi {
409 template <>
410 inline constexpr bool use_default_type_traits_v<PrimType> = false;
411 
412 template <>
413 struct TypeTraits<PrimType> : public ObjectRefWithFallbackTraitsBase<PrimType, DLDataType> {
414  TVM_FFI_INLINE static PrimType ConvertFallbackValue(DLDataType dtype) { return PrimType(dtype); }
415 };
416 
417 template <typename ExpectedType>
418 inline constexpr bool use_default_type_traits_v<TypedExpr<ExpectedType>> = false;
419 
420 template <typename ExpectedType>
421 struct TypeTraits<TypedExpr<ExpectedType>>
422  : public ObjectRefTypeTraitsBase<TypedExpr<ExpectedType>> {
423  using Base = ObjectRefTypeTraitsBase<TypedExpr<ExpectedType>>;
424  using Base::CopyFromAnyViewAfterCheck;
425  using Base::CopyToAnyView;
426  using Base::GetMismatchTypeInfo;
427  using Base::MoveFromAnyAfterCheck;
428  using Base::MoveToAny;
429  using Base::TypeSchema;
430  using Base::TypeStr;
431 
432  TVM_FFI_INLINE static bool CheckAnyStrict(const TVMFFIAny* src) {
433  if (src->type_index == TypeIndex::kTVMFFINone) {
435  }
436  if (src->type_index < TypeIndex::kTVMFFIStaticObjectBegin ||
437  !details::IsObjectInstance<ExprNode>(src->type_index)) {
438  return false;
439  }
440  const auto* expr = static_cast<const ExprNode*>(
441  details::ObjectUnsafe::ObjectPtrFromUnowned<Object>(src->v_obj).get());
442  return details::AnyUnsafe::CheckAnyStrict<ExpectedType>(expr->ty);
443  }
444 
445  TVM_FFI_INLINE static std::optional<TypedExpr<ExpectedType>> TryCastFromAnyView(
446  const TVMFFIAny* src) {
447  if (CheckAnyStrict(src)) {
448  if (src->type_index == TypeIndex::kTVMFFINone) {
449  return details::ObjectUnsafe::ObjectRefFromObjectPtr<TypedExpr<ExpectedType>>(nullptr);
450  }
451  return details::ObjectUnsafe::ObjectRefFromObjectPtr<TypedExpr<ExpectedType>>(
452  details::ObjectUnsafe::ObjectPtrFromUnowned<ExprNode>(src->v_obj));
453  }
454  return std::nullopt;
455  }
456 };
457 
458 template <>
459 inline constexpr bool use_default_type_traits_v<PrimExpr> = false;
460 
461 template <typename ObjectRefType, typename ExpectedType, typename... FallbackTypes>
463  : public ObjectRefWithFallbackTraitsBase<ObjectRefType, FallbackTypes...> {
464  using Base = ObjectRefWithFallbackTraitsBase<ObjectRefType, FallbackTypes...>;
465 
466  TVM_FFI_INLINE static bool CheckAnyStrict(const TVMFFIAny* src) {
467  return TypeTraits<TypedExpr<ExpectedType>>::CheckAnyStrict(src);
468  }
469 
470  TVM_FFI_INLINE static std::optional<ObjectRefType> TryCastFromAnyView(const TVMFFIAny* src) {
471  if (TypeTraits<TypedExpr<ExpectedType>>::TryCastFromAnyView(src)) {
472  return details::ObjectUnsafe::ObjectRefFromObjectPtr<ObjectRefType>(
473  details::ObjectUnsafe::ObjectPtrFromUnowned<ExprNode>(src->v_obj));
474  }
475  return Base::template TryFallbackTypes<FallbackTypes...>(src);
476  }
477 };
478 
479 // define automatic conversion from bool, int64_t, double, ffi::String to PrimExpr
480 // These functions are declared early to avoid circular dependency
481 template <>
482 struct TypeTraits<PrimExpr>
483  : public TypedExprWithFallbackTraitsBase<PrimExpr, PrimType, StrictBool, int64_t, double,
484  ffi::String, PrimExprConvertible> {
485  using Base = TypedExprWithFallbackTraitsBase<PrimExpr, PrimType, StrictBool, int64_t, double,
486  ffi::String, PrimExprConvertible>;
487  using Base::CheckAnyStrict;
488  using Base::CopyFromAnyViewAfterCheck;
489  using Base::CopyToAnyView;
490  using Base::GetMismatchTypeInfo;
491  using Base::MoveFromAnyAfterCheck;
492  using Base::MoveToAny;
493  using Base::TryCastFromAnyView;
494  using Base::TypeSchema;
495  using Base::TypeStr;
496 
497  TVM_DLL static PrimExpr ConvertFallbackValue(StrictBool value);
498  TVM_DLL static PrimExpr ConvertFallbackValue(int64_t value);
499  TVM_DLL static PrimExpr ConvertFallbackValue(double value);
500  TVM_FFI_INLINE static PrimExpr ConvertFallbackValue(ffi::String value) {
501  return PrimExpr::ConvertFallbackValue(value);
502  }
503  TVM_FFI_INLINE static PrimExpr ConvertFallbackValue(PrimExprConvertible value) {
504  return value->ToPrimExpr();
505  }
506 };
507 
508 template <>
509 inline constexpr bool use_default_type_traits_v<Expr> = false;
510 
511 // Allow generic Expr arguments to use the primitive-literal conversions
512 // already defined by PrimExpr.
513 template <>
514 struct TypeTraits<Expr> : public ObjectRefWithFallbackTraitsBase<Expr, PrimExpr> {
515  TVM_FFI_INLINE static Expr ConvertFallbackValue(PrimExpr value) { return value; }
516 };
517 } // namespace ffi
518 
519 } // namespace tvm
520 
521 #endif // TVM_IR_BASE_EXPR_H_
Managed reference to CallNode.
Definition: expr.h:348
Base type of all the expressions.
Definition: base_expr.h:276
Type ty
The deduced or annotated type of the expression.
Definition: base_expr.h:290
Span span
Span that points to the original source code. Reserved debug information.
Definition: base_expr.h:282
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition: base_expr.h:301
TVM_FFI_DECLARE_OBJECT_INFO("ir.Expr", ExprNode, ffi::Object)
static constexpr const uint32_t _type_child_slots
Definition: base_expr.h:303
static void RegisterReflection()
Definition: base_expr.h:292
Managed reference to ExprNode.
Definition: base_expr.h:311
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Expr, ffi::ObjectRef, ExprNode)
bool operator==(const Expr &other) const =delete
bool operator!=(const Expr &other) const =delete
bool operator<(const Expr &other) const =delete
Base class for other IR constructs that can be converted to PrimExpr. This is useful for the FFI to c...
Definition: base_expr.h:391
virtual ~PrimExprConvertibleNode()
Definition: base_expr.h:393
virtual PrimExpr ToPrimExpr() const =0
TVM_FFI_DECLARE_OBJECT_INFO("ir.PrimExprConvertible", PrimExprConvertibleNode, ffi::Object)
Managed reference to PrimExprConvertibleNode.
Definition: base_expr.h:402
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(PrimExprConvertible, ffi::ObjectRef, PrimExprConvertibleNode)
Typed reference/view over any Expr whose ExprNode::ty is PrimType.
Definition: base_expr.h:354
static constexpr bool _type_container_is_exact
Definition: base_expr.h:377
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(PrimExpr, TypedExpr< PrimType >, ExprNode)
PrimExpr(float value)
construct from float.
PrimExpr(int32_t value)
construct from integer.
static PrimExpr ConvertFallbackValue(ffi::String value)
construct from string to form a StringImm.
PrimExpr(Call call)
Construct from a call after checking that its result type is PrimType.
Primitive data types used in the low-level IR.
Definition: base_expr.h:95
DLDataType dtype
The raw DLPack dtype represented by this primitive type.
Definition: base_expr.h:100
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.PrimType", PrimTypeNode, TypeNode)
static void RegisterReflection()
Definition: base_expr.h:102
Definition: base_expr.h:113
static PrimType ScalableVector(DLDataTypeCode code, int bits, int lanes)
Construct a scalable vector type.
TVM_FFI_INLINE DLDataTypeCode code() const
Definition: base_expr.h:150
static PrimType Float(int bits, int lanes=1)
Construct a floating-point type with fixed lanes.
static PrimType Void()
Construct the void sentinel type, encoded as handle(0, 0).
TVM_FFI_INLINE bool IsVoid() const
Whether this type is the void sentinel handle(0, 0).
Definition: base_expr.h:196
TVM_FFI_INLINE PrimType WithLanes(int lanes) const
Return the same scalar element type with a fixed lane count.
Definition: base_expr.h:250
static PrimType Int(int bits, int lanes=1)
Construct a signed integer type with fixed lanes.
TVM_FFI_INLINE bool IsScalableVector() const
Whether this type is a scalable vector.
Definition: base_expr.h:203
static PrimType Bool(int lanes=1)
Construct a boolean type with fixed lanes.
TVM_FFI_INLINE int32_t bits() const
Definition: base_expr.h:155
TVM_FFI_INLINE bool IsFixedLengthVector() const
Whether this type is a fixed-length vector.
Definition: base_expr.h:208
TVM_FFI_INLINE bool IsScalar() const
Whether this type is a scalar, excluding fixed and scalable vectors.
Definition: base_expr.h:190
TVM_FFI_INLINE bool MatchesCode(Codes... codes) const
Check whether the dtype code matches any of the provided DLPack codes.
Definition: base_expr.h:184
static PrimType BFloat(int bits, int lanes=1)
Construct a bfloat type with fixed lanes.
TVM_FFI_INLINE bool MatchesElementType(DLDataTypeCode code, int bits) const
Check the scalar element code and bit width.
Definition: base_expr.h:174
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(PrimType, Type, PrimTypeNode)
TVM_FFI_INLINE int32_t VScaleFactor() const
Definition: base_expr.h:255
PrimType(DLDataTypeCode code, int bits, int lanes=1)
Construct from DLPack dtype fields.
TVM_FFI_INLINE int32_t lanes() const
Definition: base_expr.h:161
TVM_FFI_INLINE PrimType WithBits(int bits) const
Return the same type with a different scalar bit width, preserving code and lanes.
Definition: base_expr.h:240
TVM_FFI_INLINE size_t StorageBytes() const
Return the number of bytes needed to store one value of this type.
Definition: base_expr.h:218
static PrimType UInt(int bits, int lanes=1)
Construct an unsigned integer type with fixed lanes.
PrimType(DLDataType dtype)
Construct from a raw DLPack dtype.
TVM_FFI_INLINE PrimType WithCode(DLDataTypeCode code) const
Return the same type with a different dtype code, preserving bits and lanes.
Definition: base_expr.h:230
Definition: source_map.h:111
Type is the base type of all types.
Definition: base_expr.h:52
static constexpr const uint32_t _type_child_slots
Definition: base_expr.h:69
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition: base_expr.h:67
TVM_FFI_DECLARE_OBJECT_INFO("ir.Type", TypeNode, ffi::Object)
static void RegisterReflection()
Definition: base_expr.h:60
Span span
Span that points to the original source code. Reserved debug information.
Definition: base_expr.h:58
Managed reference to TypeNode.
Definition: base_expr.h:77
static Type Missing()
Sentinel for a type that has not been populated yet.
bool IsMissing() const
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Type, ffi::ObjectRef, TypeNode)
Typed reference/view over an expression whose result type is a specific Type subtype.
Definition: base_expr.h:330
static constexpr bool _type_container_is_exact
Definition: base_expr.h:342
ExpectedType ty() const
Definition: base_expr.h:333
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(TypedExpr, Expr, ExprNode)
constexpr bool use_default_type_traits_v< Expr >
Definition: base_expr.h:509
constexpr bool use_default_type_traits_v< PrimExpr >
Definition: base_expr.h:459
constexpr bool use_default_type_traits_v< PrimType >
Definition: base_expr.h:410
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition: analyzer.h:40
bool operator!=(const PrimType &lhs, const PrimType &rhs)
Definition: base_expr.h:270
bool operator==(const PrimType &lhs, const PrimType &rhs)
Definition: base_expr.h:266
A map from source names to source code.
static TVM_FFI_INLINE Expr ConvertFallbackValue(PrimExpr value)
Definition: base_expr.h:515
static TVM_FFI_INLINE PrimExpr ConvertFallbackValue(ffi::String value)
Definition: base_expr.h:500
static PrimExpr ConvertFallbackValue(int64_t value)
static TVM_FFI_INLINE PrimExpr ConvertFallbackValue(PrimExprConvertible value)
Definition: base_expr.h:503
static PrimExpr ConvertFallbackValue(StrictBool value)
static PrimExpr ConvertFallbackValue(double value)
static TVM_FFI_INLINE PrimType ConvertFallbackValue(DLDataType dtype)
Definition: base_expr.h:414
ObjectRefTypeTraitsBase< TypedExpr< ExpectedType > > Base
Definition: base_expr.h:423
static TVM_FFI_INLINE bool CheckAnyStrict(const TVMFFIAny *src)
Definition: base_expr.h:432
static TVM_FFI_INLINE std::optional< TypedExpr< ExpectedType > > TryCastFromAnyView(const TVMFFIAny *src)
Definition: base_expr.h:445
static TVM_FFI_INLINE std::optional< ObjectRefType > TryCastFromAnyView(const TVMFFIAny *src)
Definition: base_expr.h:470
static TVM_FFI_INLINE bool CheckAnyStrict(const TVMFFIAny *src)
Definition: base_expr.h:466
ObjectRefWithFallbackTraitsBase< ObjectRefType, FallbackTypes... > Base
Definition: base_expr.h:464