Condition Codes n Single bit registers CF carry
Condition Codes n Single bit registers ¨ CF – carry flag ¨ ZF – zero flag ¨ SF – sign flag ¨ OF – overflow flag n n Relevant only for the most recent operation leal does not alter any condition code In logical operations, CF and OF are set to 0 For shift operations, OF is set to 0, CF is the last shifted out bit
Setting Condition Codes
Setting Condition Codes (cont. ) Explicit Setting by Compare Instruction cmpl Src 2, Src 1 ¨ cmpl b, a like computing a-b without setting destination ¨ CF set if carry out from most significant bit n Used for unsigned comparisons ¨ ZF set if a == b ¨ SF set if (a-b) < 0 ¨ OF set if two’s complement overflow (a>0 && b<0 && (a-b)<0) || (a<0 && b>0 && (a-b)>0)
Setting Condition Codes (cont. ) Explicit Setting by Test instruction testl Src 2, Src 1 ¨ Sets condition codes based on value of Src 1 & Src 2 n Useful to have one of the operands be a mask testl b, a like computing a&b without setting destination ¨ ZF set when a&b == 0 ¨ SF set when a&b < 0 ¨
Accessing the Condition Codes
Why does it work? Let’s take setl b, a for example ¨ If there is no overflow and a≥b ¨ If there is no overflow and a<b ¨ If there is a negative overflow (a>b) ¨ If there is a positive overflow (a<b) SF=0, OF=1 SF=1, OF=0 SF=1, OF=1 SF=0, OF=1
a < b in assembly n n Translate the line: return (a<b); Suppose a is in %edx, b is in %eax: cmpl %eax, %edx # compare a to b setl %al movzbl %al, %eax # set %al to 0 or 1 # set %eax to 0 or 1
Jump Instructions
Unconditional Jump n Direct jump jmp L 1 n Indirect jump ¨ jmp *%eax ¨ jmp *(%eax)
Conditional Jump n Can’t use indirect jump n Use it to implement ¨ if conditions ¨ loops ¨ switch statements
Goto in C
If Condition in Assembly
Do-While Loops
Do-While Loops in Assembly
While Loops
Exercise Register %eax %ebx %ecx %edx Variable Initially
Exercise’s Solution Register Variable Initially %eax a a %ebx b b %ecx i 0 %edx result a
Exercise’s Solution Note the optimization done by the compiler!
For Loops
Exercise
Exercise’s Solution Note the optimization done by the compiler!
Switch Statements in C
Switch Statements in Assembly Building the jump table:
Switch Statements in Assembly
Switch Statements in Assembly
Exercise
Q&A n Q: n n n What were the values of the case labels in the switch statement body? What cases had multiple labels in the C code? A: n n The case labels had values -2, 0, 1, 2, 3, 4 The case with the labels 2 and 3
- Slides: 28