r/Compilers • • 22d ago

An alternative, allocation-free exception handling model designed for low-latency systems and kernels

https://jamsilva.github.io/posts/exciting-exception-excursions/

Hi everyone! In the post, I talk a bit about current implementations of exception handling and then I present a new one that I designed for my own programming language and could be used in places where exceptions usually have to be disabled, like kernels. Let me know your thoughts :)

24 Upvotes

17 comments sorted by

6

u/SwedishFindecanor 22d ago edited 22d ago

In the beginning, there were error codes

In the earliest systems programming languages with Exception Handling, it was a way to model hardware exceptions, such as e.g. division by zero, interrupts etc. That is what the name "Exception" comes from. On many processors, exception handler routines shares the stack with user-mode so when one is started it creates a new stack frame on the top of the stack. Each hardware exception type has a "vector", i.e. a pointer to its current handler function At the start of each "try block", you would save the old function and overwrite the vector. Then restore the old pointer value afterwards. Later, people came up with the idea of having software exception as well.

The model is as if you'd pass a handler forward down the stack instead of unwinding to the handler. In some languages the handler is a closure (with access to local variables in its context) which can resume execution to after where the exception was raised (raise can be an expression with a return value!), or it could choose to do a non-local return (unwinding) back to where the closure had been created.

Exception handling could still be zero-cost unless raised by having the runtime walking the stack and looking up metadata for each call site -- just like what most C++ runtimes do.

Instead, we reuse status flags via stc (Set Carry Flag):

Herb Sutter once proposed this method for C++'s runtime, but was voted down because it would break existing ABIs. The method is sometimes referred to as "herbceptions" :). It is also a very old assembly programming idiom.

Among rejected proposals for CLU's runtime (many years earlier) had been to have either an exception return address or a table with exception return addresses at a fixed offset from the normal return address.

4

u/WittyStick 22d ago edited 22d ago

The simplest way for compatibility with the existing ABIs is to just return a struct containing an exception ID, and the value (if no exception thrown), otherwise, an indeterminate value, but usually 0/NULL.

On SYSV, we can return 16-byte structures in registers - the first eightbytes get put in rax, the second eightbytes in rdx. x0, x1 for AARCH64, and similar for other architectures.

If our return value is just an integer or pointer, we don't need to touch the stack. It only gets put on the stack when our return value itself is larger than an eightbyte. (With struct packing we could potentially return a 112-bit value with a 16-bit exception id, but that also complicates and adds instructions to decode, for little gain).

I've made a trivial example in C on Godbolt - it uses some macro foo to implement a pseudo $try/$catch for the caller, and a pseudo $return/$throw for the callee (using a for block which only executes once).

Exceptional(long) test_func(bool throw) 
{
    if (throw)
        $throw(long, ExampleException);
    else
        $return(long, 12345678);
}

void print_exception(Exception ex) 
{
    fprintf
        ( stderr
        , "%s thrown from file %s, line %d"
        , exception_names[ex.id]
        , ex.info.filename
        , ex.info.line_no
        );
}

int main()
{
    $try(result, test_func(false)) // set to true to throw
    {
        printf("%d\n", result);
    }
    $catch(result, ex)
    {
        print_exception(ex);
    }

    return 0;
}

Yes, the macros are awful, but they're only to demonstrate a point on how you could add FFI compatibility with some safety (eg, not possible to use result in the catch block) - they cost nothing because the compiler optimizes them away.

If you look at the assembly output - there's basically almost no cost in the hot path (no exception thrown), other than a simple test and branch on the first return register (rax/x0), which will predict as not taken. Our successful value is returned in the second return register (rdx/x1)

"main":
        sub     rsp, 40                  ;; prologue

        mov     edi, 1
        call    "test_func"
        test    eax, eax
        jne     .L7                      ;; branch taken only if exception thrown
        
        mov     rsi, rdx                 ;; printf("%d\n", result);
        mov     edi, "%d\n"
        xor     eax, eax
        call    "printf"

.L8:                                     ;; epilogue (return 0;)
        xor     eax, eax                 
        add     rsp, 40
        ret
        
.L7:                                     ;; Exception handler (slow path)
        mov     DWORD PTR [rsp], eax
        mov     QWORD PTR [rsp+8], OFFSET FLAT:.LC2
        mov     DWORD PTR [rsp+16], 86
        cmp     eax, 2147483647    ;; PhonyException
        je      .L8
        sub     rsp, 32
        mov     rax, QWORD PTR [rsp+48]
        movdqa  xmm0, XMMWORD PTR [rsp+32]
        mov     QWORD PTR [rsp+16], rax
        movups  XMMWORD PTR [rsp], xmm0
        call    "print_exception"
        add     rsp, 32
        xor     eax, eax
        add     rsp, 40
        ret

You're unlikely to get cheaper than this. rdx is a caller-saved register anyway, so you can't expect whatever value it had before the call to test_func to be valid afterwards - you aren't losing anything by using it to return the value.

