RTTI with smart pointers

Hi,

I would like to use std::shared_ptr in my pass. However I’m facing a problem wrt RTTI. If I have a code like:

std::shared_ptr x(new DerivedClass());

std::shared_ptr p = std::dynamic_pointer_cast(x);

It does not compile since the default RTTI infrastructure is not used by LLVM. Also, it’s not clear to me if the ‘classof’ approach works in this case (I did try it with no success).

Is it possible to have a dynamic_cast using std smart pointers in LLVM?

Thanks.

Hi,

I would like to use std::shared_ptr in my pass. However I’m facing a problem wrt RTTI. If I have a code like:

std::shared_ptr x(new DerivedClass());

std::shared_ptr p = std::dynamic_pointer_cast(x);

It does not compile since the default RTTI infrastructure is not used by LLVM. Also, it’s not clear to me if the ‘classof’ approach works in this case (I did try it with no success).

Is it possible to have a dynamic_cast using std smart pointers in LLVM?

I don’t know of an off-the-shelf way to do this but you could look to r300098 for inspiration (it introduced unique_dyn_cast).

vedant

If you don’t expect the cast to fail because you have special knowledge about its derived type, then you should just use std::static_pointer_cast. If you do think it might fail at runtime and the only way to know is to try the dynamic_cast, then you have to use the llvm casting infrastructure because it is basically LLVM’s replacement for dynamic_cast and RTTI. So it’s up to you to add support for classof() etc to the base and derived. Then you can write:

if (llvm::isa(x.get())) {
auto p = std::static_pointer_cast(x);
}

I don’t think we have an llvm::shared_dyn_cast<>, but it might be reasonable to add one that encapsulated the above if-statement so that you could write:

if (auto p = llvm::shared_dyn_cast(x)) {

}