1 .. _how-to-set-up-llvm-style-rtti:
3 ======================================================
4 How to set up LLVM-style RTTI for your class hierarchy
5 ======================================================
12 LLVM avoids using C++'s built in RTTI. Instead, it pervasively uses its
13 own hand-rolled form of RTTI which is much more efficient and flexible,
14 although it requires a bit more work from you as a class author.
16 A description of how to use LLVM-style RTTI from a client's perspective is
17 given in the `Programmer's Manual <ProgrammersManual.html#isa>`_. This
18 document, in contrast, discusses the steps you need to take as a class
19 hierarchy author to make LLVM-style RTTI available to your clients.
21 Before diving in, make sure that you are familiar with the Object Oriented
22 Programming concept of "`is-a`_".
24 .. _is-a: http://en.wikipedia.org/wiki/Is-a
29 This section describes how to set up the most basic form of LLVM-style RTTI
30 (which is sufficient for 99.9% of the cases). We will set up LLVM-style
31 RTTI for this class hierarchy:
38 virtual double computeArea() = 0;
41 class Square : public Shape {
44 Square(double S) : SideLength(S) {}
45 double computeArea() /* override */;
48 class Circle : public Shape {
51 Circle(double R) : Radius(R) {}
52 double computeArea() /* override */;
55 The most basic working setup for LLVM-style RTTI requires the following
58 #. In the header where you declare ``Shape``, you will want to ``#include
59 "llvm/Support/Casting.h"``, which declares LLVM's RTTI templates. That
60 way your clients don't even have to think about it.
64 #include "llvm/Support/Casting.h"
66 #. In the base class, introduce an enum which discriminates all of the
67 different concrete classes in the hierarchy, and stash the enum value
68 somewhere in the base class.
70 Here is the code after introducing this change:
76 + /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
82 + const ShapeKind Kind;
84 + ShapeKind getKind() const { return Kind; }
87 virtual double computeArea() = 0;
90 You will usually want to keep the ``Kind`` member encapsulated and
91 private, but let the enum ``ShapeKind`` be public along with providing a
92 ``getKind()`` method. This is convenient for clients so that they can do
93 a ``switch`` over the enum.
95 A common naming convention is that these enums are "kind"s, to avoid
96 ambiguity with the words "type" or "class" which have overloaded meanings
97 in many contexts within LLVM. Sometimes there will be a natural name for
98 it, like "opcode". Don't bikeshed over this; when in doubt use ``Kind``.
100 You might wonder why the ``Kind`` enum doesn't have an entry for
101 ``Shape``. The reason for this is that since ``Shape`` is abstract
102 (``computeArea() = 0;``), you will never actually have non-derived
103 instances of exactly that class (only subclasses). See `Concrete Bases
104 and Deeper Hierarchies`_ for information on how to deal with
105 non-abstract bases. It's worth mentioning here that unlike
106 ``dynamic_cast<>``, LLVM-style RTTI can be used (and is often used) for
107 classes that don't have v-tables.
109 #. Next, you need to make sure that the ``Kind`` gets initialized to the
110 value corresponding to the dynamic type of the class. Typically, you will
111 want to have it be an argument to the constructor of the base class, and
112 then pass in the respective ``XXXKind`` from subclass constructors.
114 Here is the code after that change:
120 /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
126 const ShapeKind Kind;
128 ShapeKind getKind() const { return Kind; }
131 + Shape(ShapeKind K) : Kind(K) {}
132 virtual double computeArea() = 0;
135 class Square : public Shape {
138 - Square(double S) : SideLength(S) {}
139 + Square(double S) : Shape(SK_Square), SideLength(S) {}
140 double computeArea() /* override */;
143 class Circle : public Shape {
146 - Circle(double R) : Radius(R) {}
147 + Circle(double R) : Shape(SK_Circle), Radius(R) {}
148 double computeArea() /* override */;
151 #. Finally, you need to inform LLVM's RTTI templates how to dynamically
152 determine the type of a class (i.e. whether the ``isa<>``/``dyn_cast<>``
153 should succeed). The default "99.9% of use cases" way to accomplish this
154 is through a small static member function ``classof``. In order to have
155 proper context for an explanation, we will display this code first, and
156 then below describe each part:
162 /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
168 const ShapeKind Kind;
170 ShapeKind getKind() const { return Kind; }
172 Shape(ShapeKind K) : Kind(K) {}
173 virtual double computeArea() = 0;
176 class Square : public Shape {
179 Square(double S) : Shape(SK_Square), SideLength(S) {}
180 double computeArea() /* override */;
182 + static bool classof(const Shape *S) {
183 + return S->getKind() == SK_Square;
187 class Circle : public Shape {
190 Circle(double R) : Shape(SK_Circle), Radius(R) {}
191 double computeArea() /* override */;
193 + static bool classof(const Shape *S) {
194 + return S->getKind() == SK_Circle;
198 The job of ``classof`` is to dynamically determine whether an object of
199 a base class is in fact of a particular derived class. In order to
200 downcast a type ``Base`` to a type ``Derived``, there needs to be a
201 ``classof`` in ``Derived`` which will accept an object of type ``Base``.
203 To be concrete, consider the following code:
208 if (isa<Circle>(S)) {
209 /* do something ... */
212 The code of the ``isa<>`` test in this code will eventually boil
213 down---after template instantiation and some other machinery---to a
214 check roughly like ``Circle::classof(S)``. For more information, see
215 :ref:`classof-contract`.
217 The argument to ``classof`` should always be an *ancestor* class because
218 the implementation has logic to allow and optimize away
219 upcasts/up-``isa<>``'s automatically. It is as though every class
220 ``Foo`` automatically has a ``classof`` like:
227 static bool classof(const T *,
229 ::llvm::is_base_of<Foo, T>::value
230 >::type* = 0) { return true; }
234 Note that this is the reason that we did not need to introduce a
235 ``classof`` into ``Shape``: all relevant classes derive from ``Shape``,
236 and ``Shape`` itself is abstract (has no entry in the ``Kind`` enum),
237 so this notional inferred ``classof`` is all we need. See `Concrete
238 Bases and Deeper Hierarchies`_ for more information about how to extend
239 this example to more general hierarchies.
241 Although for this small example setting up LLVM-style RTTI seems like a lot
242 of "boilerplate", if your classes are doing anything interesting then this
243 will end up being a tiny fraction of the code.
245 Concrete Bases and Deeper Hierarchies
246 =====================================
248 For concrete bases (i.e. non-abstract interior nodes of the inheritance
249 tree), the ``Kind`` check inside ``classof`` needs to be a bit more
250 complicated. The situation differs from the example above in that
252 * Since the class is concrete, it must itself have an entry in the ``Kind``
253 enum because it is possible to have objects with this class as a dynamic
256 * Since the class has children, the check inside ``classof`` must take them
259 Say that ``SpecialSquare`` and ``OtherSpecialSquare`` derive
260 from ``Square``, and so ``ShapeKind`` becomes:
267 + SK_OtherSpecialSquare,
271 Then in ``Square``, we would need to modify the ``classof`` like so:
275 - static bool classof(const Shape *S) {
276 - return S->getKind() == SK_Square;
278 + static bool classof(const Shape *S) {
279 + return S->getKind() >= SK_Square &&
280 + S->getKind() <= SK_OtherSpecialSquare;
283 The reason that we need to test a range like this instead of just equality
284 is that both ``SpecialSquare`` and ``OtherSpecialSquare`` "is-a"
285 ``Square``, and so ``classof`` needs to return ``true`` for them.
287 This approach can be made to scale to arbitrarily deep hierarchies. The
288 trick is that you arrange the enum values so that they correspond to a
289 preorder traversal of the class hierarchy tree. With that arrangement, all
290 subclass tests can be done with two comparisons as shown above. If you just
291 list the class hierarchy like a list of bullet points, you'll get the
300 .. _classof-contract:
302 The Contract of ``classof``
303 ---------------------------
305 To be more precise, let ``classof`` be inside a class ``C``. Then the
306 contract for ``classof`` is "return ``true`` if the dynamic type of the
307 argument is-a ``C``". As long as your implementation fulfills this
308 contract, you can tweak and optimize it as much as you want.
312 Touch on some of the more advanced features, like ``isa_impl`` and
313 ``simplify_type``. However, those two need reference documentation in
314 the form of doxygen comments as well. We need the doxygen so that we can
315 say "for full details, see http://llvm.org/doxygen/..."
320 #. The ``Kind`` enum should have one entry per concrete class, ordered
321 according to a preorder traversal of the inheritance tree.
322 #. The argument to ``classof`` should be a ``const Base *``, where ``Base``
323 is some ancestor in the inheritance hierarchy. The argument should
324 *never* be a derived class or the class itself: the template machinery
325 for ``isa<>`` already handles this case and optimizes it.
326 #. For each class in the hierarchy that has no children, implement a
327 ``classof`` that checks only against its ``Kind``.
328 #. For each class in the hierarchy that has children, implement a
329 ``classof`` that checks a range of the first child's ``Kind`` and the
330 last child's ``Kind``.