6 ms·
I understand why it's there, but I do find it fun that when many people are trying to reduce undefined behaviour in their code, std::unreachable is literally de
by CJefferson 4y ago
I understand why it's there, but I do find it fun that when many people are trying to reduce undefined behaviour in their code, std::unreachable is literally defined as "this is undefined behaviour, use that to optimise".
I suspect 99.9% of uses of std::unreachable would be better replaced by abort. (There will be those times when the code is correct and the optimisation gains are worth it -- but they will be rare).
- actionfromafar 4y ago+100 I felt physically ill when I read: It’s intended to be used when you know you have an execution path in your code that cannot be reached but the compiler cannot figure that out. It felt like saying to the compiler, "please, find a way to make my program break even more easily". Exactly not what I need.
- gpderetta 4y agoYou might not need it, but gcc/clang have __builtin_unreachable and msvc has __assume and both are used extensively for optimizations. std::unreachable is just standardizing existing diverging practice.
- fluoridation 4y agoIf a code path that's supposed to be unreachable is reached then the program is already broken. Unless it has a bug, a compiler will not make a program more broken. At worst (or best, depending on how you look at it) it will only make any bugs it already has more obvious.
- actionfromafar 4y agoYes, but what was unreachable may get reachable as I do changes to the program. I see the utility when doing highly optimized library code. But for my purposes I much prefer to stick something which flags me (exception or logging or whatever) of "this should never happen" instead of crashing. (Undefined.)
- dahfizz 4y agoIn a real codebase, this would be wrapped by a macro to abort in a debug build but gain the optimizations in a release build.
- eco 4y agocppreference suggests this as an implementation for std::unreachable but as near as I can tell neither clang nor MSVC does that (yet?).
- leni536 4y agoI would have expected the _LIBCXX_ASSERTIONS macro in libc++ to affect the behavior, similarly to many other standard library undefined behaviors.
- actionfromafar 4y agoCan't help but feel offended that my codebase isn't real. Thanks for the laugh though :-D I'd rather have solid logging and/or abort handling than some extra yak hairs shaved off the speed on my release builds. I'm weird that way.
- assbuttbuttass 4y agoIt's undefined behavior. The compiler is free to do whatever, including making your program more broken.
- fluoridation 4y agoIf you have undefined behavior, your program is already broken. No such thing as "more broken"; there's already no theoretical limit to what might happen if it gets triggered.
- carstimon 4y agoUndefined behavior is considered worse than crashing, which is typically the alternative when reaching "unreachable" codepaths. Compare these two blocks similar to the article switch (ch) { case 'a': do_a(); return; case 'd': do_d(); return; // ch is guaranteed to be 'a' or 'd' by previous code. default: assert(0); } switch (ch) { case 'a': do_a(); return; case 'd': do_d(); return; default: std::unreachable(); } If the programmer is wrong about `ch` in the first one, the program terminates. For the second one, the compiler could change it to be equivalent to if (ch == 'a') { do_a(); } else { do_d(); } return; If the programmer is wrong here, the program might `do_d()` with unintended consequences. I'd say "going down unintended codepaths" is typically considered worse than crashing. N.b. fixed last code example- thanks afiori.
- randomNumber7 4y agoI get your point, but assert is usually removed in release builds. Abort would probably be better if you want to crash the program.
- afiori 4y agoI suspect you meant to omit the `if (c == 'd')` part in the last example
- mannykannot 4y agoI take your point, but you can get the behavior of your first example, while still marking the default branch with std::unreachable(), by asserting the preconditions before the switch. This seems to me to be a pretty general equivalence. So what does std::unreachable() do here? In this particular case, and with NDEBUG defined and any level of optimization selected, I suspect that, at a minimum, the switch would be replaced as you have shown in all versions - it would take a more complex example to show how std::unreachable() makes a difference. The point is, now we have a choice - and it is one that is being offered without creating any backwards-compatibility issues. Furthermore, the original function, without assertions, is not guaranteed to crash, with or without std::unreachable(). You need some explicit checks to get a desirable response in the case where a mistake has been made, and that option is just as available whether or not you use std::unreachable(). Therefore, while I agree you have shown that not all broken variants of a given program are equivalent, this does not show that std::unreachable() is harmful.
- DougBTX 4y ago> At worst (or best, depending on how you look at it) it will only make any bugs it already has more obvious. An abort would make them obvious, surely unreachable makes them less obvious?
- fluoridation 4y agoThe point is that you're telling the compiler "I don't care what happens if control reaches here. Assume it never will and use that information to better optimize the rest". It's not an alternative to abort() or throwing because the compiler still needs to generate code for them.
- DougBTX 4y agoYes, that’s what I mean, the compiler can completely remove a branch which is unreachable, along with any checks. If it was forced to keep the checks and report an error instead, any bug would be more obvious. If the compiler removes checks for bugs, then the application could silently continue, obscuring the bug. So this is a “hide bugs but maybe improve performance” function.
- fluoridation 4y agoNo, it doesn't hide bugs. It has no defined effect on the obviousness of bugs. The reason is that modern compilers are pretty much theorem solvers, and they're able to propagate truth values in order to deduce facts about programs. For example, a compiler could deduce that since a branch is never reached, a particular pointer is never null, and could therefore skip a null check that it deduced was redundant that would have prevented a null dereference. If it turns out that the branch is reachable and the pointer is null, the pointer would be dereferenced and the program would crash immediately (typically). But UB is UB; once you hit it all behaviors are permissible, from immediate crash, to silent data corruption, to nasal demons.
- apaprocki 4y agoOne thing people are missing is that you may need to use this to satisfy conditions that the compiler might encounter to emit a warning (or error if equivalent of -Werror is enabled). If you have strict warnings on, but no way to tell the compiler that a location should not be reachable, you wind up in situations where you are doing something like `assert(!"not reached!")` and it won't be enabled in all build types. This is similar to how `__attribute__((noreturn))` is used in a "fatal" function that isn't always enabled but needs to convey its intention to static analyzers so that they stop evaluating branches past that call.
- gpderetta 4y agoFor that abort() is just fine. Being UB, unreachable is more about optimizations .
- dahfizz 4y ago>> and it won't be enabled in all build types. The typical usecase would to wrap this in a #define, so that it aborts on a debug build but you get faster code in a production build.
- deleted 4y ago[deleted]
- apaprocki 4y agoThe literal example in the Clang documentation is not about optimization: > For example, without the __builtin_unreachable in the example below, the compiler assumes that the inline asm can fall through and prints a “function declared ‘noreturn’ should not return” warning. void myabort(void) __attribute__((noreturn)); void myabort(void) { asm("int3"); __builtin_unreachable(); }
- a1369209993 4y ago> the compiler assumes that the inline asm can fall through and prints a "function declared 'noreturn' should not return" warning. It actually can (Hint: what happens if the operating system `iret`s from its int 3 handler?), although it's probably not a issue in practice. Regardless, you don't need __builtin_unreachable to write: void myabort(void) __attribute__((noreturn)); void myabort(void) { asm("int3"); myabort(); // might need `return myabort();` to force TCO, // but gcc doesn't like that and it should work anyway } # Assuming tail-call optimization etcetera, this produces: myabort: int3 jmp myabort which is a correct implementation. However, if you're implementing built-in/standard functions like abort, you presumably know what compiler you're using and don't need a std interface in the first place. There's zero legitimate reason to use a undefined-behaviour-based `unreachable` in application code. Claiming std::unreachable is useful for implementing abort is like proposing a std::manual_copy function because your compiler optimized a implementation of memcpy to a call to itself - at some point you do in fact have to resort to implementaion-specific details to define the abstractions that abstract away said details, and "in literally the same function as the (also-nonstandard, IIRC) inline assembly that hopefully doesn't return" seems at if not noticeably past that point.
- suyjuris 4y agoYou can compromise by using abort in debug builds and std::unreachable in release builds.
- apaprocki 4y agoThe point of this is that you can control that behavior at the compiler level using different flags instead of changing the code itself (via preprocessor defines).
- JonChesterfield 4y agoI love it when switching debug mode on changes the control flow graph of my program. Keeps life interesting.
- gpderetta 4y agowell, that's already the case.
- pif 4y agoThen just use abort!
- flohofwoe 4y agoIt's been useful to me in one very specific place so far: to remove a range-check in front of the jump-table lookup in a big switch-case statement. For 'very hot' code paths like in the instruction decoder of an emulator or interpreting byte-code VM this might actually translate to a measurable difference. In debug mode it makes a lot of sense to replace the __builtin_unreachable with an abort() though.
- usefulcat 4y ago> this is undefined behaviour, use that to optimise Optimization is a very large part of the reason for having undefined behavior at all. Viewed from that perspective, I don’t see how the existence of std::unreachable is at all odd. Also, it’s not like anyone is required to use it.
- ho_schi 4y agohttps://gcc.gnu.org/onlinedocs/gcc/extensions-to-the-c-language-family/other-built-in-functions-provided-by-gcc.html#_CPPv421__builtin_unreachablev https://gcc.gnu.org/onlinedocs/gcc/extensions-to-the-c-langu... The rational is better explained there :) Most programmers will write an error message and halt execution flow (return EXIT_FAILURE, abort(), exit() or even an exception). The hint about assembler give cares about special (maybe optimized or machine specific) code or embedded stuff. And the second example refers explicitly to functions which do exit() and never return actually. The committee tidies up stuff. Something which compilers provide individually is becoming standard.