Skip to content

3.58

Problem

For a function with prototype

long decode2(long x, long y, long z);

gcc generates the following assembly code:

1   decode2:    
2   subq    %rdx, %rsi
3   imulq   %rsi, %rdi
4   movq    %rsi, %rax
5   salq    $63, %rax
6   sarq    $63, %rax
7   xorq    %rdi, %rax
8   ret 

Parameters x, y, and z are passed in registers %rdi, %rsi, and %rdx. The code stores the return value in register %rax. Write C code for decode2 that will have an effect equivalent to the assembly code shown.

Solution

decode2 first computes the value (y - z) * x (let's call it k), and then converts it to a value whose bit representation contains either all 1s (if k is odd) or all 0s (if k is even).

long decode2(long x, long y, long z)
{
    long k = (y - z) * x;
    k = (k << 63) >> 63;
    return k ^ x;
}

Interesting point: In terms of x, what are the two values that this function can return?