www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - -O flag ; automatic cast in a bitshift

reply Guillaume Lathoud <gsub glat.info> writes:
Hello,

the code below behaves differently when compiled with or without 
the -O flag (both DMD and LDC2).

Two questions:

(1) does the D language explicitly specifies what the following 
expression should do? If yes, where?

  '<ulong> |= <ubyte> << <ubyte>'

In the example below, there seems to be a cast to 32 bits first, 
then a shift, then a cast to 64 bits.

(2) why the different result when putting the -O flag?

Best regards,
Guillaume Lathoud
.

import std.stdio;

void main()
{
   ubyte b = 84;
   ulong l = 0;
   ubyte shift = 50;

   l |= b << shift;

   writefln( "%064b", l );

   /*
     DMD64 D Compiler v2.080.1

     dmd cast_question.d ; cast_question
     
0000000000000000000000000000000000000001010100000000000000000000

     dmd -O cast_question.d ; cast_question
     
0000000000000000000000000000000000000000000000000000000000000000
   */

   /*
     LDC - the LLVM D compiler (1.10.0):
     based on DMD v2.080.1 and LLVM 6.0.0

     ldmd2 cast_question.d ; cast_question
     
0000000000000000000000000000000000000001010100000000000000000000

     ldmd2 -O cast_question.d ; cast_question
     
0000000000000000000000000000000000000000000000000000000000000000
    */
}
Sep 20 2018
parent reply ketmar <ketmar ketmar.no-ip.org> writes:
Guillaume Lathoud wrote:

this is UB. by the specs, values are promoted to int, and shifting int by 
50 is UB. so both results are nonsense.
Sep 20 2018
parent reply Guillaume Lathoud <gsub glat.info> writes:
On Thursday, 20 September 2018 at 11:08:32 UTC, ketmar wrote:
 Guillaume Lathoud wrote:

 this is UB. by the specs, values are promoted to int, and 
 shifting int by 50 is UB. so both results are nonsense.
Thanks!
Sep 20 2018
parent reply Vladimir Panteleev <thecybershadow.lists gmail.com> writes:
On Thursday, 20 September 2018 at 11:14:05 UTC, Guillaume Lathoud 
wrote:
 Thanks!
FYI, it's undefined in D mainly because the behavior of the actual Intel CPU instruction is undefined in such cases: https://c9x.me/x86/html/file_module_x86_id_285.html "it is undefined for SHL and SHR instructions where the count is greater than or equal to the size (in bits) of the destination operand".
Sep 20 2018
parent Guillaume Lathoud <gsub glat.info> writes:
On Friday, 21 September 2018 at 01:44:33 UTC, Vladimir Panteleev 
wrote:
 On Thursday, 20 September 2018 at 11:14:05 UTC, Guillaume FYI, 
 it's undefined in D mainly because the behavior of the actual 
 Intel CPU instruction is undefined in such cases:

 https://c9x.me/x86/html/file_module_x86_id_285.html

 "it is undefined for SHL and SHR instructions where the count 
 is greater than or equal to the size (in bits) of the 
 destination operand".
Thanks, good to know.
Oct 01 2018