blob: f89e3027d5d023f1d12041feca951b1b8917d27b [file] [log] [blame]
Bill Wendlingc66b1522012-06-27 07:20:57 +00001==========================
2Exception Handling in LLVM
3==========================
4
5.. contents::
6 :local:
7
8Introduction
9============
10
11This document is the central repository for all information pertaining to
12exception handling in LLVM. It describes the format that LLVM exception
13handling information takes, which is useful for those interested in creating
14front-ends or dealing directly with the information. Further, this document
15provides specific examples of what exception handling information is used for in
16C and C++.
17
18Itanium ABI Zero-cost Exception Handling
19----------------------------------------
20
21Exception handling for most programming languages is designed to recover from
22conditions that rarely occur during general use of an application. To that end,
23exception handling should not interfere with the main flow of an application's
24algorithm by performing checkpointing tasks, such as saving the current pc or
25register state.
26
27The Itanium ABI Exception Handling Specification defines a methodology for
28providing outlying data in the form of exception tables without inlining
29speculative exception handling code in the flow of an application's main
30algorithm. Thus, the specification is said to add "zero-cost" to the normal
31execution of an application.
32
33A more complete description of the Itanium ABI exception handling runtime
34support of can be found at `Itanium C++ ABI: Exception Handling
Tim Northover4694b542013-01-12 19:54:21 +000035<http://mentorembedded.github.com/cxx-abi/abi-eh.html>`_. A description of the
Bill Wendlingc66b1522012-06-27 07:20:57 +000036exception frame format can be found at `Exception Frames
Tim Northover53acb322013-01-12 12:38:54 +000037<http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html>`_,
Bill Wendlingc66b1522012-06-27 07:20:57 +000038with details of the DWARF 4 specification at `DWARF 4 Standard
39<http://dwarfstd.org/Dwarf4Std.php>`_. A description for the C++ exception
40table formats can be found at `Exception Handling Tables
Tim Northover53acb322013-01-12 12:38:54 +000041<http://mentorembedded.github.com/cxx-abi/exceptions.pdf>`_.
Bill Wendlingc66b1522012-06-27 07:20:57 +000042
43Setjmp/Longjmp Exception Handling
44---------------------------------
45
46Setjmp/Longjmp (SJLJ) based exception handling uses LLVM intrinsics
47`llvm.eh.sjlj.setjmp`_ and `llvm.eh.sjlj.longjmp`_ to handle control flow for
48exception handling.
49
50For each function which does exception processing --- be it ``try``/``catch``
51blocks or cleanups --- that function registers itself on a global frame
52list. When exceptions are unwinding, the runtime uses this list to identify
53which functions need processing.
54
55Landing pad selection is encoded in the call site entry of the function
56context. The runtime returns to the function via `llvm.eh.sjlj.longjmp`_, where
57a switch table transfers control to the appropriate landing pad based on the
58index stored in the function context.
59
60In contrast to DWARF exception handling, which encodes exception regions and
61frame information in out-of-line tables, SJLJ exception handling builds and
62removes the unwind frame context at runtime. This results in faster exception
63handling at the expense of slower execution when no exceptions are thrown. As
64exceptions are, by their nature, intended for uncommon code paths, DWARF
65exception handling is generally preferred to SJLJ.
66
Andrew Kaylor78b53db2015-02-10 19:52:43 +000067Windows Runtime Exception Handling
68-----------------------------------
69
Reid Klecknerfc573f332015-08-06 21:01:32 +000070LLVM supports handling exceptions produced by the Windows runtime, but it
71requires a very different intermediate representation. It is not based on the
72":ref:`landingpad <i_landingpad>`" instruction like the other two models, and is
73described later in this document under :ref:`wineh`.
Andrew Kaylor78b53db2015-02-10 19:52:43 +000074
Bill Wendlingc66b1522012-06-27 07:20:57 +000075Overview
76--------
77
78When an exception is thrown in LLVM code, the runtime does its best to find a
79handler suited to processing the circumstance.
80
81The runtime first attempts to find an *exception frame* corresponding to the
82function where the exception was thrown. If the programming language supports
83exception handling (e.g. C++), the exception frame contains a reference to an
84exception table describing how to process the exception. If the language does
85not support exception handling (e.g. C), or if the exception needs to be
86forwarded to a prior activation, the exception frame contains information about
87how to unwind the current activation and restore the state of the prior
88activation. This process is repeated until the exception is handled. If the
89exception is not handled and no activations remain, then the application is
90terminated with an appropriate error message.
91
92Because different programming languages have different behaviors when handling
93exceptions, the exception handling ABI provides a mechanism for
94supplying *personalities*. An exception handling personality is defined by
95way of a *personality function* (e.g. ``__gxx_personality_v0`` in C++),
96which receives the context of the exception, an *exception structure*
97containing the exception object type and value, and a reference to the exception
98table for the current function. The personality function for the current
99compile unit is specified in a *common exception frame*.
100
101The organization of an exception table is language dependent. For C++, an
102exception table is organized as a series of code ranges defining what to do if
103an exception occurs in that range. Typically, the information associated with a
104range defines which types of exception objects (using C++ *type info*) that are
105handled in that range, and an associated action that should take place. Actions
106typically pass control to a *landing pad*.
107
108A landing pad corresponds roughly to the code found in the ``catch`` portion of
109a ``try``/``catch`` sequence. When execution resumes at a landing pad, it
110receives an *exception structure* and a *selector value* corresponding to the
111*type* of exception thrown. The selector is then used to determine which *catch*
112should actually process the exception.
113
114LLVM Code Generation
115====================
116
117From a C++ developer's perspective, exceptions are defined in terms of the
118``throw`` and ``try``/``catch`` statements. In this section we will describe the
119implementation of LLVM exception handling in terms of C++ examples.
120
121Throw
122-----
123
124Languages that support exception handling typically provide a ``throw``
125operation to initiate the exception process. Internally, a ``throw`` operation
126breaks down into two steps.
127
128#. A request is made to allocate exception space for an exception structure.
129 This structure needs to survive beyond the current activation. This structure
130 will contain the type and value of the object being thrown.
131
132#. A call is made to the runtime to raise the exception, passing the exception
133 structure as an argument.
134
135In C++, the allocation of the exception structure is done by the
136``__cxa_allocate_exception`` runtime function. The exception raising is handled
137by ``__cxa_throw``. The type of the exception is represented using a C++ RTTI
138structure.
139
140Try/Catch
141---------
142
143A call within the scope of a *try* statement can potentially raise an
144exception. In those circumstances, the LLVM C++ front-end replaces the call with
145an ``invoke`` instruction. Unlike a call, the ``invoke`` has two potential
146continuation points:
147
148#. where to continue when the call succeeds as per normal, and
149
150#. where to continue if the call raises an exception, either by a throw or the
151 unwinding of a throw
152
Mark Seaborn20f9ddb2014-02-27 06:54:04 +0000153The term used to define the place where an ``invoke`` continues after an
Bill Wendlingc66b1522012-06-27 07:20:57 +0000154exception is called a *landing pad*. LLVM landing pads are conceptually
155alternative function entry points where an exception structure reference and a
156type info index are passed in as arguments. The landing pad saves the exception
157structure reference and then proceeds to select the catch block that corresponds
158to the type info of the exception object.
159
Dmitri Gribenkoc5137402013-01-13 16:06:11 +0000160The LLVM :ref:`i_landingpad` is used to convey information about the landing
161pad to the back end. For C++, the ``landingpad`` instruction returns a pointer
162and integer pair corresponding to the pointer to the *exception structure* and
163the *selector value* respectively.
Bill Wendlingc66b1522012-06-27 07:20:57 +0000164
Vedant Kumar9e1998e2015-09-08 20:16:35 +0000165The ``landingpad`` instruction looks for a reference to the personality
166function to be used for this ``try``/``catch`` sequence in the parent
167function's attribute list. The instruction contains a list of *cleanup*,
168*catch*, and *filter* clauses. The exception is tested against the clauses
169sequentially from first to last. The clauses have the following meanings:
Mark Seaborn202169a2014-02-25 23:48:59 +0000170
171- ``catch <type> @ExcType``
172
173 - This clause means that the landingpad block should be entered if the
174 exception being thrown is of type ``@ExcType`` or a subtype of
175 ``@ExcType``. For C++, ``@ExcType`` is a pointer to the ``std::type_info``
176 object (an RTTI object) representing the C++ exception type.
177
178 - If ``@ExcType`` is ``null``, any exception matches, so the landingpad
179 should always be entered. This is used for C++ catch-all blocks ("``catch
180 (...)``").
181
182 - When this clause is matched, the selector value will be equal to the value
183 returned by "``@llvm.eh.typeid.for(i8* @ExcType)``". This will always be a
184 positive value.
185
186- ``filter <type> [<type> @ExcType1, ..., <type> @ExcTypeN]``
187
188 - This clause means that the landingpad should be entered if the exception
189 being thrown does *not* match any of the types in the list (which, for C++,
190 are again specified as ``std::type_info`` pointers).
191
192 - C++ front-ends use this to implement C++ exception specifications, such as
193 "``void foo() throw (ExcType1, ..., ExcTypeN) { ... }``".
194
195 - When this clause is matched, the selector value will be negative.
196
197 - The array argument to ``filter`` may be empty; for example, "``[0 x i8**]
198 undef``". This means that the landingpad should always be entered. (Note
199 that such a ``filter`` would not be equivalent to "``catch i8* null``",
200 because ``filter`` and ``catch`` produce negative and positive selector
201 values respectively.)
202
203- ``cleanup``
204
205 - This clause means that the landingpad should always be entered.
206
207 - C++ front-ends use this for calling objects' destructors.
208
209 - When this clause is matched, the selector value will be zero.
210
211 - The runtime may treat "``cleanup``" differently from "``catch <type>
212 null``".
213
214 In C++, if an unhandled exception occurs, the language runtime will call
215 ``std::terminate()``, but it is implementation-defined whether the runtime
216 unwinds the stack and calls object destructors first. For example, the GNU
217 C++ unwinder does not call object destructors when an unhandled exception
218 occurs. The reason for this is to improve debuggability: it ensures that
219 ``std::terminate()`` is called from the context of the ``throw``, so that
220 this context is not lost by unwinding the stack. A runtime will typically
221 implement this by searching for a matching non-``cleanup`` clause, and
222 aborting if it does not find one, before entering any landingpad blocks.
Bill Wendlingc66b1522012-06-27 07:20:57 +0000223
224Once the landing pad has the type info selector, the code branches to the code
225for the first catch. The catch then checks the value of the type info selector
226against the index of type info for that catch. Since the type info index is not
227known until all the type infos have been gathered in the backend, the catch code
228must call the `llvm.eh.typeid.for`_ intrinsic to determine the index for a given
229type info. If the catch fails to match the selector then control is passed on to
230the next catch.
231
232Finally, the entry and exit of catch code is bracketed with calls to
233``__cxa_begin_catch`` and ``__cxa_end_catch``.
234
235* ``__cxa_begin_catch`` takes an exception structure reference as an argument
236 and returns the value of the exception object.
237
238* ``__cxa_end_catch`` takes no arguments. This function:
239
240 #. Locates the most recently caught exception and decrements its handler
241 count,
242
243 #. Removes the exception from the *caught* stack if the handler count goes to
244 zero, and
245
246 #. Destroys the exception if the handler count goes to zero and the exception
247 was not re-thrown by throw.
248
249 .. note::
250
251 a rethrow from within the catch may replace this call with a
252 ``__cxa_rethrow``.
253
254Cleanups
255--------
256
257A cleanup is extra code which needs to be run as part of unwinding a scope. C++
258destructors are a typical example, but other languages and language extensions
259provide a variety of different kinds of cleanups. In general, a landing pad may
260need to run arbitrary amounts of cleanup code before actually entering a catch
Dmitri Gribenkoc5137402013-01-13 16:06:11 +0000261block. To indicate the presence of cleanups, a :ref:`i_landingpad` should have
262a *cleanup* clause. Otherwise, the unwinder will not stop at the landing pad if
263there are no catches or filters that require it to.
Bill Wendlingc66b1522012-06-27 07:20:57 +0000264
265.. note::
266
267 Do not allow a new exception to propagate out of the execution of a
268 cleanup. This can corrupt the internal state of the unwinder. Different
269 languages describe different high-level semantics for these situations: for
270 example, C++ requires that the process be terminated, whereas Ada cancels both
271 exceptions and throws a third.
272
273When all cleanups are finished, if the exception is not handled by the current
Nico Weberfa147e02015-02-26 19:48:43 +0000274function, resume unwinding by calling the :ref:`resume instruction <i_resume>`,
275passing in the result of the ``landingpad`` instruction for the original
276landing pad.
Bill Wendlingc66b1522012-06-27 07:20:57 +0000277
278Throw Filters
279-------------
280
281C++ allows the specification of which exception types may be thrown from a
282function. To represent this, a top level landing pad may exist to filter out
Dmitri Gribenkoc5137402013-01-13 16:06:11 +0000283invalid types. To express this in LLVM code the :ref:`i_landingpad` will have a
284filter clause. The clause consists of an array of type infos.
285``landingpad`` will return a negative value
Bill Wendlingc66b1522012-06-27 07:20:57 +0000286if the exception does not match any of the type infos. If no match is found then
287a call to ``__cxa_call_unexpected`` should be made, otherwise
288``_Unwind_Resume``. Each of these functions requires a reference to the
289exception structure. Note that the most general form of a ``landingpad``
290instruction can have any number of catch, cleanup, and filter clauses (though
291having more than one cleanup is pointless). The LLVM C++ front-end can generate
292such ``landingpad`` instructions due to inlining creating nested exception
293handling scopes.
294
295.. _undefined:
296
297Restrictions
298------------
299
300The unwinder delegates the decision of whether to stop in a call frame to that
301call frame's language-specific personality function. Not all unwinders guarantee
302that they will stop to perform cleanups. For example, the GNU C++ unwinder
303doesn't do so unless the exception is actually caught somewhere further up the
304stack.
305
306In order for inlining to behave correctly, landing pads must be prepared to
307handle selector results that they did not originally advertise. Suppose that a
308function catches exceptions of type ``A``, and it's inlined into a function that
309catches exceptions of type ``B``. The inliner will update the ``landingpad``
310instruction for the inlined landing pad to include the fact that ``B`` is also
311caught. If that landing pad assumes that it will only be entered to catch an
312``A``, it's in for a rude awakening. Consequently, landing pads must test for
313the selector results they understand and then resume exception propagation with
314the `resume instruction <LangRef.html#i_resume>`_ if none of the conditions
315match.
316
317Exception Handling Intrinsics
318=============================
319
320In addition to the ``landingpad`` and ``resume`` instructions, LLVM uses several
321intrinsic functions (name prefixed with ``llvm.eh``) to provide exception
322handling information at various points in generated code.
323
324.. _llvm.eh.typeid.for:
325
Dmitri Gribenkobb13a3c2013-01-13 16:07:49 +0000326``llvm.eh.typeid.for``
327----------------------
Bill Wendlingc66b1522012-06-27 07:20:57 +0000328
329.. code-block:: llvm
330
331 i32 @llvm.eh.typeid.for(i8* %type_info)
332
333
334This intrinsic returns the type info index in the exception table of the current
335function. This value can be used to compare against the result of
336``landingpad`` instruction. The single argument is a reference to a type info.
337
Mark Seabornf8388a72014-03-28 17:08:57 +0000338Uses of this intrinsic are generated by the C++ front-end.
339
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000340.. _llvm.eh.begincatch:
341
342``llvm.eh.begincatch``
343----------------------
344
345.. code-block:: llvm
346
Reid Kleckner2f05d4c2015-03-03 17:41:09 +0000347 void @llvm.eh.begincatch(i8* %ehptr, i8* %ehobj)
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000348
349
350This intrinsic marks the beginning of catch handling code within the blocks
351following a ``landingpad`` instruction. The exact behavior of this function
352depends on the compilation target and the personality function associated
353with the ``landingpad`` instruction.
354
Reid Kleckner2f05d4c2015-03-03 17:41:09 +0000355The first argument to this intrinsic is a pointer that was previously extracted
356from the aggregate return value of the ``landingpad`` instruction. The second
357argument to the intrinsic is a pointer to stack space where the exception object
358should be stored. The runtime handles the details of copying the exception
359object into the slot. If the second parameter is null, no copy occurs.
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000360
361Uses of this intrinsic are generated by the C++ front-end. Many targets will
362use implementation-specific functions (such as ``__cxa_begin_catch``) instead
363of this intrinsic. The intrinsic is provided for targets that require a more
364abstract interface.
365
366When used in the native Windows C++ exception handling implementation, this
367intrinsic serves as a placeholder to delimit code before a catch handler is
368outlined. When the handler is is outlined, this intrinsic will be replaced
369by instructions that retrieve the exception object pointer from the frame
370allocation block.
371
372
373.. _llvm.eh.endcatch:
374
375``llvm.eh.endcatch``
376----------------------
377
378.. code-block:: llvm
379
380 void @llvm.eh.endcatch()
381
382
383This intrinsic marks the end of catch handling code within the current block,
384which will be a successor of a block which called ``llvm.eh.begincatch''.
385The exact behavior of this function depends on the compilation target and the
386personality function associated with the corresponding ``landingpad``
387instruction.
388
389There may be more than one call to ``llvm.eh.endcatch`` for any given call to
390``llvm.eh.begincatch`` with each ``llvm.eh.endcatch`` call corresponding to the
391end of a different control path. All control paths following a call to
392``llvm.eh.begincatch`` must reach a call to ``llvm.eh.endcatch``.
393
394Uses of this intrinsic are generated by the C++ front-end. Many targets will
395use implementation-specific functions (such as ``__cxa_begin_catch``) instead
396of this intrinsic. The intrinsic is provided for targets that require a more
397abstract interface.
398
399When used in the native Windows C++ exception handling implementation, this
400intrinsic serves as a placeholder to delimit code before a catch handler is
401outlined. After the handler is outlined, this intrinsic is simply removed.
402
403
Joseph Tremoulet61efbc32015-09-03 09:15:32 +0000404.. _llvm.eh.exceptionpointer:
405
406``llvm.eh.exceptionpointer``
Joseph Tremoulet6dfe1642015-09-03 09:33:54 +0000407----------------------------
Joseph Tremoulet61efbc32015-09-03 09:15:32 +0000408
409.. code-block:: llvm
410
411 i8 addrspace(N)* @llvm.eh.padparam.pNi8(token %catchpad)
412
413
414This intrinsic retrieves a pointer to the exception caught by the given
415``catchpad``.
416
417
Mark Seabornf8388a72014-03-28 17:08:57 +0000418SJLJ Intrinsics
419---------------
420
421The ``llvm.eh.sjlj`` intrinsics are used internally within LLVM's
422backend. Uses of them are generated by the backend's
423``SjLjEHPrepare`` pass.
424
Bill Wendlingc66b1522012-06-27 07:20:57 +0000425.. _llvm.eh.sjlj.setjmp:
426
Dmitri Gribenkobb13a3c2013-01-13 16:07:49 +0000427``llvm.eh.sjlj.setjmp``
Mark Seabornf8388a72014-03-28 17:08:57 +0000428~~~~~~~~~~~~~~~~~~~~~~~
Bill Wendlingc66b1522012-06-27 07:20:57 +0000429
430.. code-block:: llvm
431
432 i32 @llvm.eh.sjlj.setjmp(i8* %setjmp_buf)
433
434For SJLJ based exception handling, this intrinsic forces register saving for the
435current function and stores the address of the following instruction for use as
436a destination address by `llvm.eh.sjlj.longjmp`_. The buffer format and the
437overall functioning of this intrinsic is compatible with the GCC
438``__builtin_setjmp`` implementation allowing code built with the clang and GCC
439to interoperate.
440
441The single parameter is a pointer to a five word buffer in which the calling
442context is saved. The front end places the frame pointer in the first word, and
443the target implementation of this intrinsic should place the destination address
444for a `llvm.eh.sjlj.longjmp`_ in the second word. The following three words are
445available for use in a target-specific manner.
446
447.. _llvm.eh.sjlj.longjmp:
448
Dmitri Gribenkobb13a3c2013-01-13 16:07:49 +0000449``llvm.eh.sjlj.longjmp``
Mark Seabornf8388a72014-03-28 17:08:57 +0000450~~~~~~~~~~~~~~~~~~~~~~~~
Bill Wendlingc66b1522012-06-27 07:20:57 +0000451
452.. code-block:: llvm
453
454 void @llvm.eh.sjlj.longjmp(i8* %setjmp_buf)
455
456For SJLJ based exception handling, the ``llvm.eh.sjlj.longjmp`` intrinsic is
457used to implement ``__builtin_longjmp()``. The single parameter is a pointer to
458a buffer populated by `llvm.eh.sjlj.setjmp`_. The frame pointer and stack
459pointer are restored from the buffer, then control is transferred to the
460destination address.
461
Dmitri Gribenkobb13a3c2013-01-13 16:07:49 +0000462``llvm.eh.sjlj.lsda``
Mark Seabornf8388a72014-03-28 17:08:57 +0000463~~~~~~~~~~~~~~~~~~~~~
Bill Wendlingc66b1522012-06-27 07:20:57 +0000464
465.. code-block:: llvm
466
467 i8* @llvm.eh.sjlj.lsda()
468
469For SJLJ based exception handling, the ``llvm.eh.sjlj.lsda`` intrinsic returns
470the address of the Language Specific Data Area (LSDA) for the current
471function. The SJLJ front-end code stores this address in the exception handling
472function context for use by the runtime.
473
Dmitri Gribenkobb13a3c2013-01-13 16:07:49 +0000474``llvm.eh.sjlj.callsite``
Mark Seabornf8388a72014-03-28 17:08:57 +0000475~~~~~~~~~~~~~~~~~~~~~~~~~
Bill Wendlingc66b1522012-06-27 07:20:57 +0000476
477.. code-block:: llvm
478
479 void @llvm.eh.sjlj.callsite(i32 %call_site_num)
480
481For SJLJ based exception handling, the ``llvm.eh.sjlj.callsite`` intrinsic
482identifies the callsite value associated with the following ``invoke``
483instruction. This is used to ensure that landing pad entries in the LSDA are
484generated in matching order.
485
486Asm Table Formats
487=================
488
489There are two tables that are used by the exception handling runtime to
490determine which actions should be taken when an exception is thrown.
491
492Exception Handling Frame
493------------------------
494
495An exception handling frame ``eh_frame`` is very similar to the unwind frame
496used by DWARF debug info. The frame contains all the information necessary to
497tear down the current frame and restore the state of the prior frame. There is
498an exception handling frame for each function in a compile unit, plus a common
499exception handling frame that defines information common to all functions in the
500unit.
501
Reid Klecknerfc573f332015-08-06 21:01:32 +0000502The format of this call frame information (CFI) is often platform-dependent,
503however. ARM, for example, defines their own format. Apple has their own compact
504unwind info format. On Windows, another format is used for all architectures
505since 32-bit x86. LLVM will emit whatever information is required by the
506target.
507
Bill Wendlingc66b1522012-06-27 07:20:57 +0000508Exception Tables
509----------------
510
511An exception table contains information about what actions to take when an
Reid Klecknerfc573f332015-08-06 21:01:32 +0000512exception is thrown in a particular part of a function's code. This is typically
513referred to as the language-specific data area (LSDA). The format of the LSDA
514table is specific to the personality function, but the majority of personalities
515out there use a variation of the tables consumed by ``__gxx_personality_v0``.
516There is one exception table per function, except leaf functions and functions
517that have calls only to non-throwing functions. They do not need an exception
518table.
519
520.. _wineh:
521
522Exception Handling using the Windows Runtime
523=================================================
524
Reid Klecknerfc573f332015-08-06 21:01:32 +0000525Background on Windows exceptions
526---------------------------------
527
David Majnemer8a1c45d2015-12-12 05:38:55 +0000528Interacting with exceptions on Windows is significantly more complicated than
529on Itanium C++ ABI platforms. The fundamental difference between the two models
530is that Itanium EH is designed around the idea of "successive unwinding," while
Reid Klecknerfc573f332015-08-06 21:01:32 +0000531Windows EH is not.
532
533Under Itanium, throwing an exception typically involes allocating thread local
534memory to hold the exception, and calling into the EH runtime. The runtime
535identifies frames with appropriate exception handling actions, and successively
536resets the register context of the current thread to the most recently active
537frame with actions to run. In LLVM, execution resumes at a ``landingpad``
538instruction, which produces register values provided by the runtime. If a
539function is only cleaning up allocated resources, the function is responsible
540for calling ``_Unwind_Resume`` to transition to the next most recently active
541frame after it is finished cleaning up. Eventually, the frame responsible for
542handling the exception calls ``__cxa_end_catch`` to destroy the exception,
543release its memory, and resume normal control flow.
544
545The Windows EH model does not use these successive register context resets.
546Instead, the active exception is typically described by a frame on the stack.
547In the case of C++ exceptions, the exception object is allocated in stack memory
548and its address is passed to ``__CxxThrowException``. General purpose structured
549exceptions (SEH) are more analogous to Linux signals, and they are dispatched by
550userspace DLLs provided with Windows. Each frame on the stack has an assigned EH
551personality routine, which decides what actions to take to handle the exception.
552There are a few major personalities for C and C++ code: the C++ personality
553(``__CxxFrameHandler3``) and the SEH personalities (``_except_handler3``,
554``_except_handler4``, and ``__C_specific_handler``). All of them implement
555cleanups by calling back into a "funclet" contained in the parent function.
556
557Funclets, in this context, are regions of the parent function that can be called
558as though they were a function pointer with a very special calling convention.
559The frame pointer of the parent frame is passed into the funclet either using
560the standard EBP register or as the first parameter register, depending on the
561architecture. The funclet implements the EH action by accessing local variables
562in memory through the frame pointer, and returning some appropriate value,
563continuing the EH process. No variables live in to or out of the funclet can be
564allocated in registers.
565
566The C++ personality also uses funclets to contain the code for catch blocks
567(i.e. all user code between the braces in ``catch (Type obj) { ... }``). The
568runtime must use funclets for catch bodies because the C++ exception object is
569allocated in a child stack frame of the function handling the exception. If the
570runtime rewound the stack back to frame of the catch, the memory holding the
571exception would be overwritten quickly by subsequent function calls. The use of
572funclets also allows ``__CxxFrameHandler3`` to implement rethrow without
573resorting to TLS. Instead, the runtime throws a special exception, and then uses
574SEH (``__try / __except``) to resume execution with new information in the child
575frame.
576
577In other words, the successive unwinding approach is incompatible with Visual
578C++ exceptions and general purpose Windows exception handling. Because the C++
579exception object lives in stack memory, LLVM cannot provide a custom personality
580function that uses landingpads. Similarly, SEH does not provide any mechanism
581to rethrow an exception or continue unwinding. Therefore, LLVM must use the IR
582constructs described later in this document to implement compatible exception
583handling.
584
585SEH filter expressions
586-----------------------
587
588The SEH personality functions also use funclets to implement filter expressions,
589which allow executing arbitrary user code to decide which exceptions to catch.
590Filter expressions should not be confused with the ``filter`` clause of the LLVM
591``landingpad`` instruction. Typically filter expressions are used to determine
592if the exception came from a particular DLL or code region, or if code faulted
593while accessing a particular memory address range. LLVM does not currently have
594IR to represent filter expressions because it is difficult to represent their
595control dependencies. Filter expressions run during the first phase of EH,
596before cleanups run, making it very difficult to build a faithful control flow
597graph. For now, the new EH instructions cannot represent SEH filter
598expressions, and frontends must outline them ahead of time. Local variables of
599the parent function can be escaped and accessed using the ``llvm.localescape``
600and ``llvm.localrecover`` intrinsics.
601
602New exception handling instructions
603------------------------------------
604
605The primary design goal of the new EH instructions is to support funclet
606generation while preserving information about the CFG so that SSA formation
607still works. As a secondary goal, they are designed to be generic across MSVC
608and Itanium C++ exceptions. They make very few assumptions about the data
609required by the personality, so long as it uses the familiar core EH actions:
610catch, cleanup, and terminate. However, the new instructions are hard to modify
611without knowing details of the EH personality. While they can be used to
612represent Itanium EH, the landingpad model is strictly better for optimization
613purposes.
614
615The following new instructions are considered "exception handling pads", in that
616they must be the first non-phi instruction of a basic block that may be the
David Majnemer8a1c45d2015-12-12 05:38:55 +0000617unwind destination of an EH flow edge:
618``catchswitch``, ``catchpad``, ``cleanuppad``, and ``terminatepad``.
619As with landingpads, when entering a try scope, if the
Reid Klecknerfc573f332015-08-06 21:01:32 +0000620frontend encounters a call site that may throw an exception, it should emit an
David Majnemer8a1c45d2015-12-12 05:38:55 +0000621invoke that unwinds to a ``catchswitch`` block. Similarly, inside the scope of a
Reid Klecknerfc573f332015-08-06 21:01:32 +0000622C++ object with a destructor, invokes should unwind to a ``cleanuppad``. The
623``terminatepad`` instruction exists to represent ``noexcept`` and throw
624specifications with one combined instruction. All potentially throwing calls in
625a ``noexcept`` function should transitively unwind to a terminateblock. Throw
626specifications are not implemented by MSVC, and are not yet supported.
627
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000628New instructions are also used to mark the points where control is transferred
629out of a catch/cleanup handler (which will correspond to exits from the
630generated funclet). A catch handler which reaches its end by normal execution
631executes a ``catchret`` instruction, which is a terminator indicating where in
632the function control is returned to. A cleanup handler which reaches its end
633by normal execution executes a ``cleanupret`` instruction, which is a terminator
David Majnemer8a1c45d2015-12-12 05:38:55 +0000634indicating where the active exception will unwind to next.
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000635
David Majnemer8a1c45d2015-12-12 05:38:55 +0000636Each of these new EH pad instructions has a way to identify which action should
637be considered after this action. The ``catchswitch`` and ``terminatepad``
638instructions are terminators, and have a unwind destination operand analogous
639to the unwind destination of an invoke. The ``cleanuppad`` instruction is not
640a terminator, so the unwind destination is stored on the ``cleanupret``
641instruction instead. Successfully executing a catch handler should resume
642normal control flow, so neither ``catchpad`` nor ``catchret`` instructions can
643unwind. All of these "unwind edges" may refer to a basic block that contains an
644EH pad instruction, or they may unwind to the caller. Unwinding to the caller
645has roughly the same semantics as the ``resume`` instruction in the landingpad
646model. When inlining through an invoke, instructions that unwind to the caller
647are hooked up to unwind to the unwind destination of the call site.
Reid Klecknerfc573f332015-08-06 21:01:32 +0000648
649Putting things together, here is a hypothetical lowering of some C++ that uses
650all of the new IR instructions:
651
652.. code-block:: c
653
654 struct Cleanup {
655 Cleanup();
656 ~Cleanup();
657 int m;
658 };
659 void may_throw();
660 int f() noexcept {
661 try {
662 Cleanup obj;
663 may_throw();
664 } catch (int e) {
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000665 may_throw();
Reid Klecknerfc573f332015-08-06 21:01:32 +0000666 return e;
667 }
668 return 0;
669 }
670
671.. code-block:: llvm
672
673 define i32 @f() nounwind personality i32 (...)* @__CxxFrameHandler3 {
674 entry:
675 %obj = alloca %struct.Cleanup, align 4
676 %e = alloca i32, align 4
677 %call = invoke %struct.Cleanup* @"\01??0Cleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj)
678 to label %invoke.cont unwind label %lpad.catch
679
680 invoke.cont: ; preds = %entry
681 invoke void @"\01?may_throw@@YAXXZ"()
682 to label %invoke.cont.2 unwind label %lpad.cleanup
683
684 invoke.cont.2: ; preds = %invoke.cont
685 call void @"\01??_DCleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj) nounwind
686 br label %return
687
David Majnemer8a1c45d2015-12-12 05:38:55 +0000688 return: ; preds = %invoke.cont.3, %invoke.cont.2
689 %retval.0 = phi i32 [ 0, %invoke.cont.2 ], [ %3, %invoke.cont.3 ]
Reid Klecknerfc573f332015-08-06 21:01:32 +0000690 ret i32 %retval.0
691
David Majnemer8a1c45d2015-12-12 05:38:55 +0000692 lpad.cleanup: ; preds = %invoke.cont.2
693 %0 = cleanuppad within none []
694 call void @"\01??1Cleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj) nounwind
695 cleanupret %0 unwind label %lpad.catch
Reid Klecknerfc573f332015-08-06 21:01:32 +0000696
David Majnemer8a1c45d2015-12-12 05:38:55 +0000697 lpad.catch: ; preds = %lpad.cleanup, %entry
698 %1 = catchswitch within none [label %catch.body] unwind label %lpad.terminate
Reid Klecknerfc573f332015-08-06 21:01:32 +0000699
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000700 catch.body: ; preds = %lpad.catch
David Majnemer8a1c45d2015-12-12 05:38:55 +0000701 %catch = catchpad within %1 [%rtti.TypeDescriptor2* @"\01??_R0H@8", i32 0, i32* %e]
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000702 invoke void @"\01?may_throw@@YAXXZ"()
David Majnemer8a1c45d2015-12-12 05:38:55 +0000703 to label %invoke.cont.3 unwind label %lpad.terminate
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000704
705 invoke.cont.3: ; preds = %catch.body
David Majnemer8a1c45d2015-12-12 05:38:55 +0000706 %3 = load i32, i32* %e, align 4
707 catchret from %catch to label %return
Reid Klecknerfc573f332015-08-06 21:01:32 +0000708
David Majnemer8a1c45d2015-12-12 05:38:55 +0000709 lpad.terminate: ; preds = %catch.body, %lpad.catch
710 terminatepad within none [void ()* @"\01?terminate@@YAXXZ"] unwind to caller
Reid Klecknerfc573f332015-08-06 21:01:32 +0000711 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000712
713Funclet parent tokens
714-----------------------
715
716In order to produce tables for EH personalities that use funclets, it is
717necessary to recover the nesting that was present in the source. This funclet
718parent relationship is encoded in the IR using tokens produced by the new "pad"
719instructions. The token operand of a "pad" or "ret" instruction indicates which
720funclet it is in, or "none" if it is not nested within another funclet.
721
722The ``catchpad`` and ``cleanuppad`` instructions establish new funclets, and
723their tokens are consumed by other "pad" instructions to establish membership.
724The ``catchswitch`` instruction does not create a funclet, but it produces a
725token that is always consumed by its immediate successor ``catchpad``
726instructions. This ensures that every catch handler modelled by a ``catchpad``
727belongs to exactly one ``catchswitch``, which models the dispatch point after a
728C++ try. The ``terminatepad`` instruction cannot contain lexically nested
729funclets inside the termination action, so it does not produce a token.
730
731Here is an example of what this nesting looks like using some hypothetical
732C++ code:
733
734.. code-block:: c
735
736 void f() {
737 try {
738 throw;
739 } catch (...) {
740 try {
741 throw;
742 } catch (...) {
743 }
744 }
745 }
746
747.. code-block:: llvm
David Majnemer496842f2015-12-12 06:56:02 +0000748
David Majnemer8a1c45d2015-12-12 05:38:55 +0000749 define void @f() #0 personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*) {
750 entry:
751 invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1
752 to label %unreachable unwind label %catch.dispatch
753
754 catch.dispatch: ; preds = %entry
755 %0 = catchswitch within none [label %catch] unwind to caller
756
757 catch: ; preds = %catch.dispatch
758 %1 = catchpad within %0 [i8* null, i32 64, i8* null]
759 invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1
760 to label %unreachable unwind label %catch.dispatch2
761
762 catch.dispatch2: ; preds = %catch
763 %2 = catchswitch within %1 [label %catch3] unwind to caller
764
765 catch3: ; preds = %catch.dispatch2
766 %3 = catchpad within %2 [i8* null, i32 64, i8* null]
767 catchret from %3 to label %try.cont
768
769 try.cont: ; preds = %catch3
770 catchret from %1 to label %try.cont6
771
772 try.cont6: ; preds = %try.cont
773 ret void
774
775 unreachable: ; preds = %catch, %entry
776 unreachable
777 }
778
779The "inner" ``catchswitch`` consumes ``%1`` which is produced by the outer
780catchswitch.