Skip to content

Cpp 07 casting

Mugundan edited this page Nov 27, 2026 · 1 revision

LLVM-Style RTTI: isa, cast, dyn_cast

Relevant source files

The following files were used as context for generating this wiki page:

In a pass you constantly hold a Value * or Instruction * and need to ask "is this actually a load?". Standard C++ answers with dynamic_cast, but LLVM is built with C++ RTTI turned off. Instead, every class in a hierarchy stores a small kind number, and three templates use it: isa<>, cast<> and dyn_cast<>. You will write these more than almost anything else.

Purpose and Scope

This page covers the three casting operators and their null-tolerant variants, how classof makes them work, how to add LLVM-style RTTI to your own classes, and how IR classes do it. Class hierarchies in general are on Classes and RAII.

The Badge Analogy

Office LLVM-style RTTI
Everyone wears a badge with their job printed on it Each object stores a kind (ValueID)
"Are you a nurse?" — look at the badge isa<Nurse>(P)
"You're a nurse, take this patient" — wrong if not cast<Nurse>(P) (asserts)
"If you're a nurse, take this patient; otherwise no one" dyn_cast<Nurse>(P) (returns null)

The Three Operators

Call Returns If the type is wrong Use when
isa<T>(V) bool false You only need to test
cast<T>(V) T * Assertion failure in debug builds You know it's a T
dyn_cast<T>(V) T * or nullptr nullptr It might be a T
isa_and_nonnull<T>(V) bool false, also false if V is null V may be null
dyn_cast_if_present<T>(V) T * or nullptr nullptr, also if V is null V may be null

isa, cast and dyn_cast themselves must not be given a null pointer.

// illustrative: the everyday pattern in a pass
for (Instruction &I : instructions(F)) {
  if (auto *LI = dyn_cast<LoadInst>(&I)) {      // "if it is a load..."
    Value *Ptr = LI->getPointerOperand();
    ...
  } else if (isa<StoreInst>(I)) {
    ...
  }
}

Sources: llvm/include/llvm/Support/Casting.h:547, llvm/include/llvm/Support/Casting.h:559-577, llvm/include/llvm/Support/Casting.h:643-655

How It Works: classof

isa<T>(V) simply calls the static function T::classof(V). Each class answers by looking at the kind stored in the object.

flowchart LR
    C["isa&lt;AllocaInst&gt;(V)"] --> CO["AllocaInst::classof(V)"]
    CO --> Q1{"isa&lt;Instruction&gt;(V)?"}
    Q1 -->|"no"| F["false"]
    Q1 -->|"yes"| Q2{"getOpcode() == Alloca?"}
    Q2 -->|"yes"| T["true"]
    Q2 -->|"no"| F
Loading

Here is the real code from AllocaInst:

  // Methods for support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const Instruction *I) {
    return (I->getOpcode() == Instruction::Alloca);
  }
  static bool classof(const Value *V) {
    return isa<Instruction>(V) && classof(cast<Instruction>(V));
  }

The kind lives in Value: an enum ValueTy lists every value kind, and getValueID() returns it. Checking a kind is one load and a compare, much cheaper than dynamic_cast, and it needs no vtable.

Sources: llvm/include/llvm/IR/Instructions.h:165-171, llvm/include/llvm/IR/Value.h:524, llvm/include/llvm/IR/Value.h:543

Adding It to Your Own Classes

The recipe from How to set up LLVM-style RTTI:

  1. Put an enum of kinds in the base class, one entry per concrete class.
  2. Store the kind in the base; the constructor takes it.
  3. Give each derived class static bool classof(const Base *) that checks the kind.
// example: casting
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

class Shape {
public:
  enum ShapeKind { SK_Circle, SK_Square };
  ShapeKind getKind() const { return Kind; }
protected:
  explicit Shape(ShapeKind K) : Kind(K) {}
private:
  const ShapeKind Kind;
};

class Circle : public Shape {
public:
  explicit Circle(int R) : Shape(SK_Circle), Radius(R) {}
  int Radius;
  static bool classof(const Shape *S) { return S->getKind() == SK_Circle; }
};

class Square : public Shape {
public:
  explicit Square(int S) : Shape(SK_Square), Side(S) {}
  int Side;
  static bool classof(const Shape *S) { return S->getKind() == SK_Square; }
};

void describe(const Shape *S) {
  if (const auto *C = dyn_cast<Circle>(S))
    outs() << "circle radius " << C->Radius << "\n";
  else
    outs() << "square side " << cast<Square>(S)->Side << "\n";
}

int main() {
  Circle C(3);
  Square Q(4);
  const Shape *All[] = {&C, &Q};
  for (const Shape *S : All)
    describe(S);
  outs() << "isa circle: " << isa<Circle>(All[0]) << " " << isa<Circle>(All[1]) << "\n";
  const Shape *None = nullptr;
  outs() << "nonnull: " << isa_and_nonnull<Circle>(None) << "\n";
}
circle radius 3
square side 4
isa circle: 1 0
nonnull: 0

For a class with subclasses of its own, classof checks a range of kinds (K >= SK_FirstX && K <= SK_LastX); this is exactly how Value.h handles groups such as constants.

Comparison with dynamic_cast

dynamic_cast dyn_cast
Needs C++ RTTI and virtual functions Yes No
Cost Walks type info at run time One compare on a stored kind
Works on classes you add Automatically After you write classof
Available in LLVM builds No (RTTI off) Yes

Sources: cppreference: dynamic_cast, Wikipedia: Run-time type information

Common Traps

  • Using cast when you aren't sure: release builds don't check, so a wrong cast is undefined behaviour.
  • Testing with isa and then calling cast again: write one dyn_cast instead.
  • Passing null to isa/cast/dyn_cast: use the _and_nonnull / _if_present forms.
  • Forgetting classof in a new subclass: compile errors mention classof.

Key Points

  • isa tests, cast converts and asserts, dyn_cast converts or returns null.
  • They work through static classof functions checking a kind stored in the object, with no C++ RTTI.
  • Add LLVM-style RTTI to your own hierarchy with a kind enum and classof.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally