Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following assembly code long loop(long x, int n) x in %rdi, n in %e

ID: 3732904 • Letter: C

Question

Consider the following assembly code long loop(long x, int n) x in %rdi, n in %esi 1 loop: movl movl movl %esi, %ecx $1, %edx $0,%eax 4 2 ·L3 : movq %rdi, %r8 orq L2: testq %rdx , %rax jne rep; ret 12 13 L3 The preceding code was generated by compiling C code that had the following overall form: 1 long loop(long x, long n) long result long mask; for (mask = mask mask result I- return result; Your task is to fill in the missing parts of the C code to get a program equivalent to the generated assembly code. Recall that the result of the function is returned in register %rax. You will find it helpful to examine the assembly code before, during, and after the loop to form a consistent mapping between the registers and the program variables. A. Which registers hold program values x, n, result, and mask? B. What are the initial values of result and mask? C. What is the test condition for mask? D. How does mask get updated? E. How does result get updated? F. Fill in all the missing parts of the C code

Explanation / Answer

For A:

x = %rdi

n = %esi

result = %eax

msk = %edx

For B:

Here we have to know Initial values of result and mask are 0and 1 respectively.

For C:

Here we have to know the mask is left shifted every time by the contents of %cl register by following instruction

Salq

%cl,

% rdx and it is tested by following condition:

testq

%rdx,

%rdx

jne .L3

the test instruction sets the Zero flag if contents of %rdx are zero, which is used by jne instruction. Therefore test condition of mask will below

mask!= 0

for D:

Here we can get mask update as he value in the mask is left shifted by number present in n, which is stored in %esi register.

movl

%esi,

%ecx

salq

%cl,

%rdx

For E:

Here we know the value of result is stored in %eax.It is updated by value of mask(%edx). The value of mask is NDed with value of x. The result of this operation is ORed with result, that updates the value of result. This process is done in L3 loop.

.L3

movq %rdi,%r8 #mov x to r8

andq %rdx,%r8 #And mask with r8(x)

orq %r8,%rax #OR result(rax) with r8

C equivalentlent code for this is as below:

mask = mask & x;

result = result | mask;

for F:

here wwe can Complete function is as below:

long loop(long x,long n)

{

long result = 0;

long mask;

for (mask = 1; mask != 0; mask << n)

{

result |= mask & x;

}

return result;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote