[fpc-devel] Unexpected behaviour with intermediate results

Giuliano Colla giuliano.colla at fastwebnet.it
Tue Jun 12 13:42:49 CEST 2018


Il 12/06/2018 02:07, J. Gareth Moreton ha scritto:
> Someone pointed out that if you perform "(x shl 8) shr 8", where x is 
> of type Word, the result is always x, even though logic dictates that 
> the upper 8 bits should be shifted out and hence the result actually 
> be equal to "x and $FF".

IMHO logic dictates that (x shl 8) shr 8 should give x, because the shr 
cancels the effect of shl, and that a further compiler optimization 
might simply suppress the code at all. Register size when performing a 
calculation is not dictated by logic, but by physical constraints, which 
have nothing to do with logic.

If the programmer wishes to mask out some bits he should explicitly use 
an *and* instruction, making the code both more readable and more 
portable. Generating a less efficient code, with and instructions added 
with the sole purpose of supporting the improper usage of a shl 
instruction wouldn't be very smart.

I'm in favour of a compiler which generates the most efficient code, and 
leaves to the programmer the responsibility to mask unwanted bits.

Just my 2 cents.

Giuliano




More information about the fpc-devel mailing list