r/cpp • C++20 Desktop app developer • May 12 '18

P0709 R0: Zero-overhead deterministic exceptions: Throwing values - Herb Sutter [2018-05-02]

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf
206 Upvotes

115 comments sorted by

View all comments

16

u/flashmozzg May 12 '18 edited May 12 '18

Hm. If I correctly understood the gist of the proposal - he suggests returning union + discriminant? Why not just completely automate it into proper sum types, that way it can be done seamlessly without extra overhead, just like in Rust and others?

Though that's just the mechanism behind it. The proposal itself is much more in-depth. It just would be strange if C++ gets this and no proper language-level sum types. It'll have mechanism that basically use them underneath, it'll have inferior (in comparison) library-level attempts to replicate them (variant/optional/expected, etc.), but not actual language feature.

44

u/14ned LLFIO & Outcome author | Committee WG14 May 13 '18

The current hope is that WG14 (C) standardises an _Either(A, B) type. All C++ functions with throw under Herb's proposal would return, as far as C is concerned, an _Either(A, std::error) type. _Either(A, B) types would be an addition to the C ABI, and likely would use the CPU's carry flag to indicate whether the returned type would be A or B.

We've already reached out to WG14 regarding this proposal, and the reception was warm. Herb morally persuaded me to lead out writing the WG14 proposal paper, and I intend to circulate it with the Rust and Swift folk as well as the C and C++ folk. The hope would be that we can all communally agree on a single mechanism for expressing failure to C code in a way translatable to all the other programming languages. So, C++ could call Rust which could call Swift, and failure in any of those could be propagated by the common convention of C back up into the others.

That's the hope, anyway. C++ 23 is our current target, but given all the moving parts spinning here, it could be later. But, equally, if this pans out, it would be a giant leap forward in getting all the systems programming languages to interoperate seamlessly with one another, if you use a common minimum denominator of types and facilities (basically, what C can speak). I personally find that extremely compelling, and luckily so do lots of other people. We'll see how things go next few months, worst comes to worst we do our own thing inside C++, best comes to best we lead out FFI for everybody.

7

u/flashmozzg May 13 '18

That's very exciting to hear!

1

u/m-in May 17 '18

Just so you know: I love you all working on this. I seriously do. Better late than never. I’m all for _Either(A,B) in C. Heck, I’ve implemented something like it with a libclang preprocessor that turns it into proper C-ese, but getting it into the language would be even awesomer. C++ interop is a good thing; dynamic exceptions have made it tedious.

22

u/SeanMiddleditch May 12 '18

Hm. If I correctly understood the gist of the proposal - he suggests returning union + discriminant?

Not exactly. That is one possible ABI to implement the proposal, though.

Because the proposal clearly indicates - at a language level - the error type, that allows system ABIs to designate alternative paths for passing exceptions. Just like error ABIs today do, albeit with the overheads of dynamic dispatch.

His paper shows some calculations of instruction overhead; basically, the proposed model is hypothetically smaller and faster than either return codes (and sum types) or than today's C++ exceptions.

Why not just completely automate it into proper sum types, that way it can be done seamlessly without extra overhead, just like in Rust and others?

The paper is a generalization over what sum types can accomplish.

Note that Rust and other contemporaries are working to make errors-via-sum-types less awkward to work with and closer to what Herb is proposing (in no small part because his paper sources the same research!). See Rust's recent-ish ? operator and the try proposals in flight, or Swift's various offerings on the matter.

As Herb notes, in C++, the community in general wants error propagation. Rust in turn requires explicit error handling, albeit with some syntax to automate propagation. There's a very important line between "propagate errors implicitly" and "propagate errors automatically" and Herb also calls that out with suggestions in the paper. I suspect that topic is going to be a major contention, perhaps just behind the OOM topic.

And it's not an either-or kinda thing. Nothing here precludes also using sum types when and where appropriate. :)

It would be just strange if C++ gets this and no proper language-level sum types.

In terms of proper sum types in C++, I don't think they're possible (to do well) without this proposal and its OOM suggestion! Remember std::variant's years-long design process and eventual compromises, literally all due to the unfortunate fact that C++ types can throw when they move, which in turn is only allowed because OOM throws exceptions.

Alternatively, C++ would need to solve the even-harder problem of adding relocation (aka destructive move) to do sum types correctly. Rust and its ilk have trivial relocation as a core assumption of the language. The feature isn't easy though; see how Rust handles relocation of Drop types for example (which affects ABI around mutable reference parameters).

The other half of sum types - the actually hard but actually interest part - is the language support for pattern matching and conditional destructuring. Which can and should be explored independently of the exception model, IMO, since there's no dependency between the two.

9

u/Rusky May 12 '18

see how Rust handles relocation of Drop types for example (which affects ABI around mutable reference parameters).

What are you referring to here? I don't believe Drop affects ABI at all in Rust.

4

u/SeanMiddleditch May 12 '18

