Intrigued by this post about UB, I've decided to start reading Jonathan Bartlett's Programming from the Ground Up in order to play around with C++ UB and see what the assembly looks like.
But while trying out things I've found something strange in a pretty simple case. Consider this code
int foo(int * p) {
int y = 7;
if (p)
++y;
return y;
}
Its assembly is
foo(int*):
cmpq $1, %rdi
movl $7, %eax
sbbl $-1, %eax
ret
Now I understand that movl $7, %eax
is putting the value 7
into the eax
register, then one that's gonna be returned to the caller by ret
. So I also understant that sbbl $-1, %eax
is the instruction taking care of subtracting -1
from the content of eax
and storing the result into eax
itself, and that this instruction happens only if p
is not null. Which leads me to assume that sbbl
is making use of a hidden boolean value computed by earlier lines. The only candidate, even by the name, is cmpq $1, %rdi
.
But what is that doing? From the aforementioned book I've understood that functions arguments are passed from caller to callee via the stack: the caller pushes arguments on the stack, and the callee extracts those values. But there's no such a thing here.
So is %rdi
what? The register of the first (and in this case only) arugument of the function? Why is it so? Are there other registers referring to further arguments? How many? And besides, what is a good source of information on this topic?