Reputation:
I have learned that there are some common cases of local storage on the stack
case 1: There are not enough registers to hold all of the local data
case 2: The address operator '&' is applied to a local variable, and hence we must be able to generate an address for it
case 3: Some of the local variables are arrays of structures and hence must be accessed by array or structure reference.
In the practice problem there are some codes
long call_proc()
{
long x1=1; int x2= 2;
short x3=3; char x4=4;
proc(x1,&x1,x2,&x2,x3,&x3,x4,&x4);
return (x1+x2)*(x3-x4);
}
<generated assembly code>
call_proc:
subq $32, %rsp
movq $1, 24(%rsp)
movl $2, 20(%rsp)
movw $3, 18(%rsp)
movb $4, 17(%rsp)
leaq 17(%rsp), %rax
movq %rax, 8(%rsp)
movl $4, (%rsp)
leaq 18(%rsp), %r9
movl $3, %r8d
leaq 20(%rsp), %rcx
movl $2, %edx
leaq 24(%rsp), %rsi
movl $1, %edi
call proc
.....
Q1. In this practice, Is it applied case2 not case1 according to that kind of cases?
Q2. If it is correct case2, Can I get some examples about case1?
Q3. By assuming that code I think it is not necessary for all local variable to be saved in stack like x1, x2, x3, x4. Is it reasonable assuming?
Upvotes: 0
Views: 77
Reputation: 12434
Q1. Yes, the example shown is case 2.
Q2. To create an example of case 1, simply create a function with more than 6 local variables (for x86-64; for other architectures a different number would be needed), where the values of those variables need to be retained across another function call.
Here is a quick example I wrote: https://godbolt.org/z/S8m0lG. In this example, the variable n
is the one that the compiler chose to put on the stack, because there isn't a register available to store it. Note that even though this is a trivial example, I made sure to give all variables distinct values, so the compiler wouldn't combine them.
Upvotes: 1