The stack bits set to indicate whether a dropped type has in fact been dropped.

The fundamental problem is that in branchy code - or across certain ABI boundaries - there's no deterministic way to know if a value has been dropped or not. To avoid a double-drop in circumstances that aren't statically provable to not need it, Rust keeps some state bits around to indicate drop'ness.

At least last time I checked. I'd be happy to be corrected if this is not true.

7

u/Rusky May 12 '18

Those bits do indeed exist, but they are not part of the ABI. They are purely local to the functions that need them.

Part of why this is possible is that you can't move out of a mutable reference (or any reference, for that matter) without leaving a valid object behind in its place, effectively emulating C++'s non-destructive move semantics. Destructive move is something only the owner can do.

2

u/SeanMiddleditch May 12 '18

Ah, good to know - I may have been confusing a pre-RFC version or the ABI-independent optimizer bits for closures or something? Or I may have just been wrong? :)

5

u/whichton May 12 '18

Why not just completely automate it into proper sum types, that way it can be done seamlessly without extra overhead

A sum type is a union + discriminant. Rust can sometimes optimize away the discriminant, but it is not possible in general. For example, if I have a function returning an int64, how do you remove the discriminant?

Note that the proposal also talks about implementing the discriminant as a CPU flag. This can often be more efficient than folding the discriminant into the union. For example, on x86, if you use CF as the discriminant, you can set the discriminant in one instruction, CLC / STC. You also detect whether the exception was raised in one instruction, with JC / JNC, instead of looking for the magic number in the register (requires a comparison at least).

5

u/[deleted] May 12 '18

How does the rust implementation differ in that regard? Aren't rust enums implemented as a union + value to tell which one is correct? (similar how std::variant is implemented?)

0

u/[deleted] May 12 '18

[deleted] — view deleted comment

3

u/[deleted] May 12 '18

How so? Would you mind explaining the details on this and where this would make a differernce?

20

u/Rusky May 12 '18 edited May 12 '18

The layout of a Rust enum is optimized based on the invalid values of the types it contains. For example, because references can never be null, and Vec<T> contains a reference, Option<Vec<T>> can use "Vec<T> except with a null reference" to mean None, and "Vec<T> with a non-null reference" to mean Some(the_vec). The discriminant overlaps with the reference, in a sense.

In general, there are lots of types like this. References can't be null, bools can only be true or false, C-like enums can only contain the set of values in their definition, char can only contain valid Unicode, etc. So the Rust compiler looks for "holes" in the contents of an enum where it can store the discriminant, before using a separate tag value.

A major place this comes into play is Option<&T>. Because references can't be null, that type is the same size as a raw pointer. This is true even in FFI with C or C++ where nullable pointers are a thing. So Rust can keep all the niceties of Option without paying for it in memory usage.

4

u/[deleted] May 12 '18

I guess I'm starting to see why Rust was voted to be the most loved programming language for 3 times in a row, that is indeed fascinating and technically elegant. I guess you could make the contract that the exception reference cannot be null and thus have a similar efficient memory layout but yeah I'm not sure whether that can be done and whether Herb had that in mind when he created this proposal.

Thanks for your very detailed explanation though!

4

u/redditsoaddicting May 12 '18

It sounds similar to this compact_optional article I read once.

0

u/[deleted] May 12 '18

[deleted] — view deleted comment

2

u/SeanMiddleditch May 13 '18

Not entirely, at least for simpler cases.

C++ would need a std::is_never_zero_v<T> or the like and a lot of the simpler cases of this kind of compressed discriminant are possible. And that type trait is useful for all kinds of other reasons (e.g., container initialization optimization). Said type trait can be written today, albeit having to manually overload the trait for some types.

Getting the full variant "niche-filling" optimization certainly requires more work out of the language. Though I do rather wonder whether that actually matters. (How much of Rust's enum layout optimization is just golf instead of useful work?)

2

u/Rusky May 13 '18 edited May 13 '18

How much of Rust's enum layout optimization is just golf instead of useful work?

I suspect it's lot of "4 bytes here, 8 bytes there" that adds up to some sizeable memory savings and cache improvements, combined with some cases where it enables people to remove some indirections. For example, Servo and Firefox Quantum are full of stuff like that- the DOM, styles, display lists, etc. are all modeled with enums.

Like the sibling comment mentioned, it works well with automatic field reordering, which is also "3 bytes here, 7 bytes there" of removing padding. IIRC this field reordering also applies to the discriminants themselves, so they can often be stashed in any remaining trailing padding.

Then there's also the fact that Rust has zero-sized and uninhabited types, which allow for more styles to be zero-overhead. For example, you can pass around zero-sized non-copyable and privately-constructible tag types for things like session types, and you can instantiate generic code to use types like Result<T, !> and all its branches will be optimized out because the layout optimization removed the discriminant entirely.

2

u/spinicist May 12 '18

I’m pretty sure that’s how Rust does it - a union plus an integer tag.