Plan for today Example question from previous final Using gcc and gdb to generate and step through x86 code Generating x86 instead of MIPS – Figuring out the x86 calling convention – Enough x86 to replace MIPS Generating Java byte code instead of MIPS – Using javap and Jasmin to figure it out step-by-step CS453 Lecture x86 code gen 1 Instruction selection for x86-64 Registers – 16 64-bit registers – RSP, the stack pointer register – RBP, the frame pointer register – 32-bit register names used to access lower 32-bits of corresponding 64-bit register: eax, edx, exc, ebx, esi, esi, edi, esp and ebp Representations – Constants prefixed with ‘$’, for example $3, $4, $-5, etc – Registers prefixed with ‘%’, for example %rsp, %rbp, etc. Some Instructions – movl %eax, -12(%rbp) // M[%rbp-12] = %eax – addl -20(%rbp), %eax // %eax = M[%rbp-20] * %eax – cmpl -4(%rbp), %eax – jge .L2 // if ( M[%rbp-4] >= %eax ) goto .L2 CS453 Lecture x86 code gen 2 x86-64 example .file "funcCall2.c” .text .globl foo .type foo, @function foo: pushq %rbp movq %rsp, %rbp movl %edi, -20(%rbp) movl %esi, -24(%rbp) movl -24(%rbp), %eax addl -20(%rbp), %eax movl %eax, -4(%rbp) movl -4(%rbp), %eax leave ret .size foo, .-foo # %rsp = %rsp-8; M[%rsp ] = %rbp # %rbp = %rsp # storing parameters to stack # accessing x # adding y to x and storing in %eax CS453 Lecture x86 code gen 3 Example continued... .globl main .type main, @function main: pushq %rbp # %rsp = %rsp-8; M[%rsp ] = %rbp; pushes onto stack movq %rsp, %rbp # %rbp = %rsp subq $16, %rsp # %rsp = %rsp - 16 movl $5, %esi # %esi = 5 movl $4, %edi # %edi = 4 call foo movl %eax, -4(%rbp) # M[%rbp-4] = %eax movl -4(%rbp), %eax # %eax = M[%rbp-4] leave ret CS453 Lecture x86 code gen 4 Suggested Exercises Compile the following three C programs – using ‘gcc -S filename.c’ on a 32-bit machine – read http://cs.wellesley.edu/~cs342/fall06/crash-course.pdf, pages 5-9 Answer the following questions (use google if necessary) – Identify and explain the lines of assembly code (5 lines that start at cmpl) generated for the ‘if’ statement. – What is the return register? How do you know? int main() {! return 20;! }! CS453 Lecture int main() int x, x = 2; return }! {! y;! y = 42;! x*y;! x86 code gen int main() {! int x, y;! x = 2; y = 42;! if (x>y) {! return 7;! } else {! return 8;! }! }! 5