x86 Inline Assembly Programming


Assumptions

The program is in a single file.  All variables are 32-bit.
Inline Assembly
Inline assembly code may be included as a string parameter, one instruction per line, to the asm function  in a C/C++ source program.

...
asm("incl x;
           movl 8(%ebp), %eax
        ");

Where the basic syntax is: asm [ volatile ] ( /*asm statements*/
                                                                [: /* outputs - comma separated list of constraint name pairs */
                                                                [: /* inputs - comma separated list of constraint name pairs*/
                                                                [: /* clobbered space - registers, memory*/
                                                                ]]]);

Constraints are The outputs and inputs are referenced by numbers beginning with %0 inside asm statements.
 
Example:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>

int f( int );

int main (void)
{
  int x; 
  asm volatile("movl $3,%0" :"=g"(x): :"memory"); // x = 3;
  printf("%d  ->  %d\n",x,f(x));
}

/*END   Main    */

int f( int x )
{
   asm volatile("movl %0,%%eax
                 imull $3, %%eax
                 addl $4,%%eax"
         :
         :"a" (x)
         : "eax", "memory"
        ); //return (3*x + 4);
}
Global Variables
Assuming that x and y are global variables, the following code implements x = y*(x+1)

asm("incl x
            movl x, %eax
            imull y
           movl %eax,x
          ");

Local variables
Space for local variables is reserved on the stack in the order that they are declared.  So given the declaration: int x, y;

x is at -4(%ebp)
y is at -8(%ebp)

Value Parameters
Parameters are pushed onto the stack from right to left and are referenced relative to the base pointer (ebp) at four byte intervals beginning with a displacement of 8.  So in the body of p(int x,  int y, int z)

x is at 8(%ebp)
y is at 12(%ebp)
z is at 16(%ebp)

Reference parameters
Reference parameters are pushed onto the stack in the same order that value parameters are pushed onto the stack.  The difference is that access to the value to which the parameter points is as follows

p(int& x,...

   movl 8(%ebp), %eax  # reference to x copied to eax
   movl  $5, (%eax)        # x = 5

References