gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

ASM > Is this how stacks work in principle?

#177122 - blessingta@hotmail.co.uk - Wed Dec 14, 2011 3:46 am

is this how stacks work in principle ?

Quote:

//variables depended on case 1 being true
...

//variables depended on case 2 being true
....

//blah blah...
TEST_IF_CASE1_OR_CASE2:

//push to stack

EXECUTE_SUBROUTINE_HERE:
//liftback from stack
//latter functionality here
....

#177123 - elhobbs - Wed Dec 14, 2011 7:26 pm

the ds/gba has a region of memory set aside (by devkitARM) for stack usage. stack space is reserved when a function is entered. it stores local variables, saves current register values, and other compiler created workspace. when the function returns then the reserved space is released. there are more places where stack can be reserved - local variables inside blocks, etc, but this is a simplified description.

I would say this is not really an ASM questions and you can find much more detail on the web - I will give you a hint - it rhymes with moogle ;)

#177124 - Miked0801 - Wed Dec 14, 2011 7:29 pm

Sort of:

Code:

void main()
{
  int a = 1;
  int b = 2;
  int c = sum(a,b);
}

int sum(int a, int b)
{
  return a + b;
}


The above code can be compiled without a single use of the stack, or it can use it extensively, depending on how the compiler wants to do things.

It could push the value of a and b on the stack along with a return address, call sum, then have sum pop all those values off the stack and the return value into a register to tell it how to return, or it could leave a and b in registers and inline the call to sum by just adding the registers into a 3rd register c.

Basically, as routines become more complex and more values are needed to be tracked, the stack is used as a variable overflow area. This is especially true of any non-trivial sized structure. When allocating space for them, the compiler just offsets the stack pointer directly with a subtract instead of pushing a ton of values.

Your example seems to assume that variables are set before the conditional is checked. While this can be true, it usually is not the case.

Code:

if(a == 1)
{
  myStruct.a = 0;
  foo(myStruct);
}
else
{
  myStruct.a = 1;
  foo(myStruct);
}


Here, the values are set individually in each if statement before the function call. Also, the push of stack state happens within the called function, not before the call. This is more space efficient and keeps pushes and pops together close to each other making it much easier to fix push/pop mismatches - quite common when coding assembler.