essence16
essence16

Reputation: 173

Understanding of the following assembly code from CSAPP

I am recently reading CSAPP and I have a question about example of assembly code. This is an example from CSAPP, the code is followed:

    long pcount_goto
    (unsigned long x) {
    long result = 0;
    result += x & 0x1;
    x >>= 1;
    if(x) goto loop;
    return result;

 And the corresponding assembly code is:

   movl    $0, %eax     #  result = 0
   .L2:                 # loop:
    movq    %rdi, %rdx
    andl    $1, %edx    #  t = x & 0x1
    addq    %rdx, %rax   #  result += t
    shrq    %rdi         #  x >>= 1
    jne .L2                 #  if (x) goto loop
    rep; ret

The questions I have may look naive since I am very new to assembly code but I will be grateful is someone can help me with these questions.

  1. what's the difference between %eax, %rax, (also %edx, %rdx). I have seen them occur in the assembly code but they seems to refer to the same space/address. What's the point of using two different names?

  2. In the code

    andl    $1, %edx    #  t = x & 0x1
    

    I understand that %edx now stores the t, but where does x goes then?

  3. In the code

    shrq    %rdi  
    

    I think

     shrq   1, %rdi
    

    should be better?

  4. For

    jne .L2                 #  if (x) goto loop
    

    Where does if (x) goes? I can't see any judgement.

Upvotes: 0

Views: 490

Answers (1)

Jester
Jester

Reputation: 58762

These are really basic questions, a little research of your own should have answered all of them. Anyway,

  1. The e registers are the low 32 bits of the r registers. You pick one depending on what size you need. There are also 16 and 8 bit registers. Consult a basic architecture manual.
  2. The and instruction modifies its argument, it's not a = b & c, it's a &= b.
  3. That would be shrq $1, %rdi which is valid, and shrq %rdi is just an alias for it.
  4. jne examines the zero flag which is set earlier by shrq automatically if the result was zero.

Upvotes: 2

Related Questions