Search code examples
compiler-optimizationd

may the compiler optimize based on assert(...) expressions/contracts?


http://dlang.org/expression.html#AssertExpression

Regarding assert(0): "The optimization and code generation phases of compilation may assume that it is unreachable code."

The same documentation claims assert(0) is a 'special case', but there are several reasons that follow.

Can the D compiler optimize based on general assert-ions made in contracts and elsewhere?

(as if I needed another reason to enjoy the in{} and out{} constructs, but it certainly would make me feel a little more giddy to know that writing them could make things go fwoosh-ier)


Solution

  • In theory, yes, in practice, I don't think it does, especially since the asserts are killed before even getting to the optimizer on dmd -release. I'm not sure about gdc and ldc, but I think they share this portion of the code.

    The spec's special case reference btw is that assert(0) is still present, in some form, with the -release compile flag. It is translated into an illegal instruction there (asm {hlt;} - non-kernel programs on x86 aren't allowed to use that so it will segfault upon hitting it), whereas all other asserts are simply left out of the code entirely in -release mode.