You could potentially improve on it for AARCH64 - because ARMs own convention permits for returning up to 8 values in registers. SYSV doesn't though - it stops at two like for x86-64.

3

u/mwksoul 22d ago

Wow, thanks for taking the time to write a Godbolt example and paste the assembly, that is pretty nice!

Funnily enough, you are exploring a path I considered earlier too. A bit earlier, my design used this exact 128-bit double-register return ABI (splitting the top and bottom halves for success vs failure). I eventually moved away from it and decided that both paths could share the same return registers, using a flag to flip the meaning. Here is why:

  1. The hidden stack penalty for large returns: The RAX + RDX trick works beautifully if you return a long or a pointer. But if your function needs to return a legitimate 16-byte struct on success, you've already burned both registers. System V will then force the compiler to drop down to a hidden pointer passed in RDI, causing hidden stack writes. By shifting the indicator to the Carry Flag (stc), the full 128-bit register space remains 100% available for the success payload, no matter its layout.
  2. Dropping the test instruction: In your assembly, you have a test eax, eax followed by a jne. With the Carry Flag, you skip the test completely. The caller just emits a single jc (Jump if Carry) immediately after the call. It saves an instruction slot at every single call site on the happy path.
  3. FFI considerations: It could make calling standard C functions cleaner at the code-gen level, since you don't have to force custom struct layouts across the boundary. And you'd have to do exception/error conversion at the FFI boundary either way because C++ wouldn't expect the flag/extra register and Menehune wouldn't expect the stack walk/personality functions.

Your macro setup is a beautiful proof of concept for C++, but since I'm planning to build the compiler from scratch, I can abuse the CPU flags directly in those cases.

2

u/mwksoul 22d ago

That's a nice piece of historical context, thanks for mentioning it. :)

And yeah, you caught me - Herb Sutter's P0709 proposal aka Herbceptions was a starting point for this mechanism. However, the architectural implementation under the hood should be quite a bit different in practice.

As far as I recall, P0709 relies on functions returning a rigid, deterministic type (essentially wrapping existing std::error_code structures) which forces you to declare the explicit error types upfront.

Menehune's model goes a step further by using link-time relocations for the Library ID. This means the exception registry can scale incrementally and support inheritance-like behaviors across isolated shared libraries without needing a central enum or a fixed static type mapping.

The other benefit is that by abusing the Carry Flag (or extra register) out-of-band, the usual return registers stay clean for the successful return, avoiding the encapsulation layout issues that the C++ committee spent years arguing about.

2

u/nculwell 22d ago

Seems to me that if you have structured payloads then you can still get dynamically formatted error messages if you want to. You could include a static format string with the exception. Then just do the actual formatting when it's time to print the message.

1

u/mwksoul 22d ago

I think I can see that, and it's a great point. If the static format string behaves like a type-safe printf blueprint, and the compiler is aware of the type invariants at the call-site, it could generate the code to pull the raw bytes from the structured payload and feed them into the formatter when it's actually time to print.

Since the 64-bit ID already packs a Source ID (which points to the exact line/metadata), we could potentially use that to resolve the matching format string at runtime without adding any dynamic string-building overhead during the throw itself. Something like that?

2

u/tending 21d ago

This isn't zero cost in the happy path. Traditional exceptions are zero cost in the happy path precisely because they don't need branching to check for flags or sentinel values. Branch prediction reduces the cost, but it's not free.

1

u/mwksoul 21d ago

That's a fair point when you're considering the Itanium ABI, but the whole debate around 'zero-cost' on the happy path has some more nuance to it in practice.

First off, for functions that don't throw and don't call throwing functions, the cost in Menehune is rigorously zero. Since non-throwing is our default - unlike C++, where the compiler assumes everything can throw unless it's explicitly marked noexcept - the code produced is "optimal". No branches, flag checks, static metadata overhead and so on; just raw C-style performance.

Second, even where throwing functions are involved, the cost of checking the in-flight indicator (via the Carry Flag or dedicated register) is low compared to the other two main models (Rust's viral Result wrappers or C++'s massive tables). On top of that, it's WAY cheaper and more predictable than the traditional setjmp/longjmp fallback, which forces you to save the entire CPU register state to memory and is still used in some (admittedly rare) C++ implementations and platforms.

The Itanium ABI sells the illusion of zero-cost on the happy path by hiding massive .eh_frame tables out of band, but it pays for it by crippling aggressive compiler optimizations because the middle-end can't reorder instructions freely across potential unwind boundaries. In Menehune, we prefer mechanical honesty: the cost is local, predictable, and modern CPU branch predictors should melt right through those flag checks on the happy path anyway.

1

u/tending 21d ago

First off, for functions that don't throw and don't call throwing functions, the cost in Menehune is rigorously zero.

Yes but they also would be in Rust with panic=abort or even C++ if nothrow is sprinkled appropriately. The case where throwing is actually possible still has a branch that the exception code does not.

