C++ code into assembly

304 views Asked by At

i have a gcd function in c++ visual studio and i want to convert it into assembly language.Here's the function :

int GCD(int a, int b)
{
    int  gcd;
    for(int i=1;i<=a&&i<=b;i++)
    {
        if(a%i==0 && b%i == 0 )
        {
             gcd=i;
        }
    }
}
1

There are 1 answers

1
Josh Broadhurst On

There are tools that automatically generate visible assembly code for you (such as using the -S and -masm=intel flags with gcc/g++ compiler), but if you want to convert your code to assembly manually as a learning exercise, here is something to get you started:

Understand the Call Stack

Before your GCD function is called, the call stack looks something like this. ESP is the stack pointer. It keeps track of the top of your call stack and changes position as you push and pop elements on the stack. EBP is the base pointer. It is used as a relative reference to refer to variables stored above or below it on the stack by a certain offset.

As a programmer, you have a responsibility to follow a calling convention that other programmers have established. This calling convention requires you to set up the call stack at the beginning of your function so that you don't mess up anything else around it. This is done with the following lines of assembly code:

GCD:
; make new call frame
    push    ebp
    mov     ebp, esp
        ...

The first line saves the previous EBP value by pushing it to the top of the stack and the second line updates EBP to point to the top of the stack it just saved. Any local variables you declare inside your GCD function will be placed on top of this new stack. Assuming you return your gcd variable as the result, it will be placed at the top of the stack above the previous EBP.

The remaining part of the calling convention requires you to clean up the stack frame you modified. This is done with the following lines of code at the end of your function (equivalent to the leave instruction):

        ...
; cleanup call frame
    mov     esp, ebp
    pop     ebp

Translate the Function Body

Once you have your call stack setup properly, you can start to translate the function body. This typically requires some skill and takes a while to do even for a small function like yours, so I will simply post a solution for a similar exercise I've done previously. You can draw comparisons to help you translate and also the assembly.ynh.io linked in the comments above is very helpful for visualizing your specific function's translation.

Hope this helps!