2

Let me give you an example to explain what I would like to do (or at least know if this is something that's possible to do) :

In Clang, let's take some basic ValueDecl. As you can see on the provided link, this ValueDecl can either :

I would like to know if, given a ValueDecl *, I can determine whether it's one of the above listed class, or am I bounded to this ValueDecl * ?

In every class, there is this bool classof() method, but I don't understand the purpose of this method. Could it be a solution to my problem ?

Marc-O
  • 701
  • 1
  • 5
  • 22

1 Answers1

4

classof is indeed part of the solution, it is however not normally meant for direct use.

Instead you should be using the isa<>, cast<> and dyn_cast<> templates. An example from the LLVM Programmer's Manual:

static bool isLoopInvariant(const Value *V, const Loop *L) {
  if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
    return true;

  // Otherwise, it must be an instruction...
  return !L->contains(cast<Instruction>(V)->getParent());
}

The difference between cast<> and dyn_cast<> is that the former asserts if the instance cannot be cast whereas the former merely returns a null pointer.

Note: cast<> and dyn_cast<> do not allow for a null argument, you can use the cast_or_null<> and dyn_cast_or_null<> if the argument may be null.


For further insights into the design of polymorphism without virtual methods, see How is LLVM isa<> implemented, you will note it uses classof behind the scenes.

Community
  • 1
  • 1
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722