0

这是我的C代码:

int test(int x, int y){
    int val=4*x;
    if (y>0){
        if (x<y) val=x-y;
        else val=x^y;
    }
    else if (y<-2) val=x+y;
    return val;
}

这是我在 GCC 命令行中输入的内容:

gcc -O1 -S -march=i686 test.c

这是我得到的S文件(只有计算部分):

pushl   %ebx
movl    8(%esp), %ecx
movl    12(%esp), %edx
testl   %edx, %edx
jle     L2
movl    %ecx, %eax
subl    %edx, %eax
movl    %edx, %ebx
xorl    %ecx, %ebx
cmpl    %edx, %ecx
cmovge  %ebx, %eax
jmp     L4

L2:
leal    0(,%ecx,4), %eax
addl    %edx, %ecx
cmpl    $-2, %edx
cmovl   %ecx, %eax

L4:
popl    %ebx
ret

我的问题是:我可以使用上面的 S 文件返回完全相同的 C 代码吗?我的意思是完全一样的。例如,我可以确定valis 4*x(C 代码的第 2 行)的默认值吗?我可以确定每个if语句的测试表达式吗?

我真的需要你的帮助。谢谢!!!

4

1 回答 1

2

In this case, you can find out that the each registers corresponding to a variable:

  • %eax - var
  • %ebx - a contextual temporary variable
  • %ecx - x
  • %edx - y

If you mean 'exactly' for the identifiers, it is only possible when a special structure named 'symbol table'. (compiled with -g flag in GCC)

Anyway, you should know a code can be always optimized by the compiler. It means, in this case, your code is changed to another having same mathematical meaning. If your code is backward-translated, it should be like this.

int test(int x, int y) {
    int val;
    if (y > 0) {
        if (x < y)
            val = x - y;
        else
            val = x ^ y;
    } else {
        if (y < -2)
            val = x + y;
        else
            val = 4 * x;
    }
    return val;
}

If you want no optimization, use flag -O0 instead of -O1.

于 2013-07-05T03:54:18.537 回答