Sunday 11 December 2011

gcc inline assembler


  1. Register Naming: Register names are prefixed with %, so that registers are %eax, %cl.
  2. Ordering of operands: order of operands is source(s) first, and destination last. mov %edx, %eax" means move contents of edx register to eax
  3. Operand Size: size of memory operands is determined from the last character of the op-code name. The suffix is b for (8-bit) byte, w for (16-bit) word, and l for (32-bit) long. For example, the correct syntax for the above instruction would have been "movl %edx, %eax".
  4. Immediate Operand: Immediate operands are marked with a $ prefix, as in "addl $5, %eax", which means add immediate long value 5 to register %eax).
  5. Memory Operands: Missing operand prefix indicates it is a memory-address; hence "movl $bar, %ebx" puts the address of variable bar into register %ebx, but "movl bar, %ebx" puts the contents of variable bar into register %ebx.
  6. Indexing: Indexing or indirection is done by enclosing the index register or indirection memory cell address in parentheses. For example, "movl 8(%ebp), %eax" (moves the contents at offset 8 from the cell pointed to by %ebp into register %eax).
inline assembler invoked with __asm__("instruction"; "instruction"; "instruction");

__asm__ ("movl %ebx, %eax"); // moves the contents of ebx register to eax
__asm__ ("movb %ch, (%ebx)"); // moves the byte from ch to the memory pointed by ebx
// Add 10 and 20 and store result into register %eax
__asm__ ( "movl $10, %eax;"
          "movl $20, %ebx;"
          "addl %ebx, %eax;" );

Can optionally specify the operands. It allows us to specify the input registers, output registers and a list of clobbered registers.

__asm__ ( "assembly code"
           : output operands                  // optional
           : input operands                   // optional
           : list of clobbered registers );   // optional

If there are no output operands but there are input operands, we must place two consecutive colons surrounding the place where the output operands would go.

It is not mandatory to specify the list of clobbered registers to use, we can leave that to GCC and GCC’s optimization scheme do the needful.


Distilled from here: http://www.codeproject.com/KB/cpp/edujini_inline_asm.aspx

More info: http://ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html

No comments:

Post a Comment