本文讲解了C语言运行在MIPS体系中结构体传参的情况
硬件平台:Loongson 3A3000
系统:uos
在《see MIPS run》中11.2.5中描述到,会将结构体成员压缩到各个arg寄存器中进行传递
“we have to pack the register with data to mimic the arrangement of data in memory.”
- C语言代码:
构造一个函数,参数为结构体,在main函数中调用函数,并传入结构体
#include <stdio.h>
#include <stdint.h>struct shape{uint32_t a;uint16_t b
};void test(struct shape sp){uint32_t c = sp.a + sp.b;printf("%d \n", c);
}void main()
{struct shape sp; sp.a = 12; sp.b = 32; test(sp);
}
- 汇编代码
0000000000000b00 <test>:b00: 67bdffc0 daddiu sp,sp,-64b04: ffbf0038 sd ra,56(sp)b08: ffbe0030 sd s8,48(sp)b0c: ffbc0028 sd gp,40(sp)b10: 03a0f025 move s8,spb14: 3c1c0002 lui gp,0x2b18: 0399e02d daddu gp,gp,t9b1c: 679c8320 daddiu gp,gp,-31968b20: ffc40010 sd a0,16(s8)b24: 8fc30010 lw v1,16(s8)b28: 97c20014 lhu v0,20(s8)b2c: 00621021 addu v0,v1,v00000000000000b74 <main>:b74: 67bdffd0 daddiu sp,sp,-48b78: ffbf0028 sd ra,40(sp)b7c: ffbe0020 sd s8,32(sp)b80: ffbc0018 sd gp,24(sp)b84: 03a0f025 move s8,spb88: 3c1c0002 lui gp,0x2b8c: 0399e02d daddu gp,gp,t9b90: 679c82ac daddiu gp,gp,-32084b94: 2402000c li v0,12 //加载立即数到V0b98: afc20000 sw v0,0(s8) //保存到栈中b9c: 24020020 li v0,32 //加载立即数到V0ba0: a7c20004 sh v0,4(s8) //保存到栈中ba4: dfc40000 ld a0,0(s8)ba8: df828058 ld v0,-32680(gp)bac: 0040c825 move t9,v0bb0: 0411ffd3 bal b00 <test>
- 在ba0代码执行完毕后栈内数据情况如下
- ba4 ld a0,0(s8); 把栈中8个字节加载到了a0寄存器,即图中0~8中的数据,即结构体中的a、b
- b20 sd a0,16(s8); 把a0,放到栈中16offset
- b24 lw v1,16(s8); 从栈中16offset读取前4个字节
- b28 lhu v0,20(s8);从栈中20offset读取剩下两个字节