Raymond Chen's take on so-called zero cost exceptions

deadalnix deadalnix at gmail.com
Tue Mar 1 12:51:08 UTC 2022


On Tuesday, 1 March 2022 at 05:06:22 UTC, Elronnd wrote:
> On Tuesday, 1 March 2022 at 01:39:05 UTC, deadalnix wrote:
>> obj can be kept in a register in the goto case, it cannot in 
>> the exception case. So you'll have a couple extra load/store 
>> vs extra branches.
>
> Nope, it can be kept in a register in the exception case too.  
> See: https://godbolt.org/z/zP1P3xvr3
>
> The pushes and pops of RBX are necessary in both cases, because 
> it is a caller-saved register.  (And, well, they are also 
> necessary for stack alignment, so be wary of taking too many 
> conclusions from a microbenchmark.)  Beyond that, note that the 
> exception-using versions have fewer instructions in the hot 
> path, fewer branches, and exactly the same number of memory 
> accesses as the manually-checking versions.
>
> (GCC generates better code, but clang's implementation of 'h' 
> is more representative, which is why I show both; *usually* you 
> can't run both the happy path and the sad path branchlessly.)

I'm not sure that gcc's code is actually better, it's pretty much 
the same, with the cold section split out. The only notable 
difference in is to use add/mov vs lea for gcc.

Interestingly, i submitted a patch to split exception code in 
cold section for LLVM the way GCC does it, but it ended up not 
being merged :/

In any case, your example show that even in the presence of 
exception, register promotion is still possible, which I think 
strengthen my original point: of all the solutions available, 
exception are the one that imposes the smallest cost on the non 
exception path.


More information about the Digitalmars-d mailing list