Lunderberg opened a new pull request, #14522:
URL: https://github.com/apache/tvm/pull/14522
Prior to this PR, the `ObjectRef::as<T>()` method could be used for any `T`
that inherits from `tvm::Object`, and would return a `const T*` if the class
could be cast to the specified type, or `nullptr` otherwise. However, if the
caller needed a `ObjectRef`, they would then need to call `GetRef<MyObjRef>` to
convert from a `const T*`.
This PR extends `ObjectRef::as<T>` to operate on a `T` that inherits from
`tvm::ObjectRef` as well. In this case, the return type is `Optional<T>`,
returning either an instance of the specified subclass, or `NullOpt` if the
object was not an instance of the specified subclass. Example usage of this
new conversion, along with how it relates to existing functionality, is shown
below.
```c++
// Unconditionally convert, throwing an exception if the object isn't
// of the specified type. In contexts where the type of the object is
// unknown, this shouldn't be used.
PrimExpr expr = Downcast<PrimExpr>(obj);
// Protect the Downcast from throwing an exception using IsInstance.
// This avoids the error, but performs the type-checking twice. In
// addition, it requires the caller to specify both the ObjectRef
// subclass and the Object subclass, even though these usually have a
// 1:1 correspondence.
if (obj->IsInstance<PrimExprNode>()) {
PrimExpr expr = Downcast<PrimExpr>(obj);
}
// Perform both type-checking and downcasting with the ObjectRef::as()
// method, then use GetRef to convert to an ObjectRef. This avoids
// double-checking the type, but still requires the caller to
if (const PrimExprNode* ptr = obj.as<PrimExprNode>()) {
PrimExpr expr = GetRef<PrimExpr>(ptr);
}
// New method introduced by this PR. The type-checking is only
// performed once, and the Object subclass is inferred from the
// ObjectRef subclass.
if (Optional<PrimExpr> opt = obj.as<PrimExpr>()) {
PrimExpr expr = opt.value();
}
```
This PR is implemented as two commits. The first commit implements the new
functionality, but makes no further changes. The second commit looks for cases
where `object_ref.as<TNode>()` was immediately followed by `GetRef<T>()`,
replacing with either `object_ref.as<T>()` or with `Downcast<T>(object_ref)`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]