title: Manual Assembly vs GCC
body: <p>Disclaimer: I'm just starting out with x86 assembly. I did learn a bit of SPIM at university, but that's hardly worth mentioning.</p>
  
  <p>I thought I start with what's probably the most simple function in libc, abs(). Pretty straightforward in C:</p>
  
  <pre><code>long myAbs(long j) {
      return j &lt; 0 ? -j : j;
  }
  </code></pre>
  
  <p>My version in assembly:</p>
  
  <pre><code>    .global myAbs
      .type   myAbs, @function
      .text
  
  myAbs:
      test %rdi, %rdi
      jns end
      negq %rdi
  end:
      movq %rdi, %rax
      ret
  </code></pre>
  
  <p>(This doesn't work for 32bit integers, probably because RAX is a 64bit register and the sign is probably at the wrong position - I have to investigate that).</p>
  
  <p>Now here's what gcc does (gcc -O2 -S myAbs.c):</p>
  
  <pre><code>        .file   "myAbs.c"
          .section        .text.unlikely,"ax",@progbits
  .LCOLDB0:
          .text
  .LHOTB0:
          .p2align 4,,15
          .globl  myAbs
          .type   myAbs, @function
  myAbs:
  .LFB0:
          .cfi_startproc
          pushq   %rbp
          .cfi_def_cfa_offset 16
          .cfi_offset 6, -16
          movq    %rsp, %rbp
          .cfi_def_cfa_register 6
          subq    $4144, %rsp
          orq     $0, (%rsp)
          addq    $4128, %rsp
          movq    %rdi, %rdx
          sarq    $63, %rdx
          movq    %fs:40, %rax
          movq    %rax, -8(%rbp)
          xorl    %eax, %eax
          movq    %rdi, %rax
          xorq    %rdx, %rax
          subq    %rdx, %rax
          movq    -8(%rbp), %rcx
          xorq    %fs:40, %rcx
          jne     .L5
          leave
          .cfi_remember_state
          .cfi_def_cfa 7, 8
          ret
  .L5:
          .cfi_restore_state
          call    __stack_chk_fail@PLT
          .cfi_endproc
  .LFE0:
          .size   myAbs, .-myAbs
          .section        .text.unlikely
  .LCOLDE0:
          .text
  .LHOTE0:
          .ident  "GCC: (Gentoo Hardened 5.1.0 p1.2, pie-0.6.3) 5.1.0"
          .section        .note.GNU-stack,"",@progbits
  </code></pre>
  
  <p>Why this big difference? GCC produces substantially more instructions. I can't imagine that this won't be slower than my code.
  Am I missing something? Or am I doing something seriousely wrong here?</p>