For this exercise, we will examine the code generated by GCC for functions that
ID: 3786564 • Letter: F
Question
For this exercise, we will examine the code generated by GCC for functions that have structures as arguments and return values, and from this see how these language features are typically implemented.
The following C code has a function process having structures as argument and return values, and a function eval that calls process:
1 typedef struct {
2 long a[2
3 long *p;
4 } strA;
5
6 typedef struct {
7 long u[2];
8 long q;
9 } strB;
10
11 strB process (strA s) {
12 strB r;
13 r.u[0] = s.a[1];
14 r.u[1] = s.a[0];
15 r.q = *s.p;
16 return r;
17 }
18
19 long eval (long x, long y, long z) {
20 strA s;
21 s.a[0] = x;
22 s.a[1] = y;
23 s.p = &z;
24 strB r = process(s);
25 return r.u[0] + r.u[1] + r.q;
26 }
GCC generates the following code for these two functions:
strB process(strA s)
1 process:
2 movq %rdi, %rax
3 move 24(%rsp), %rdx
4 movq (%rdx), %rdx
5 movq 16(%rsp), %
6 movq %rcx, (%rdi)
7 movq 8(%rsp), %rcx
8 movq %rcx, 8(%rdi)
9 movq %rdx, 16(%rdi)
10 ret
long eval(long x, long y, long z)
x in %rdi, y in %rsi, z in %rdx
1 eval:
2 subq $104, %rsp
3 movq %rdx, 24(%rsp)
4 leaq 24(%rsp), %rax
5 movq %rdi, (%rsp)
6 movq %rsi, 8(%rsp)
7 movq %rax, 16(%rsp)
8 leaq 64(%rsp), %rdi
9 call process
10 movq 72(%rsp), %rax
11 addq 64(%rsp), %rax
12 addq 80(%rsp), %rax
13 addq $104, %rsp
14 ret
A. We can see on line 2 of function eval that it allocates 104 bytes on the stack. Diagram the stack frame for eval, showing the values that it stores on the stack prior to calling process.
B. What value does eval pass in its cal to process?
C. How does the code for process access the elements of structure arguments?
D. How does the code for process set the fields of result structure r?
E. Complete your diagram of the stack frame for eval, showing how eval accesses the elements of structure r following the return from process.
Explanation / Answer
eval creates a brand new variable of sort strA mistreatment its input variables x,y and z.
It then passes this fresh created structure to operate method
How it really happens once reborn to assembly code? Well eval is aware of size of strA (as compiler is aware of that strA has 2 variables of long sort, a [0], a [1] and one pointer p, every of eight bytes) is 24bytes. Therefore it changes stack pointer by 24bytes before occupation method, as seen in instruction four of eval's assembly code. Then it sets values at offset of eight bytes (i.e. first at 0, then at eight and eventually at sixteen bytes from stack pointer), and these values ar what structure parts ought to be. Finally it calls method, and method navigates mistreatment its stack pointer, gets the worth and will the duty.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.