develooper Front page | perl.perl5.porters | Postings from June 2015

Re: Coverity finding: shift by negative

Thread Previous | Thread Next
From:
Zefram
Date:
June 23, 2015 13:45
Subject:
Re: Coverity finding: shift by negative
Message ID:
20150623134524.GL23010@fysh.org
Jarkko Hietaniemi wrote:
>(Yes, I'm asking should we define a semantics for this thing which is
>undefined in C.)

It is perfectly reasonable to define this.  These two languages have
quite different levels of abstraction.  The reason why it is undefined
in C is specifically so that the C shift operators can compile down
to machine code shift instructions, for speed, and instruction sets
differ on how they handle variable shifts that are nominally by more
than the word width.  Perl does not get a significant performance win
from mapping Perl shift operators down to C/assembler shift operators,
because of the comparatively large op overhead.

>shift left by negative n == shift right by -n ?
>shift right by negative n == shift left by -n?

This seems less surprising and more useful than any kind of error (undef
or croak).

>shift by too many bits == shift by n modulo wordbits?

No, that's a silly interpretation.  It's what some CPUs do simply to save
transistors: the shift instruction only looks at the low-order bits of
the shift distance operand.  (Well, also to save cycles if shifting is
done by one bit per cycle.)

If shifting by too many bits is to be defined, the only sensible
definition is the mathematically obvious one: all the bits get shifted
out of the word.  The over-long shift should be equivalent to a sequence
of two or more short shifts that total the requested distance.

>for use integer we would need to think about signed behavior.

We already have specific behaviour around the sign bit.  The signedness
of the main operand is ignored, it is treated as an untyped bit vector;
"use integer" determines whether a right shift zero-fills or sign-fills;
"use integer" also determines whether the resulting bit vector is treated
as a UV or an IV.  The shift-distance operand should be interpreted
according to its actual signedness regardless of "use integer".

-zefram

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About