V Lecture 21 — control flow in x86 assembly
V arithmetic exercise
V generate x86-64 assembly to compute the expression
a*b + c*d
* the final result should be stored in %rax
* a is in %rcx
b is in %rdx
c is in %rsi
d is in %rdi
* it should take no more than 4 instructions
* imulq %rdx, %rcx
imulq %rdi, %rsi
addq %rsi, %rcx
movq %rcx, %rax
or
imulq %rdx, %rcx
imulq %rdi, %rsi
leaq (%rsi, %rcx), %rax
V what is a C expression equivalent to the following assembly
sub %rsi,%rdi
mov %rdi,%rax
shl $0x4,%rax
add %rdi,%rax
* %rsi holds a variable b
%rdi holds a variable a
* 17 * (a - b)
V control flow
V jumps
* jump instructions are how things like ifs and loops are achieved in assembly
* a jump instruction takes as an argument a memory address and then may set the instruction pointer to that address
* most jump instructions depend on the value of one or more condition codes
V condition codes
* processor has 1-bit flags that get set based on the result of arithmetic instructions
V carry flag (CF) set if carry out from most significant bit
* used for unsigned
* zero flag (ZF) set if the result is zero
* sign flag (SF) set if the result is negative
V overflow flag (OF) set if there is two’s complement (signed) overflow
V for addq
* operands are positive, result is negative
* operands are negative, result is positive
V example
* function with an if statement
* -Og vs -O1 vs -O2
V factorial exercise
V aside: can refer to lower-order bits of registers by using different names
* for example, %eax is the lower 32 bits of register %rax
* note the uses for each register
* int fact(int n) {
int r = 1;
while(n > 1)
r *= n;
n--;
}
return r;
}
* 0000000000400616 <fact>:
400616: b8 01 00 00 00 mov $0x1,%eax
40061b: eb 06 jmp 400623 <fact+0xd>
40061d: 0f af c7 imul %edi,%eax
400620: 83 ef 01 sub $0x1,%edi
400623: 83 ff 01 cmp $0x1,%edi
400626: 7f f5 jg 40061d <fact+0x7>
400628: f3 c3 retq
V trace the series of instructions, register values, and condition codes for fact(3)