|
Boost : |
From: Marcin Kalicinski (kalita_at_[hidden])
Date: 2005-09-15 09:15:47
> On 9/15/05, Simon Buchan <simon_at_[hidden]> wrote:
>> Felipe Magno de Almeida wrote:
>> So... you want asserts to assure the compiler that the expression
>> should be impossible? I can't think of too many times that would
>> actually generate better code, and may be a source of unexpected
>> behaviour, but better minds than I should think about it, I guess.
>
> Yes. I think that almost always unexpected behavior is already the
> case when an assertion is violated.
> IMO, assertions should be invariants, and as such should never(and I
> mean really never) be violated, no matter what. The only way I can see
> variants could be broken are through bugs in the library, improper use
> or incorrect synchronization(which is an improper use). What I'm only
> suggesting is using these already thought and coded invariants to be
> used for optimization. Maybe could have be a define in boost that
> could do enable this, and have the default behavior as this
> optimisation disabled.
Besides helping optimization __assume suppresses some warnings:
int f()
{
if ( ... some condition ...)
return 0;
__assume(0); // warning if no assume present here
}
Without __assume compiler emits obvious warning: 'not all control paths
return a value'. That means with __assume you don't have to put junk return
statements that will never get executed, and may actually cause some
unneeded code to be generated. To see if there's actually any code generated
for such an extra return statement (added only to suppress the warning) I
did another test with MSVC:
int f(int n)
{
if (n == 0) return 7;
else if (n == 1) return 19;
else
//__assume(0);
// return 0;
}
Code generated with 'return 0;' at the end:
mov eax, DWORD PTR _n$[esp-4]
test eax, eax
jne SHORT $LN4_at_f
mov eax, 7
ret 0
$LN4_at_f:
sub eax, 1
neg eax
sbb eax, eax
and eax, -19
add eax, 19
ret 0
Code generated with '__assume(0);' at the end:
mov eax, DWORD PTR _n$[esp-4]
neg eax
sbb eax, eax
and eax, 12
add eax, 7
ret 0
Note the clever way compiler avoids a conditional in 'assume' case, while it
is unable to do it with redundant 'return 0'.
This is the first case that came to my mind, there might as well be cases
where the gains are bigger.
Marcin
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk