Search code examples
assemblyx86mov

Advice regarding what this assembler is doing MOVs for?


This C++:

int my_func(int y, int t){
    int m = 0;
    m= y*t;
    return m;
}

int main(){
    int h = my_func(1,2);
    return 1;
}

Producing this x86:

int main(){
push        ebp  
mov         ebp,esp  
sub         esp,8  
    int m = my_func(1,2);
mov         dword ptr [ebp-4],0  
mov         eax,1
imul        eax,eax,2  
mov         dword ptr [ebp-4],eax     ;Why?
mov         ecx,dword ptr [ebp-4]     ;Why?
mov         dword ptr [m],ecx         ;Why?
    return 1;
mov         eax,1  
}
mov         esp,ebp  
pop         ebp  
ret

I don't understand why three movs are required when the value of m is already contained in register eax, after the imul?

Is it because eax has to be used for the return 1 line and eax is therefore a special register?

Also, what does dword ptr [ebp-4] refer to exactly? Is it the 1 or the 2?


Solution

  • [ebp-4] is where my_func's local copy of m is stored on the stack. [m] is where main's local copy of m is stored. What's missing here is the definition for main's copy of m. I would have expected it to also be an offset from ebp. Using VS2005, I compiled this example, using volatile to prevent optimizing the muliplty away.

    __inline int myfun(int a, int b)
    {
    int m;
        m = a*b;
        return (m);
    }
    
    int main (void)
    {
    volatile int a, b, m;
        a = 1;
        b = 2;
        m = myfun(a, b);
        return(0);
    }
    

    and got this assembly code. Note that m and a share the same memory location: -4[ebp+8]:

    _b$ = -8                                                ; size = 4
    _m$ = -4                                                ; size = 4
    _a$ = -4                                                ; size = 4
    _main   PROC
            sub     esp, 8
            mov     DWORD PTR _a$[esp+8], 1
            mov     DWORD PTR _b$[esp+8], 2
            mov     ecx, DWORD PTR _b$[esp+8]
            mov     eax, DWORD PTR _a$[esp+8]
            imul    eax, ecx
            mov     DWORD PTR _m$[esp+8], eax
            xor     eax, eax
            add     esp, 8
            ret     0