-
[resolved]asm to c code
I have the following MIPS 32 asm code:
Assuming B is an array of 10 words whose base address is in register $s0, andvariable c and i are in $s1 and $s2, respectively. What is the C statement implemented by the below MIPS assembly code?
add $t0, $s2, $s2
add $t0, $t0, $t0
lw $t1, 0($s0)
lw $t2, 8($s0)
sub $s1, $t2, $t1
In C what does it look like?
i said c = B[i+2] - B[i]
but the other optpoins are:
c = B[i] - B[i+2]
c = B[i] - B[i+8]
c = B[i+8] - B[i]
Can someone see if i'm correct?
-
Re: asm to c code
That ASM lacks context. The first two lines are in no relation to the other three. If I read the argument order correctly (ADD result op1 op2), then the first line assigns to t0 twice the value of s2. The second line effectively doubles t0. The third reads the word (I'm assuming the MIPS architecture means a 32-bit value here) from the address that s0 contains (note that s0 hasn't been set in the snippet) into t1. The fourth reads the word at s0+8 into t2. The last subtracts one from the other and stores the result in s1.
So none of the four options is fully correct - they're all possibilities for the last three lines, but disregard the first two. The first two are, I think, just
a = b * 4;
As for which of the four options correctly portray the last three lines, it's impossible to say. Two of them are definitely wrong: check the reference for the SUB instruction to find out which operand is subtracted from which.
As for the other, it depends on how much lw loads. If it loads a 32-bit word, the i+2 options are correct. If it loads an 8-bit word, the i+8 options are correct. If it loads a 16-bit word, the i+4 options you didn't list are correct, and B is probably a short[] or short*.
On the other hand, it might not be direct array indexing at all. It could, for example, be this C code:
Code:
struct point3d
{
int x, y, z;
};
point3d points[NUM_POINTS];
int i = rand() % NUM_POINTS;
// This line might compile to the three assembly lines in question:
int t = points[i].z - points[i].x;
As you see, decompilation is far from trivial.
-
Re: asm to c code
THanks CornedBee! It was correct with the answer i chose, C. I agree the problem was worded not so nice.