I have a macro used all over my code that in debug mode does:
#define contract(condition)
if (!(condition))
throw exception("a contract has been violated");
... but in release mode:
#define contract(condition)
if (!(condition))
__builtin_unreachable();
What this does over an assert()
is that, in release builds, the compiler can heavily optimize the code thanks to UB propagation.
For example, testing with the following code:
int foo(int i) {
contract(i == 1);
return i;
}
// ...
foo(0);
... throws an exception in debug mode, but produces assembly for an unconditional return 1;
in release mode:
foo(int):
mov eax, 1
ret
The condition, and everything that depended on it, has been optimized out.
My issue arises with more complex conditions. When compiler cannot prove that the condition has no side effect, it does not optimize it out, which is a runtme penalty compared to not using the contract.
Is there a way to express that the condition in the contract has no side effect, so that it is always optimized out?
See Question&Answers more detail:os