tvm
attrs.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  */
28 #ifndef TVM_IR_ATTRS_H_
29 #define TVM_IR_ATTRS_H_
30 
31 #include <tvm/ffi/container/map.h>
32 #include <tvm/ffi/extra/structural_equal.h>
33 #include <tvm/ffi/extra/structural_hash.h>
34 #include <tvm/ffi/function.h>
35 #include <tvm/ffi/reflection/accessor.h>
36 #include <tvm/ffi/reflection/registry.h>
37 #include <tvm/ir/expr.h>
38 
39 #include <functional>
40 #include <string>
41 #include <type_traits>
42 #include <unordered_map>
43 #include <utility>
44 #include <vector>
45 
46 namespace tvm {
47 
53 template <typename TObjectRef>
54 inline TObjectRef NullValue() {
55  static_assert(TObjectRef::_type_is_nullable, "Can only get NullValue for nullable types");
56  return TObjectRef(ObjectPtr<typename TObjectRef::ContainerType>(nullptr));
57 }
58 
59 template <>
61  return DataType(DataType::kHandle, 0, 0);
62 }
63 
67 class AttrFieldInfoNode : public Object {
68  public:
70  ffi::String name;
72  ffi::String type_info;
74  ffi::String description;
75 
76  static void RegisterReflection() {
77  namespace rfl = ffi::reflection;
78  rfl::ObjectDef<AttrFieldInfoNode>()
79  .def_ro("name", &AttrFieldInfoNode::name)
80  .def_ro("type_info", &AttrFieldInfoNode::type_info)
81  .def_ro("description", &AttrFieldInfoNode::description);
82  }
83 
84  static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
85 
87 };
88 
90 class AttrFieldInfo : public ObjectRef {
91  public:
93 };
94 
101 class BaseAttrsNode : public Object {
102  public:
104  virtual ~BaseAttrsNode() {}
110  template <typename... Args>
111  inline void InitBySeq(Args&&... args);
119  TVM_DLL virtual void InitByPackedArgs(const ffi::PackedArgs& kwargs,
120  bool allow_unknown = false) = 0;
121 
122  static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
124 };
125 
130 class Attrs : public ObjectRef {
131  public:
133 };
134 
141 class DictAttrsNode : public BaseAttrsNode {
142  public:
144  ffi::Map<ffi::String, ffi::Any> dict;
145 
146  static void RegisterReflection() {
147  namespace rfl = ffi::reflection;
148  rfl::ObjectDef<DictAttrsNode>().def_ro("__dict__", &DictAttrsNode::dict);
149  }
150 
151  void InitByPackedArgs(const ffi::PackedArgs& args, bool allow_unknown) final;
152 
153  // type info
155 };
156 
161 class DictAttrs : public Attrs {
162  public:
166  explicit DictAttrs(ffi::UnsafeInit tag) : Attrs(tag) {}
171  TVM_DLL explicit DictAttrs(ffi::Map<ffi::String, Any> dict = {});
172 
173  // Utils for accessing attributes
174  // This needs to be on DictAttrs, not DictAttrsNode because we return the default
175  // value if DictAttrsNode is not defined.
195  template <typename TObjectRef>
196  ffi::Optional<TObjectRef> GetAttr(
197  const std::string& attr_key,
198  ffi::Optional<TObjectRef> default_value = ffi::Optional<TObjectRef>(std::nullopt)) const {
199  if (!defined()) return default_value;
200  const DictAttrsNode* node = this->as<DictAttrsNode>();
201  auto it = node->dict.find(attr_key);
202  if (it != node->dict.end()) {
203  return (*it).second.cast<TObjectRef>();
204  } else {
205  return default_value;
206  }
207  }
208  // variant that uses TObjectRef to enable implicit conversion to default value.
209  template <typename TObjectRef>
210  ffi::Optional<TObjectRef> GetAttr(const std::string& attr_key, TObjectRef default_value) const {
211  return GetAttr<TObjectRef>(attr_key, ffi::Optional<TObjectRef>(default_value));
212  }
232  bool HasNonzeroAttr(const std::string& attr_key) const {
233  return GetAttr<Integer>(attr_key, 0).value_or(0).IntValue() != 0;
234  }
235 
237  DictAttrsNode);
239 };
240 
251 DictAttrs WithAttrs(DictAttrs attrs, ffi::Map<ffi::String, Any> new_attrs);
252 
264 DictAttrs WithAttr(DictAttrs attrs, ffi::String key, Any value);
265 
266 inline DictAttrs WithAttr(DictAttrs attrs, const std::string& key, Any value) {
267  return WithAttr(std::move(attrs), ffi::String(key), std::move(value));
268 }
269 
279 DictAttrs WithoutAttr(DictAttrs attrs, const std::string& key);
280 
308 template <typename TFunc>
309 inline TFunc WithAttr(TFunc input, const std::string& attr_key, Any attr_value) {
310  using TNode = typename TFunc::ContainerType;
311  static_assert(TNode::_type_final, "Can only operate on the leaf nodes");
312  TNode* node = input.CopyOnWrite();
313  node->attrs = WithAttr(std::move(node->attrs), attr_key, attr_value);
314  return input;
315 }
316 
327 template <typename TFunc>
328 inline TFunc WithAttrs(TFunc input, ffi::Map<ffi::String, Any> attrs) {
329  using TNode = typename TFunc::ContainerType;
330  static_assert(TNode::_type_final, "Can only operate on the leaf nodes");
331  TNode* node = input.CopyOnWrite();
332 
333  node->attrs = WithAttrs(std::move(node->attrs), attrs);
334 
335  return input;
336 }
337 
364 template <typename TFunc>
365 inline TFunc WithoutAttr(TFunc input, const std::string& attr_key) {
366  using TNode = typename TFunc::ContainerType;
367  static_assert(TNode::_type_final, "Can only operate on the leaf nodes");
368 
369  TNode* node = input.CopyOnWrite();
370  node->attrs = WithoutAttr(std::move(node->attrs), attr_key);
371 
372  return input;
373 }
374 
383 template <typename DerivedType>
385  public:
386  void InitByPackedArgs(const ffi::PackedArgs& args, bool allow_unknown) final {
387  TVM_FFI_THROW(InternalError) << "`" << DerivedType::_type_key
388  << "` uses new reflection mechanism for init";
389  }
390 
391  private:
392  DerivedType* self() const {
393  return const_cast<DerivedType*>(static_cast<const DerivedType*>(this));
394  }
395 };
396 
402 template <typename TAttrs>
403 inline TAttrs AttrsWithDefaultValues() {
404  static_assert(std::is_base_of_v<Attrs, TAttrs>, "Can only take attr nodes");
405  using ContainerType = typename TAttrs::ContainerType;
406  if constexpr (std::is_base_of_v<AttrsNodeReflAdapter<ContainerType>, ContainerType>) {
407  static auto finit_object = ffi::Function::GetGlobalRequired("ffi.MakeObjectFromPackedArgs");
408  AnyView packed_args[1];
409  packed_args[0] = ContainerType::RuntimeTypeIndex();
410  ffi::Any rv;
411  finit_object.CallPacked(ffi::PackedArgs(packed_args, 1), &rv);
412  return rv.cast<TAttrs>();
413  } else {
414  auto n = ffi::make_object<ContainerType>();
415  n->InitByPackedArgs(ffi::PackedArgs(nullptr, 0), false);
416  return TAttrs(n);
417  }
418 }
419 
420 } // namespace tvm
421 #endif // TVM_IR_ATTRS_H_
Information about attribute fields in string representations.
Definition: attrs.h:67
ffi::String name
name of the field
Definition: attrs.h:70
ffi::String type_info
type docstring information in str.
Definition: attrs.h:72
ffi::String description
detailed description of the type
Definition: attrs.h:74
static void RegisterReflection()
Definition: attrs.h:76
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.AttrFieldInfo", AttrFieldInfoNode, Object)
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition: attrs.h:84
AttrFieldInfo.
Definition: attrs.h:90
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(AttrFieldInfo, ObjectRef, AttrFieldInfoNode)
Adapter for AttrsNode with the new reflection API.
Definition: attrs.h:384
void InitByPackedArgs(const ffi::PackedArgs &args, bool allow_unknown) final
Initialize the attributes by arguments.
Definition: attrs.h:386
Managed reference to BaseAttrsNode.
Definition: attrs.h:130
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE(Attrs, ObjectRef, BaseAttrsNode)
Base class of all attribute class.
Definition: attrs.h:101
virtual ~BaseAttrsNode()
virtual destructor
Definition: attrs.h:104
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition: attrs.h:122
void InitBySeq(Args &&... args)
Initialize the attributes by sequence of arguments.
virtual void InitByPackedArgs(const ffi::PackedArgs &kwargs, bool allow_unknown=false)=0
Initialize the attributes by arguments.
TVM_FFI_DECLARE_OBJECT_INFO("ir.Attrs", BaseAttrsNode, Object)
Specialized attribute type that is backed by a map. The DictAttrsNode implements the Attrs behavior,...
Definition: attrs.h:141
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.DictAttrs", DictAttrsNode, BaseAttrsNode)
static void RegisterReflection()
Definition: attrs.h:146
void InitByPackedArgs(const ffi::PackedArgs &args, bool allow_unknown) final
Initialize the attributes by arguments.
ffi::Map< ffi::String, ffi::Any > dict
internal attrs map
Definition: attrs.h:144
Managed reference to DictAttrsNode.
Definition: attrs.h:161
bool HasNonzeroAttr(const std::string &attr_key) const
Check whether the function has an non-zero integer attr.
Definition: attrs.h:232
DictAttrs(ffi::Map< ffi::String, Any > dict={})
Consruct a Attrs backed by DictAttrsNode.
ffi::Optional< TObjectRef > GetAttr(const std::string &attr_key, ffi::Optional< TObjectRef > default_value=ffi::Optional< TObjectRef >(std::nullopt)) const
Get a function attribute.
Definition: attrs.h:196
TVM_DEFINE_OBJECT_REF_COW_METHOD(DictAttrsNode)
DictAttrs(ffi::UnsafeInit tag)
constructor with UnsafeInit
Definition: attrs.h:166
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NULLABLE_WITHOUT_DEFAULT_CONSTRUCTOR(DictAttrs, Attrs, DictAttrsNode)
ffi::Optional< TObjectRef > GetAttr(const std::string &attr_key, TObjectRef default_value) const
Definition: attrs.h:210
Runtime primitive data type.
Definition: data_type.h:47
@ kHandle
Definition: data_type.h:61
Base expr nodes in TVM.
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition: analyzer.h:37
DictAttrs WithoutAttr(DictAttrs attrs, const std::string &key)
Copy the DictAttrs, but without a specific attribute.
DataType NullValue< DataType >()
Definition: attrs.h:60
TAttrs AttrsWithDefaultValues()
Create an Attr object with all default values.
Definition: attrs.h:403
runtime::DataType DataType
Definition: data_type.h:462
DictAttrs WithAttrs(DictAttrs attrs, ffi::Map< ffi::String, Any > new_attrs)
Copy the DictAttrs, but overrides attributes with the entries from attrs.
TObjectRef NullValue()
Create a NodeRef type that represents null.
Definition: attrs.h:54
DictAttrs WithAttr(DictAttrs attrs, ffi::String key, Any value)
Copy the DictAttrs, but overrides a single attribute.