Reputation: 173
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.
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?
In the code
andl $1, %edx # t = x & 0x1
I understand that %edx now stores the t, but where does x goes then?
In the code
shrq %rdi
I think
shrq 1, %rdi
should be better?
For
jne .L2 # if (x) goto loop
Where does if (x) goes? I can't see any judgement.
Upvotes: 0
Views: 490
Reputation: 58762
These are really basic questions, a little research of your own should have answered all of them. Anyway,
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.and
instruction modifies its argument, it's not a = b & c
, it's a &= b
.shrq $1, %rdi
which is valid, and shrq %rdi
is just an alias for it.jne
examines the zero flag which is set earlier by shrq
automatically if the result was zero.Upvotes: 2