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.Global Variables...
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
- asm statements - enclosed with quotes, at&t syntax, separated by new lines
- outputs & inputs - constraint-name pairs "constraint" (name), separated by commas
- registers-modified - names separated by commas
The outputs and inputs are referenced by numbers beginning with %0 inside asm statements.
- g - let the compiler decide which register to use for the variable
- r - load into any avaliable register
- a - load into the eax register
- b - load into the ebx register
- c - load into the ecx register
- d - load into the edx register
- f - load into the floating point register
- D - load into the edi register
- S - load into the esi register
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); }
Local variablesAssuming 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
");
Value ParametersSpace 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)
Reference parametersParameters 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 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 followsp(int& x,...
movl 8(%ebp), %eax # reference to x copied to eax
movl $5, (%eax) # x = 5