Stack and Global Pointer Usage

Download project files.

Variables a and b are stored in .rwdata. Variable c is stored on the stack.

    int c;
    c = sign(a,b);
  800224:    d1200017     ldw    r4,-32768(gp)
  800228:    d1600117     ldw    r5,-32764(gp)
  80022c:    08002880     call    800288 <sign>
  800230:    e0800015     stw    r2,0(fp)

Variables a and b are loaded relative to the global pointer register gp. Variable c is stored relative to the frame pointer fp (derived from the stack pointer).

From the symbol table and a dump of .rwdata:

symboladdresscontents
hexdecimal
_gp0x80d948

a0x8059480xe14
b0x80594c0xfffffff8-8

Note that gp − &a = 0x80d948 - 0x805948 = 0x8000,
the largest negative number in 16 bits (-32768).

main2.c


01: /*
02:  *  stack and global pointer
03:  */
04: 
05: #include <stdio.h>
06: 
07: int sign(int x, int y);
08: int a = 14;
09: int b = -8;
10: 
11: int main()
12: {
13:     int c;
14:     c = sign(a,b);
15:     return 0;
16: }
17: 
18: int abs(int a)
19: {
20:     return (a<0? -a: a);
21: }
22: 
23: int sign(int x, int y)
24: {
25:     return (y<0? -abs(x): abs(x));
26: }
27: 

Disassembly

00800214 <main>:
int a = 14;
int b = -8;

int main()
{
  800214:    defffd04     addi    sp,sp,-12
  800218:    dfc00215     stw    ra,8(sp)
  80021c:    df000115     stw    fp,4(sp)
  800220:    d839883a     mov    fp,sp
    int c;
    c = sign(a,b);
  800224:    d1200017     ldw    r4,-32768(gp)
  800228:    d1600117     ldw    r5,-32764(gp)
  80022c:    08002880     call    800288 <sign>
  800230:    e0800015     stw    r2,0(fp)
    return 0;
  800234:    0005883a     mov    r2,zero
}
  800238:    dfc00217     ldw    ra,8(sp)
  80023c:    df000117     ldw    fp,4(sp)
  800240:    dec00304     addi    sp,sp,12
  800244:    f800283a     ret


Maintained by John Loomis, updated Tue Nov 11 22:09:43 2008