1 ==========================
2 Exception Handling in LLVM
3 ==========================
11 This document is the central repository for all information pertaining to
12 exception handling in LLVM. It describes the format that LLVM exception
13 handling information takes, which is useful for those interested in creating
14 front-ends or dealing directly with the information. Further, this document
15 provides specific examples of what exception handling information is used for in
18 Itanium ABI Zero-cost Exception Handling
19 ----------------------------------------
21 Exception handling for most programming languages is designed to recover from
22 conditions that rarely occur during general use of an application. To that end,
23 exception handling should not interfere with the main flow of an application's
24 algorithm by performing checkpointing tasks, such as saving the current pc or
27 The Itanium ABI Exception Handling Specification defines a methodology for
28 providing outlying data in the form of exception tables without inlining
29 speculative exception handling code in the flow of an application's main
30 algorithm. Thus, the specification is said to add "zero-cost" to the normal
31 execution of an application.
33 A more complete description of the Itanium ABI exception handling runtime
34 support of can be found at `Itanium C++ ABI: Exception Handling
35 <http://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html>`_. A description of the
36 exception frame format can be found at `Exception Frames
37 <http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html>`_,
38 with details of the DWARF 4 specification at `DWARF 4 Standard
39 <http://dwarfstd.org/Dwarf4Std.php>`_. A description for the C++ exception
40 table formats can be found at `Exception Handling Tables
41 <http://itanium-cxx-abi.github.io/cxx-abi/exceptions.pdf>`_.
43 Setjmp/Longjmp Exception Handling
44 ---------------------------------
46 Setjmp/Longjmp (SJLJ) based exception handling uses LLVM intrinsics
47 `llvm.eh.sjlj.setjmp`_ and `llvm.eh.sjlj.longjmp`_ to handle control flow for
50 For each function which does exception processing --- be it ``try``/``catch``
51 blocks or cleanups --- that function registers itself on a global frame
52 list. When exceptions are unwinding, the runtime uses this list to identify
53 which functions need processing.
55 Landing pad selection is encoded in the call site entry of the function
56 context. The runtime returns to the function via `llvm.eh.sjlj.longjmp`_, where
57 a switch table transfers control to the appropriate landing pad based on the
58 index stored in the function context.
60 In contrast to DWARF exception handling, which encodes exception regions and
61 frame information in out-of-line tables, SJLJ exception handling builds and
62 removes the unwind frame context at runtime. This results in faster exception
63 handling at the expense of slower execution when no exceptions are thrown. As
64 exceptions are, by their nature, intended for uncommon code paths, DWARF
65 exception handling is generally preferred to SJLJ.
67 Windows Runtime Exception Handling
68 -----------------------------------
70 LLVM supports handling exceptions produced by the Windows runtime, but it
71 requires a very different intermediate representation. It is not based on the
72 ":ref:`landingpad <i_landingpad>`" instruction like the other two models, and is
73 described later in this document under :ref:`wineh`.
78 When an exception is thrown in LLVM code, the runtime does its best to find a
79 handler suited to processing the circumstance.
81 The runtime first attempts to find an *exception frame* corresponding to the
82 function where the exception was thrown. If the programming language supports
83 exception handling (e.g. C++), the exception frame contains a reference to an
84 exception table describing how to process the exception. If the language does
85 not support exception handling (e.g. C), or if the exception needs to be
86 forwarded to a prior activation, the exception frame contains information about
87 how to unwind the current activation and restore the state of the prior
88 activation. This process is repeated until the exception is handled. If the
89 exception is not handled and no activations remain, then the application is
90 terminated with an appropriate error message.
92 Because different programming languages have different behaviors when handling
93 exceptions, the exception handling ABI provides a mechanism for
94 supplying *personalities*. An exception handling personality is defined by
95 way of a *personality function* (e.g. ``__gxx_personality_v0`` in C++),
96 which receives the context of the exception, an *exception structure*
97 containing the exception object type and value, and a reference to the exception
98 table for the current function. The personality function for the current
99 compile unit is specified in a *common exception frame*.
101 The organization of an exception table is language dependent. For C++, an
102 exception table is organized as a series of code ranges defining what to do if
103 an exception occurs in that range. Typically, the information associated with a
104 range defines which types of exception objects (using C++ *type info*) that are
105 handled in that range, and an associated action that should take place. Actions
106 typically pass control to a *landing pad*.
108 A landing pad corresponds roughly to the code found in the ``catch`` portion of
109 a ``try``/``catch`` sequence. When execution resumes at a landing pad, it
110 receives an *exception structure* and a *selector value* corresponding to the
111 *type* of exception thrown. The selector is then used to determine which *catch*
112 should actually process the exception.
117 From 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
119 implementation of LLVM exception handling in terms of C++ examples.
124 Languages that support exception handling typically provide a ``throw``
125 operation to initiate the exception process. Internally, a ``throw`` operation
126 breaks down into two steps.
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.
132 #. A call is made to the runtime to raise the exception, passing the exception
133 structure as an argument.
135 In C++, the allocation of the exception structure is done by the
136 ``__cxa_allocate_exception`` runtime function. The exception raising is handled
137 by ``__cxa_throw``. The type of the exception is represented using a C++ RTTI
143 A call within the scope of a *try* statement can potentially raise an
144 exception. In those circumstances, the LLVM C++ front-end replaces the call with
145 an ``invoke`` instruction. Unlike a call, the ``invoke`` has two potential
148 #. where to continue when the call succeeds as per normal, and
150 #. where to continue if the call raises an exception, either by a throw or the
153 The term used to define the place where an ``invoke`` continues after an
154 exception is called a *landing pad*. LLVM landing pads are conceptually
155 alternative function entry points where an exception structure reference and a
156 type info index are passed in as arguments. The landing pad saves the exception
157 structure reference and then proceeds to select the catch block that corresponds
158 to the type info of the exception object.
160 The LLVM :ref:`i_landingpad` is used to convey information about the landing
161 pad to the back end. For C++, the ``landingpad`` instruction returns a pointer
162 and integer pair corresponding to the pointer to the *exception structure* and
163 the *selector value* respectively.
165 The ``landingpad`` instruction looks for a reference to the personality
166 function to be used for this ``try``/``catch`` sequence in the parent
167 function's attribute list. The instruction contains a list of *cleanup*,
168 *catch*, and *filter* clauses. The exception is tested against the clauses
169 sequentially from first to last. The clauses have the following meanings:
171 - ``catch <type> @ExcType``
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.
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
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
186 - ``filter <type> [<type> @ExcType1, ..., <type> @ExcTypeN]``
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).
192 - C++ front-ends use this to implement the C++ exception specifications, such as
193 "``void foo() throw (ExcType1, ..., ExcTypeN) { ... }``". (Note: this
194 functionality was deprecated in C++11 and removed in C++17.)
196 - When this clause is matched, the selector value will be negative.
198 - The array argument to ``filter`` may be empty; for example, "``[0 x i8**]
199 undef``". This means that the landingpad should always be entered. (Note
200 that such a ``filter`` would not be equivalent to "``catch i8* null``",
201 because ``filter`` and ``catch`` produce negative and positive selector
202 values respectively.)
206 - This clause means that the landingpad should always be entered.
208 - C++ front-ends use this for calling objects' destructors.
210 - When this clause is matched, the selector value will be zero.
212 - The runtime may treat "``cleanup``" differently from "``catch <type>
215 In C++, if an unhandled exception occurs, the language runtime will call
216 ``std::terminate()``, but it is implementation-defined whether the runtime
217 unwinds the stack and calls object destructors first. For example, the GNU
218 C++ unwinder does not call object destructors when an unhandled exception
219 occurs. The reason for this is to improve debuggability: it ensures that
220 ``std::terminate()`` is called from the context of the ``throw``, so that
221 this context is not lost by unwinding the stack. A runtime will typically
222 implement this by searching for a matching non-``cleanup`` clause, and
223 aborting if it does not find one, before entering any landingpad blocks.
225 Once the landing pad has the type info selector, the code branches to the code
226 for the first catch. The catch then checks the value of the type info selector
227 against the index of type info for that catch. Since the type info index is not
228 known until all the type infos have been gathered in the backend, the catch code
229 must call the `llvm.eh.typeid.for`_ intrinsic to determine the index for a given
230 type info. If the catch fails to match the selector then control is passed on to
233 Finally, the entry and exit of catch code is bracketed with calls to
234 ``__cxa_begin_catch`` and ``__cxa_end_catch``.
236 * ``__cxa_begin_catch`` takes an exception structure reference as an argument
237 and returns the value of the exception object.
239 * ``__cxa_end_catch`` takes no arguments. This function:
241 #. Locates the most recently caught exception and decrements its handler
244 #. Removes the exception from the *caught* stack if the handler count goes to
247 #. Destroys the exception if the handler count goes to zero and the exception
248 was not re-thrown by throw.
252 a rethrow from within the catch may replace this call with a
258 A cleanup is extra code which needs to be run as part of unwinding a scope. C++
259 destructors are a typical example, but other languages and language extensions
260 provide a variety of different kinds of cleanups. In general, a landing pad may
261 need to run arbitrary amounts of cleanup code before actually entering a catch
262 block. To indicate the presence of cleanups, a :ref:`i_landingpad` should have
263 a *cleanup* clause. Otherwise, the unwinder will not stop at the landing pad if
264 there are no catches or filters that require it to.
268 Do not allow a new exception to propagate out of the execution of a
269 cleanup. This can corrupt the internal state of the unwinder. Different
270 languages describe different high-level semantics for these situations: for
271 example, C++ requires that the process be terminated, whereas Ada cancels both
272 exceptions and throws a third.
274 When all cleanups are finished, if the exception is not handled by the current
275 function, resume unwinding by calling the :ref:`resume instruction <i_resume>`,
276 passing in the result of the ``landingpad`` instruction for the original
282 Prior to C++17, C++ allowed the specification of which exception types may be
283 thrown from a function. To represent this, a top level landing pad may exist to
284 filter out invalid types. To express this in LLVM code the :ref:`i_landingpad`
285 will have a filter clause. The clause consists of an array of type infos.
286 ``landingpad`` will return a negative value
287 if the exception does not match any of the type infos. If no match is found then
288 a call to ``__cxa_call_unexpected`` should be made, otherwise
289 ``_Unwind_Resume``. Each of these functions requires a reference to the
290 exception structure. Note that the most general form of a ``landingpad``
291 instruction can have any number of catch, cleanup, and filter clauses (though
292 having more than one cleanup is pointless). The LLVM C++ front-end can generate
293 such ``landingpad`` instructions due to inlining creating nested exception
299 The unwinder delegates the decision of whether to stop in a call frame to that
300 call frame's language-specific personality function. Not all unwinders guarantee
301 that they will stop to perform cleanups. For example, the GNU C++ unwinder
302 doesn't do so unless the exception is actually caught somewhere further up the
305 In order for inlining to behave correctly, landing pads must be prepared to
306 handle selector results that they did not originally advertise. Suppose that a
307 function catches exceptions of type ``A``, and it's inlined into a function that
308 catches exceptions of type ``B``. The inliner will update the ``landingpad``
309 instruction for the inlined landing pad to include the fact that ``B`` is also
310 caught. If that landing pad assumes that it will only be entered to catch an
311 ``A``, it's in for a rude awakening. Consequently, landing pads must test for
312 the selector results they understand and then resume exception propagation with
313 the `resume instruction <LangRef.html#i_resume>`_ if none of the conditions
316 Exception Handling Intrinsics
317 =============================
319 In addition to the ``landingpad`` and ``resume`` instructions, LLVM uses several
320 intrinsic functions (name prefixed with ``llvm.eh``) to provide exception
321 handling information at various points in generated code.
323 .. _llvm.eh.typeid.for:
325 ``llvm.eh.typeid.for``
326 ----------------------
330 i32 @llvm.eh.typeid.for(i8* %type_info)
333 This intrinsic returns the type info index in the exception table of the current
334 function. This value can be used to compare against the result of
335 ``landingpad`` instruction. The single argument is a reference to a type info.
337 Uses of this intrinsic are generated by the C++ front-end.
339 .. _llvm.eh.exceptionpointer:
341 ``llvm.eh.exceptionpointer``
342 ----------------------------
346 i8 addrspace(N)* @llvm.eh.padparam.pNi8(token %catchpad)
349 This intrinsic retrieves a pointer to the exception caught by the given
356 The ``llvm.eh.sjlj`` intrinsics are used internally within LLVM's
357 backend. Uses of them are generated by the backend's
358 ``SjLjEHPrepare`` pass.
360 .. _llvm.eh.sjlj.setjmp:
362 ``llvm.eh.sjlj.setjmp``
363 ~~~~~~~~~~~~~~~~~~~~~~~
367 i32 @llvm.eh.sjlj.setjmp(i8* %setjmp_buf)
369 For SJLJ based exception handling, this intrinsic forces register saving for the
370 current function and stores the address of the following instruction for use as
371 a destination address by `llvm.eh.sjlj.longjmp`_. The buffer format and the
372 overall functioning of this intrinsic is compatible with the GCC
373 ``__builtin_setjmp`` implementation allowing code built with the clang and GCC
376 The single parameter is a pointer to a five word buffer in which the calling
377 context is saved. The front end places the frame pointer in the first word, and
378 the target implementation of this intrinsic should place the destination address
379 for a `llvm.eh.sjlj.longjmp`_ in the second word. The following three words are
380 available for use in a target-specific manner.
382 .. _llvm.eh.sjlj.longjmp:
384 ``llvm.eh.sjlj.longjmp``
385 ~~~~~~~~~~~~~~~~~~~~~~~~
389 void @llvm.eh.sjlj.longjmp(i8* %setjmp_buf)
391 For SJLJ based exception handling, the ``llvm.eh.sjlj.longjmp`` intrinsic is
392 used to implement ``__builtin_longjmp()``. The single parameter is a pointer to
393 a buffer populated by `llvm.eh.sjlj.setjmp`_. The frame pointer and stack
394 pointer are restored from the buffer, then control is transferred to the
397 ``llvm.eh.sjlj.lsda``
398 ~~~~~~~~~~~~~~~~~~~~~
402 i8* @llvm.eh.sjlj.lsda()
404 For SJLJ based exception handling, the ``llvm.eh.sjlj.lsda`` intrinsic returns
405 the address of the Language Specific Data Area (LSDA) for the current
406 function. The SJLJ front-end code stores this address in the exception handling
407 function context for use by the runtime.
409 ``llvm.eh.sjlj.callsite``
410 ~~~~~~~~~~~~~~~~~~~~~~~~~
414 void @llvm.eh.sjlj.callsite(i32 %call_site_num)
416 For SJLJ based exception handling, the ``llvm.eh.sjlj.callsite`` intrinsic
417 identifies the callsite value associated with the following ``invoke``
418 instruction. This is used to ensure that landing pad entries in the LSDA are
419 generated in matching order.
424 There are two tables that are used by the exception handling runtime to
425 determine which actions should be taken when an exception is thrown.
427 Exception Handling Frame
428 ------------------------
430 An exception handling frame ``eh_frame`` is very similar to the unwind frame
431 used by DWARF debug info. The frame contains all the information necessary to
432 tear down the current frame and restore the state of the prior frame. There is
433 an exception handling frame for each function in a compile unit, plus a common
434 exception handling frame that defines information common to all functions in the
437 The format of this call frame information (CFI) is often platform-dependent,
438 however. ARM, for example, defines their own format. Apple has their own compact
439 unwind info format. On Windows, another format is used for all architectures
440 since 32-bit x86. LLVM will emit whatever information is required by the
446 An exception table contains information about what actions to take when an
447 exception is thrown in a particular part of a function's code. This is typically
448 referred to as the language-specific data area (LSDA). The format of the LSDA
449 table is specific to the personality function, but the majority of personalities
450 out there use a variation of the tables consumed by ``__gxx_personality_v0``.
451 There is one exception table per function, except leaf functions and functions
452 that have calls only to non-throwing functions. They do not need an exception
457 Exception Handling using the Windows Runtime
458 =================================================
460 Background on Windows exceptions
461 ---------------------------------
463 Interacting with exceptions on Windows is significantly more complicated than
464 on Itanium C++ ABI platforms. The fundamental difference between the two models
465 is that Itanium EH is designed around the idea of "successive unwinding," while
468 Under Itanium, throwing an exception typically involves allocating thread local
469 memory to hold the exception, and calling into the EH runtime. The runtime
470 identifies frames with appropriate exception handling actions, and successively
471 resets the register context of the current thread to the most recently active
472 frame with actions to run. In LLVM, execution resumes at a ``landingpad``
473 instruction, which produces register values provided by the runtime. If a
474 function is only cleaning up allocated resources, the function is responsible
475 for calling ``_Unwind_Resume`` to transition to the next most recently active
476 frame after it is finished cleaning up. Eventually, the frame responsible for
477 handling the exception calls ``__cxa_end_catch`` to destroy the exception,
478 release its memory, and resume normal control flow.
480 The Windows EH model does not use these successive register context resets.
481 Instead, the active exception is typically described by a frame on the stack.
482 In the case of C++ exceptions, the exception object is allocated in stack memory
483 and its address is passed to ``__CxxThrowException``. General purpose structured
484 exceptions (SEH) are more analogous to Linux signals, and they are dispatched by
485 userspace DLLs provided with Windows. Each frame on the stack has an assigned EH
486 personality routine, which decides what actions to take to handle the exception.
487 There are a few major personalities for C and C++ code: the C++ personality
488 (``__CxxFrameHandler3``) and the SEH personalities (``_except_handler3``,
489 ``_except_handler4``, and ``__C_specific_handler``). All of them implement
490 cleanups by calling back into a "funclet" contained in the parent function.
492 Funclets, in this context, are regions of the parent function that can be called
493 as though they were a function pointer with a very special calling convention.
494 The frame pointer of the parent frame is passed into the funclet either using
495 the standard EBP register or as the first parameter register, depending on the
496 architecture. The funclet implements the EH action by accessing local variables
497 in memory through the frame pointer, and returning some appropriate value,
498 continuing the EH process. No variables live in to or out of the funclet can be
499 allocated in registers.
501 The C++ personality also uses funclets to contain the code for catch blocks
502 (i.e. all user code between the braces in ``catch (Type obj) { ... }``). The
503 runtime must use funclets for catch bodies because the C++ exception object is
504 allocated in a child stack frame of the function handling the exception. If the
505 runtime rewound the stack back to frame of the catch, the memory holding the
506 exception would be overwritten quickly by subsequent function calls. The use of
507 funclets also allows ``__CxxFrameHandler3`` to implement rethrow without
508 resorting to TLS. Instead, the runtime throws a special exception, and then uses
509 SEH (``__try / __except``) to resume execution with new information in the child
512 In other words, the successive unwinding approach is incompatible with Visual
513 C++ exceptions and general purpose Windows exception handling. Because the C++
514 exception object lives in stack memory, LLVM cannot provide a custom personality
515 function that uses landingpads. Similarly, SEH does not provide any mechanism
516 to rethrow an exception or continue unwinding. Therefore, LLVM must use the IR
517 constructs described later in this document to implement compatible exception
520 SEH filter expressions
521 -----------------------
523 The SEH personality functions also use funclets to implement filter expressions,
524 which allow executing arbitrary user code to decide which exceptions to catch.
525 Filter expressions should not be confused with the ``filter`` clause of the LLVM
526 ``landingpad`` instruction. Typically filter expressions are used to determine
527 if the exception came from a particular DLL or code region, or if code faulted
528 while accessing a particular memory address range. LLVM does not currently have
529 IR to represent filter expressions because it is difficult to represent their
530 control dependencies. Filter expressions run during the first phase of EH,
531 before cleanups run, making it very difficult to build a faithful control flow
532 graph. For now, the new EH instructions cannot represent SEH filter
533 expressions, and frontends must outline them ahead of time. Local variables of
534 the parent function can be escaped and accessed using the ``llvm.localescape``
535 and ``llvm.localrecover`` intrinsics.
537 New exception handling instructions
538 ------------------------------------
540 The primary design goal of the new EH instructions is to support funclet
541 generation while preserving information about the CFG so that SSA formation
542 still works. As a secondary goal, they are designed to be generic across MSVC
543 and Itanium C++ exceptions. They make very few assumptions about the data
544 required by the personality, so long as it uses the familiar core EH actions:
545 catch, cleanup, and terminate. However, the new instructions are hard to modify
546 without knowing details of the EH personality. While they can be used to
547 represent Itanium EH, the landingpad model is strictly better for optimization
550 The following new instructions are considered "exception handling pads", in that
551 they must be the first non-phi instruction of a basic block that may be the
552 unwind destination of an EH flow edge:
553 ``catchswitch``, ``catchpad``, and ``cleanuppad``.
554 As with landingpads, when entering a try scope, if the
555 frontend encounters a call site that may throw an exception, it should emit an
556 invoke that unwinds to a ``catchswitch`` block. Similarly, inside the scope of a
557 C++ object with a destructor, invokes should unwind to a ``cleanuppad``.
559 New instructions are also used to mark the points where control is transferred
560 out of a catch/cleanup handler (which will correspond to exits from the
561 generated funclet). A catch handler which reaches its end by normal execution
562 executes a ``catchret`` instruction, which is a terminator indicating where in
563 the function control is returned to. A cleanup handler which reaches its end
564 by normal execution executes a ``cleanupret`` instruction, which is a terminator
565 indicating where the active exception will unwind to next.
567 Each of these new EH pad instructions has a way to identify which action should
568 be considered after this action. The ``catchswitch`` instruction is a terminator
569 and has an unwind destination operand analogous to the unwind destination of an
570 invoke. The ``cleanuppad`` instruction is not
571 a terminator, so the unwind destination is stored on the ``cleanupret``
572 instruction instead. Successfully executing a catch handler should resume
573 normal control flow, so neither ``catchpad`` nor ``catchret`` instructions can
574 unwind. All of these "unwind edges" may refer to a basic block that contains an
575 EH pad instruction, or they may unwind to the caller. Unwinding to the caller
576 has roughly the same semantics as the ``resume`` instruction in the landingpad
577 model. When inlining through an invoke, instructions that unwind to the caller
578 are hooked up to unwind to the unwind destination of the call site.
580 Putting things together, here is a hypothetical lowering of some C++ that uses
581 all of the new IR instructions:
604 define i32 @f() nounwind personality i32 (...)* @__CxxFrameHandler3 {
606 %obj = alloca %struct.Cleanup, align 4
607 %e = alloca i32, align 4
608 %call = invoke %struct.Cleanup* @"??0Cleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj)
609 to label %invoke.cont unwind label %lpad.catch
611 invoke.cont: ; preds = %entry
612 invoke void @"?may_throw@@YAXXZ"()
613 to label %invoke.cont.2 unwind label %lpad.cleanup
615 invoke.cont.2: ; preds = %invoke.cont
616 call void @"??_DCleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj) nounwind
619 return: ; preds = %invoke.cont.3, %invoke.cont.2
620 %retval.0 = phi i32 [ 0, %invoke.cont.2 ], [ %3, %invoke.cont.3 ]
623 lpad.cleanup: ; preds = %invoke.cont.2
624 %0 = cleanuppad within none []
625 call void @"??1Cleanup@@QEAA@XZ"(%struct.Cleanup* nonnull %obj) nounwind
626 cleanupret %0 unwind label %lpad.catch
628 lpad.catch: ; preds = %lpad.cleanup, %entry
629 %1 = catchswitch within none [label %catch.body] unwind label %lpad.terminate
631 catch.body: ; preds = %lpad.catch
632 %catch = catchpad within %1 [%rtti.TypeDescriptor2* @"??_R0H@8", i32 0, i32* %e]
633 invoke void @"?may_throw@@YAXXZ"()
634 to label %invoke.cont.3 unwind label %lpad.terminate
636 invoke.cont.3: ; preds = %catch.body
637 %3 = load i32, i32* %e, align 4
638 catchret from %catch to label %return
640 lpad.terminate: ; preds = %catch.body, %lpad.catch
641 cleanuppad within none []
642 call void @"?terminate@@YAXXZ"
646 Funclet parent tokens
647 -----------------------
649 In order to produce tables for EH personalities that use funclets, it is
650 necessary to recover the nesting that was present in the source. This funclet
651 parent relationship is encoded in the IR using tokens produced by the new "pad"
652 instructions. The token operand of a "pad" or "ret" instruction indicates which
653 funclet it is in, or "none" if it is not nested within another funclet.
655 The ``catchpad`` and ``cleanuppad`` instructions establish new funclets, and
656 their tokens are consumed by other "pad" instructions to establish membership.
657 The ``catchswitch`` instruction does not create a funclet, but it produces a
658 token that is always consumed by its immediate successor ``catchpad``
659 instructions. This ensures that every catch handler modelled by a ``catchpad``
660 belongs to exactly one ``catchswitch``, which models the dispatch point after a
663 Here is an example of what this nesting looks like using some hypothetical
681 define void @f() #0 personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*) {
683 invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1
684 to label %unreachable unwind label %catch.dispatch
686 catch.dispatch: ; preds = %entry
687 %0 = catchswitch within none [label %catch] unwind to caller
689 catch: ; preds = %catch.dispatch
690 %1 = catchpad within %0 [i8* null, i32 64, i8* null]
691 invoke void @_CxxThrowException(i8* null, %eh.ThrowInfo* null) #1
692 to label %unreachable unwind label %catch.dispatch2
694 catch.dispatch2: ; preds = %catch
695 %2 = catchswitch within %1 [label %catch3] unwind to caller
697 catch3: ; preds = %catch.dispatch2
698 %3 = catchpad within %2 [i8* null, i32 64, i8* null]
699 catchret from %3 to label %try.cont
701 try.cont: ; preds = %catch3
702 catchret from %1 to label %try.cont6
704 try.cont6: ; preds = %try.cont
707 unreachable: ; preds = %catch, %entry
711 The "inner" ``catchswitch`` consumes ``%1`` which is produced by the outer
714 .. _wineh-constraints:
717 -----------------------
719 The EH tables for personalities that use funclets make implicit use of the
720 funclet nesting relationship to encode unwind destinations, and so are
721 constrained in the set of funclet transitions they can represent. The related
722 LLVM IR instructions accordingly have constraints that ensure encodability of
723 the EH edges in the flow graph.
725 A ``catchswitch``, ``catchpad``, or ``cleanuppad`` is said to be "entered"
726 when it executes. It may subsequently be "exited" by any of the following
729 * A ``catchswitch`` is immediately exited when none of its constituent
730 ``catchpad``\ s are appropriate for the in-flight exception and it unwinds
731 to its unwind destination or the caller.
732 * A ``catchpad`` and its parent ``catchswitch`` are both exited when a
733 ``catchret`` from the ``catchpad`` is executed.
734 * A ``cleanuppad`` is exited when a ``cleanupret`` from it is executed.
735 * Any of these pads is exited when control unwinds to the function's caller,
736 either by a ``call`` which unwinds all the way to the function's caller,
737 a nested ``catchswitch`` marked "``unwinds to caller``", or a nested
738 ``cleanuppad``\ 's ``cleanupret`` marked "``unwinds to caller"``.
739 * Any of these pads is exited when an unwind edge (from an ``invoke``,
740 nested ``catchswitch``, or nested ``cleanuppad``\ 's ``cleanupret``)
741 unwinds to a destination pad that is not a descendant of the given pad.
743 Note that the ``ret`` instruction is *not* a valid way to exit a funclet pad;
744 it is undefined behavior to execute a ``ret`` when a pad has been entered but
747 A single unwind edge may exit any number of pads (with the restrictions that
748 the edge from a ``catchswitch`` must exit at least itself, and the edge from
749 a ``cleanupret`` must exit at least its ``cleanuppad``), and then must enter
750 exactly one pad, which must be distinct from all the exited pads. The parent
751 of the pad that an unwind edge enters must be the most-recently-entered
752 not-yet-exited pad (after exiting from any pads that the unwind edge exits),
753 or "none" if there is no such pad. This ensures that the stack of executing
754 funclets at run-time always corresponds to some path in the funclet pad tree
755 that the parent tokens encode.
757 All unwind edges which exit any given funclet pad (including ``cleanupret``
758 edges exiting their ``cleanuppad`` and ``catchswitch`` edges exiting their
759 ``catchswitch``) must share the same unwind destination. Similarly, any
760 funclet pad which may be exited by unwind to caller must not be exited by
761 any exception edges which unwind anywhere other than the caller. This
762 ensures that each funclet as a whole has only one unwind destination, which
763 EH tables for funclet personalities may require. Note that any unwind edge
764 which exits a ``catchpad`` also exits its parent ``catchswitch``, so this
765 implies that for any given ``catchswitch``, its unwind destination must also
766 be the unwind destination of any unwind edge that exits any of its constituent
767 ``catchpad``\s. Because ``catchswitch`` has no ``nounwind`` variant, and
768 because IR producers are not *required* to annotate calls which will not
769 unwind as ``nounwind``, it is legal to nest a ``call`` or an "``unwind to
770 caller``\ " ``catchswitch`` within a funclet pad that has an unwind
771 destination other than caller; it is undefined behavior for such a ``call``
772 or ``catchswitch`` to unwind.
774 Finally, the funclet pads' unwind destinations cannot form a cycle. This
775 ensures that EH lowering can construct "try regions" with a tree-like
776 structure, which funclet-based personalities may require.
778 Exception Handling support on the target
779 =================================================
781 In order to support exception handling on particular target, there are a few
782 items need to be implemented.
786 First, you have to assign each target register with a unique DWARF number.
787 Then in ``TargetFrameLowering``'s ``emitPrologue``, you have to emit `CFI
788 directives <https://sourceware.org/binutils/docs/as/CFI-directives.html>`_
789 to specify how to calculate the CFA (Canonical Frame Address) and how register
790 is restored from the address pointed by the CFA with an offset. The assembler
791 is instructed by CFI directives to build ``.eh_frame`` section, which is used
792 by th unwinder to unwind stack during exception handling.
794 * ``getExceptionPointerRegister`` and ``getExceptionSelectorRegister``
796 ``TargetLowering`` must implement both functions. The *personality function*
797 passes the *exception structure* (a pointer) and *selector value* (an integer)
798 to the landing pad through the registers specified by ``getExceptionPointerRegister``
799 and ``getExceptionSelectorRegister`` respectively. On most platforms, they
800 will be GPRs and will be the same as the ones specified in the calling convention.
804 The ISD node represents the undocumented GCC extension ``__builtin_eh_return (offset, handler)``,
805 which adjusts the stack by offset and then jumps to the handler. ``__builtin_eh_return``
806 is used in GCC unwinder (`libgcc <https://gcc.gnu.org/onlinedocs/gccint/Libgcc.html>`_),
807 but not in LLVM unwinder (`libunwind <https://clang.llvm.org/docs/Toolchain.html#unwind-library>`_).
808 If you are on the top of ``libgcc`` and have particular requirement on your target,
809 you have to handle ``EH_RETURN`` in ``TargetLowering``.
811 If you don't leverage the existing runtime (``libstdc++`` and ``libgcc``),
812 you have to take a look on `libc++ <https://libcxx.llvm.org/>`_ and
813 `libunwind <https://clang.llvm.org/docs/Toolchain.html#unwind-library>`_
814 to see what have to be done there. For ``libunwind``, you have to do the following
816 * ``__libunwind_config.h``
818 Define macros for your target.
820 * ``include/libunwind.h``
822 Define enum for the target registers.
824 * ``src/Registers.hpp``
826 Define ``Registers`` class for your target, implement setter and getter functions.
828 * ``src/UnwindCursor.hpp``
830 Define ``dwarfEncoding`` and ``stepWithCompactEncoding`` for your ``Registers``
833 * ``src/UnwindRegistersRestore.S``
835 Write an assembly function to restore all your target registers from the memory.
837 * ``src/UnwindRegistersSave.S``
839 Write an assembly function to save all your target registers on the memory.