【问题标题】:local variable storage allocation in assembly汇编中的局部变量存储分配
【发布时间】:2009-04-28 08:15:56
【问题描述】:

当说为局部变量分配存储时,经常使用以下 sn-p

addl $8,%esp  //allocate 8-byte storage

push %ebx     //store some value onto the stack

为什么不简单地将值压入堆栈,而是提前分配一些空间?

【问题讨论】:

    标签: assembly


    【解决方案1】:

    如果您要问为什么编译器不为本地存储生成推送指令而不是直接操作堆栈指针,那是效率问题。

    自动变量(无论如何在 C 中)未初始化,因此代码序列将是(我将使用 subl,因为我习惯于堆栈在内存中向下增长):

    C Code            Actual assembly        Your suggestion
    void x(void) {
        int a;        subl 8,%esp            push 0
        int b;                               push 0
        : : :         blah blah              blah blah
    }
    

    我的回答是,在以下情况下这是不必要且低效的:

    C Code            Actual assembly        Your suggestion
    void x(void) {
        int a[100];   subl 400,%esp          push 0
                                             push 0
                                             push 0
                                             : : :
                                             push 0
        : : :         blah blah              blah blah
    

    您的建议可能对以下内容有意义:

    C Code            Your suggestion
    void x(void) {
        int a = 7;    push 7
        int b = 9;    push 9
        int c[4];     subl 16,%esp
        : : :         blah blah
    }
    

    【讨论】:

      【解决方案2】:

      这样分配的空间是固定大小的,这对于编译器来说是最简单的,因为可以使用“DWORD PTR [ebp+(offset)]”来访问内存。 通常的函数序言是这样的:

      (英特尔语法) 推送ebp 添加 ebp, 8 mov ebp, esp

      对于具有 8 个字节的局部变量的函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 2015-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多