is low compared to the other two main models (Rust's viral Result wrappers or C++'s massive tables).

It's low by comparison on the unhappy path, but it's still significant more than exceptions on the happy path, that's my point. The whole "exceptions should be exceptional" mantra is partly because of this -- if they're happening frequently they're the wrong tool. So if you've written code where they are genuinely infrequent, the happy path is the common case, and there C++ will be faster.

and modern CPU branch predictors should melt right through those flag checks on the happy path anyway.

All your functions are longer because of the branching, and longer functions are bigger, and then because they're bigger they don't get inlined, and then you're back to losing out of optimizations just for a different reason.

1

u/mwksoul 21d ago

Yes but they also would be in Rust with panic=abort or even C++ if nothrow is sprinkled appropriately.

I'll start by arguing that just the fact that noexcept is not the default in C++ makes it highly likely to miss optimizations in real-world code because developers will forget it. I try to be careful about performance and I still forget it all the time. The same goes for const, which is why both are the default in Menehune.

The case where throwing is actually possible still has a branch that the exception code does not.

Ok, sure, 'zero-cost' might be slightly overselling it from that strict, pure micro-benchmark POV. Let's call it near-zero then ;)

The whole "exceptions should be exceptional" mantra is partly because of this -- if they're happening frequently they're the wrong tool.

To play a bit of devil's advocate here: considering how common it is to see developers using exceptions as a means of control flow or a desperate 'bail-out' (especially in higher-level languages), perhaps the 'exceptional' mantra is more of a workaround for the fact that traditional implementations are so slow, rather than a universal law of software design. Making both paths fast lowers that cognitive tax.

All your functions are longer because of the branching, and longer functions are bigger, and then because they're bigger they don't get inlined

I think you might be under the impression that explicit checking and branching must be inserted for every single function layer all the way up the call stack until it is handled. That's not the case. For example, if the potentially-exceptional call is a tail call and the caller itself is marked throw (and not currently inside a try block), the compiler doesn't emit any checking code at all. It just propagates the return directly, keeping the function small and perfectly eligible for inlining.

1

u/padfoot9446 22d ago

i don’t see how this is substantially different to rust. A single ? per call isn’t much of a hassle; marking the function throw is no different to -> Result<T, int> (or a massive enum table, or anyhow instead of int).

2

u/mwksoul 22d ago

Depends on what you're looking at.

From a performance point of view it should be pretty similar - both avoid heap allocations. But under the hood, Rust's Result changes the actual size of the return type payload on the stack. If you return a large struct, wrapping it in a Result adds padding and layout pressure unless you box it.

If you look at ergonomics though, I find try-catch blocks way nicer to use than the functional style used in Rust where you have to sprinkle ? at every single call site.

The big architectural difference though is the linker part. Rust forces you to either declare a massive enum upfront (which is rigid) or use something like anyhow (which drops down to vtables and dynamic traits). Using linker relocations for the Library ID means the exception list can build up incrementally across different modules and shared libraries without needing a central enum or dynamic runtime registration. You get extensibility but it stays O(1) and static.

1

u/EggplantExtra4946 22d ago

places where exceptions usually have to be disabled, like kernels.

You're talking about exceptions as if they were interrupts. They are not the same thing.

1

u/mwksoul 21d ago

Exceptions and interrupts are quite different indeed. I did mean the case where you need to use -fno-exceptions flag to the compiler to completely disable the language's exception handling runtime though.

In environments like OS kernels or real-time embedded drivers (like macOS DriverKit), you really can't use C++ exceptions. The reasons are:

  1. Dynamic Allocation vs Memory Exhaustion: Standard exceptions often require allocating the exception object on the heap. If you are throwing an exception because the system is out of memory, the exception allocation itself will crash the kernel. You can't have non-deterministic allocations inside an ISR or core driver path.
  2. Unpredictable Latency: Walking the stack via .eh_frame tables is slow and non-deterministic. Kernels and low-latency systems need O(1) execution guarantees.

If you want a software abstraction that behaves like hardware interrupts, you look at POSIX signals - not that I think that's what you were asking; I believe you were just mentioning how sometimes you need to disable interrupts to handle things that need to be atomic.

1

u/severelywrong 19d ago

Hey, you mention that the Library ID is assigned at load time via relocation. I have a rough understanding of how relocation works, and would be very interested how one can derive a unique 16 bit value with it!

2

u/mwksoul 19d ago

Great question!
Relocations are basically a means of doing basic calculations at link/load time. In this case, we add a global Library ID variable to each library and ask the loader to initialize it with a monotonically increasing value.
We do it this way because Library IDs must identify the library where the exception type was declared, not where it was thrown (otherwise two libraries throwing the same imported exception wouldn't produce matching IDs in a catch block).
Then the exception value is built by just OR-ing the right Library ID global variable into place, which is pretty cheap at runtime.

1

u/severelywrong 18d ago

Thank you!