I have seen this question which is about emulating __builtin_unreachable
in an older version of GCC. My question is exactly that, but for Visual Studio (2019). Does Visual Studio have some equivalent of __builtin_unreachable
? Is it possible to emulate it?
MSVC has the __assume builtin which can be used to implement __builtin_unreachable. As the documentation says, __assume (0) must not be in a reachable branch of code, which means, that branch must be unreachable. Show activity on this post.
Why: Improve readability and maintainability by removing code that is superfluous and will never be executed. Place your cursor anywhere in the faded out code that is unreachable: Press Ctrl +. to trigger the Quick Actions and Refactorings menu and select Remove unreachable code from the Preview window popup.
Calling __builtin_unreachable () is accepted by emcc, but the resulting wasm seems to contain nothing, rather than the expected unreachable instruction. It looks like that is lowered to an LLVM unreachable.
Since you want to have unreachable code to be omitted by compiler, below is the simplest way. Compiler optimizes away x = x; instruction especially when it's unreachable. Here is the usage: If you put __builtin_unreachable () in the beginning of foo () then compiler generates a linker error for unimplemented operator =.
By the way, before std::unreachable() is available you can implement it as a compiler-independent function, so that you don't have to define any macros:
#ifdef __GNUC__ // GCC 4.8+, Clang, Intel and other compilers compatible with GCC (-std=c++0x or above)
[[noreturn]] inline __attribute__((always_inline)) void unreachable() {__builtin_unreachable();}
#elif defined(_MSC_VER) // MSVC
[[noreturn]] __forceinline void unreachable() {__assume(false);}
#else // ???
inline void unreachable() {}
#endif
Usage:
int& g()
{
unreachable();
//no warning about a missing return statement
}
int foo();
int main()
{
int a = g();
foo(); //any compiler eliminates this call with -O1 so that there is no linker error about an undefined reference
return a+5;
}
MSVC has the __assume
builtin which can be used to implement __builtin_unreachable
. As the documentation says, __assume(0)
must not be in a reachable branch of code, which means, that branch must be unreachable.
Visual Studio has __assume(0)
for this use-case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With