0
addi $s7, $s7, -4
add  $s7, $s7, $s1
lw   $s0, 4($s7)

Assume integer variables i and j are in registers $s0 and $s1. Assume base address of an integer array X is in register $s7.

So far I have this:

X = X - 4
X = X + j
i = X - 4 + j

Is this correct? I'm not overly sure so just looking for confirmation.

yoshi105
  • 41
  • 2
  • 6
  • `lw` stands for "load word". – Seva Alekseyev Apr 02 '13 at 19:46
  • Actually, that code cannot be [reliably] translated into C. C arithmetic operations will (usually) be translated into unsigned MIPS instructions like addu/subu/addiu. This is due to the fact that the signed versions of the MIPS instructions trap on overflows - that's often ignored in C for signed types and always ignored in C for unsigned types. Seeing how `X` is likely a pointer, the unsigned instructions should be used. – Wiz Apr 02 '13 at 20:20

2 Answers2

4

It is incorrect. Note that lw instruction reads a word from memory.

In C it would look something like

  //int *x;
  x--;            // addi $s7, $s7, -4 decrements pointer to x one element
  x = (int*)((char*)x + j);  // add $s7, $s7, $s1 increments the address pointed by x j elements
  i = *(x+1);     // lw $s0, 4($s7) reads the next element pointed by x

Addendum after OPs comment:

If j = $s7 is multiple of 4 (note that each integer occupies 4 bytes), then it could be rewritten in C as i = x[j/4].

gusbro
  • 22,357
  • 35
  • 46
  • So as C statement it could be something like: i = X [ j + 1 ] – yoshi105 Apr 02 '13 at 20:54
  • @yoshi105: not really. The problem is that each integer occupies 4 bytes, but the middle instruction adds an unknown number. **IF** j=`$s1` is multiple of 4 then it could be rewritten as i = X[j/4] – gusbro Apr 02 '13 at 21:35
  • `(char*)x += j;` is wrong. It should be `x = (int*)((char*)x + j);` or if `j` is a multiple of `sizeof(int)`, `x += j/sizeof(int);` – Alexey Frunze Apr 02 '13 at 22:54
  • @AlexeyFrunze: changed that line. I believe the way it was written might not be "compile as-is" code but idea of what it did was mainly the same as it's written now. – gusbro Apr 03 '13 at 15:11
0

lw-->Load word

syntax:lw $t, offset($s) operation: $t = MEM[$s + offset]; advance_pc (4);

hims15
  • 96
  • 1
  • 4