1

I have a C program which has a function decod and the function has the following statements.

My decode.c script:

int decod(int x, int y, int z) {
   int ty = y;
   ty = ty - z;
   int py = ty;
   py = py << 31;
   py = py >> 31;
   ty = ty * x;
   py = py ^ ty;
   }

The assembly code of this program (generated by gcc -S decod.c) shows the following code.

    movl    %edi, -20(%rbp)
movl    %esi, -24(%rbp)
movl    %edx, -28(%rbp)
movl    -24(%rbp), %eax
movl    %eax, -8(%rbp)
movl    -28(%rbp), %eax
subl    %eax, -8(%rbp)
movl    -8(%rbp), %eax
movl    %eax, -4(%rbp)
sall    $31, -4(%rbp)
sarl    $31, -4(%rbp)
movl    -8(%rbp), %eax
imull   -20(%rbp), %eax
movl    %eax, -8(%rbp)
movl    -8(%rbp), %eax
xorl    %eax, -4(%rbp)
popq    %rbp
.cfi_def_cfa 7, 8
ret

But, I want the program generate an assembly file with only the following lines of code.

subl    %edx, %esi
movl    %esi, %eax
sall    $31, %eax
sarl    $31, %eax
imull   %edi, %esi
xorl    %esi, %eax
ret

I know I am pretty close to write a program which will generate the above mentioned code. But, I am clueless why the script generates different assembly code. Any direction will be helpful.

Naz Islam
  • 409
  • 1
  • 6
  • 20
  • That function does not return anything.. – Arash Mar 09 '17 at 05:44
  • If you want it to result in *that* code, why are you writing it in C instead of assembly? – David Hoelzer Mar 09 '17 at 09:14
  • to get sensible asm-code, turn on optimization. On the other hand, to have sensible optimized code, provide code that will not be optimize out completely, ( since it doesnt return anything, it is completely useless) – Tommylee2k Mar 09 '17 at 11:35
  • If you want the compiler to optimize the code, you have to [Ask for it](http://stackoverflow.com/questions/1778538/how-many-gcc-optimization-levels-are-there). – Bo Persson Mar 09 '17 at 11:37

1 Answers1

3

If you compile your function as is, in optimization level3, -O3 the entire function is optimized out. This is because there is no return value and py and ty are anyways discarded after the function.

For reference the code is below

    .globl  decod
    .def    decod;  .scl    2;  .type   32; .endef
    .seh_proc   decod
decod:
    .seh_endprologue
    ret
    .seh_endproc

If however, you add a return py; at the end the code generated is as follows.

    .globl  decod
    .def    decod;  .scl    2;  .type   32; .endef
    .seh_proc   decod
decod:
    .seh_endprologue
    subl    %r8d, %edx
    movl    %edx, %eax
    imull   %edx, %ecx
    sall    $31, %eax
    sarl    $31, %eax
    xorl    %ecx, %eax
    ret
    .seh_endproc

This is functionally identical to what you are expecting.

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31