remove the rest of the "written by" lines in the documentation. It is
[oota-llvm.git] / docs / HowToSetUpLLVMStyleRTTI.rst
1 .. _how-to-set-up-llvm-style-rtti:
2
3 ======================================================
4 How to set up LLVM-style RTTI for your class hierarchy
5 ======================================================
6
7 .. contents::
8
9 Background
10 ==========
11
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.
15
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.
20
21 Before diving in, make sure that you are familiar with the Object Oriented
22 Programming concept of "`is-a`_".
23
24 .. _is-a: http://en.wikipedia.org/wiki/Is-a
25
26 Basic Setup
27 ===========
28
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:
32
33 .. code-block:: c++
34
35    class Shape {
36    public:
37      Shape() {}
38      virtual double computeArea() = 0;
39    };
40
41    class Square : public Shape {
42      double SideLength;
43    public:
44      Square(double S) : SideLength(S) {}
45      double computeArea() /* override */;
46    };
47
48    class Circle : public Shape {
49      double Radius;
50    public:
51      Circle(double R) : Radius(R) {}
52      double computeArea() /* override */;
53    };
54
55 The most basic working setup for LLVM-style RTTI requires the following
56 steps:
57
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.
61
62    .. code-block:: c++
63
64       #include "llvm/Support/Casting.h"
65
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.
69
70    Here is the code after introducing this change:
71
72    .. code-block:: c++
73
74        class Shape {
75        public:
76       +  /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
77       +  enum ShapeKind {
78       +    SK_Square,
79       +    SK_Circle
80       +  };
81       +private:
82       +  const ShapeKind Kind;
83       +public:
84       +  ShapeKind getKind() const { return Kind; }
85       +
86          Shape() {}
87          virtual double computeArea() = 0;
88        };
89
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.
94
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``.
99
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.
108
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.
113
114    Here is the code after that change:
115
116    .. code-block:: c++
117
118        class Shape {
119        public:
120          /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
121          enum ShapeKind {
122            SK_Square,
123            SK_Circle
124          };
125        private:
126          const ShapeKind Kind;
127        public:
128          ShapeKind getKind() const { return Kind; }
129
130       -  Shape() {}
131       +  Shape(ShapeKind K) : Kind(K) {}
132          virtual double computeArea() = 0;
133        };
134
135        class Square : public Shape {
136          double SideLength;
137        public:
138       -  Square(double S) : SideLength(S) {}
139       +  Square(double S) : Shape(SK_Square), SideLength(S) {}
140          double computeArea() /* override */;
141        };
142
143        class Circle : public Shape {
144          double Radius;
145        public:
146       -  Circle(double R) : Radius(R) {}
147       +  Circle(double R) : Shape(SK_Circle), Radius(R) {}
148          double computeArea() /* override */;
149        };
150
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:
157
158    .. code-block:: c++
159
160        class Shape {
161        public:
162          /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
163          enum ShapeKind {
164            SK_Square,
165            SK_Circle
166          };
167        private:
168          const ShapeKind Kind;
169        public:
170          ShapeKind getKind() const { return Kind; }
171
172          Shape(ShapeKind K) : Kind(K) {}
173          virtual double computeArea() = 0;
174        };
175
176        class Square : public Shape {
177          double SideLength;
178        public:
179          Square(double S) : Shape(SK_Square), SideLength(S) {}
180          double computeArea() /* override */;
181       +
182       +  static bool classof(const Shape *S) {
183       +    return S->getKind() == SK_Square;
184       +  }
185        };
186
187        class Circle : public Shape {
188          double Radius;
189        public:
190          Circle(double R) : Shape(SK_Circle), Radius(R) {}
191          double computeArea() /* override */;
192       +
193       +  static bool classof(const Shape *S) {
194       +    return S->getKind() == SK_Circle;
195       +  }
196        };
197
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``.
202
203    To be concrete, consider the following code:
204
205    .. code-block:: c++
206
207       Shape *S = ...;
208       if (isa<Circle>(S)) {
209         /* do something ... */
210       }
211
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`.
216
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:
221
222    .. code-block:: c++
223
224       class Foo {
225         [...]
226         template <class T>
227         static bool classof(const T *,
228                             ::llvm::enable_if_c<
229                               ::llvm::is_base_of<Foo, T>::value
230                             >::type* = 0) { return true; }
231         [...]
232       };
233
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.
240
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.
244
245 Concrete Bases and Deeper Hierarchies
246 =====================================
247
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
251
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
254   type.
255
256 * Since the class has children, the check inside ``classof`` must take them
257   into account.
258
259 Say that ``SpecialSquare`` and ``OtherSpecialSquare`` derive
260 from ``Square``, and so ``ShapeKind`` becomes:
261
262 .. code-block:: c++
263
264     enum ShapeKind {
265       SK_Square,
266    +  SK_SpecialSquare,
267    +  SK_OtherSpecialSquare,
268       SK_Circle
269     }
270
271 Then in ``Square``, we would need to modify the ``classof`` like so:
272
273 .. code-block:: c++
274
275    -  static bool classof(const Shape *S) {
276    -    return S->getKind() == SK_Square;
277    -  }
278    +  static bool classof(const Shape *S) {
279    +    return S->getKind() >= SK_Square &&
280    +           S->getKind() <= SK_OtherSpecialSquare;
281    +  }
282
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.
286
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
292 ordering right::
293
294    | Shape
295      | Square
296        | SpecialSquare
297        | OtherSpecialSquare
298      | Circle
299
300 .. _classof-contract:
301
302 The Contract of ``classof``
303 ---------------------------
304
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.
309
310 .. TODO::
311
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/..."
316
317 Rules of Thumb
318 ==============
319
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``.