CS360 Midterm -- March 14, 2002. Answer/Grading for Question 1


Answer

Straightforward assembler-crunching.
fp:
      push #4                 / allocate ptr

      ld [fp+16] -> %r0       / Load from*4 into r1
      mov #4 -> %r1
      mul %r0, %r1 -> %r1
      ld [fp+12] -> %r0       / Load graph into r0
      add %r0, %r1 -> %r1     
      ld [r1] -> %r0          / Load graph[from] into r0
      st %r0 -> [fp]          / Store it into ptr

l1:   ld [fp] -> %r0          / while(*ptr > 0)
      ld [r0] -> %r0
      cmp %r0, %g0
      ble l2

      ld [fp] -> %r0          / if (ptr == t0) ..
      ld [r0] -> %r0
      ld [fp+20] -> %r1
      cmp %r0, %r1
      bne l3
      mov #1 -> %r0           / return 1
      ret

l3:
      ld [fp+20] -> %r0       / push to
      st %r0 -> [sp]--
      ld [fp] -> %r0          / push *ptr
      ld [r0] -> %r0
      st %r0 -> [sp]--
      ld [fp+12] -> %r0       / push graph
      st %r0 -> [sp]--
      jsr fp                  / call fp and pop the arguments
      pop #12
      cmp %r0, %g1            / compare with 1
      bne l4
      mov #1 -> %r0           / return 1
      ret

l4:
      ld [fp] -> %r0          / add 4 to ptr
      mov #4 -> %r1
      add %r0, %r1 -> %r0
      st %r0 -> [fp]

      b l1                    / go to the top of the while loop

l2:      
      mov #0 -> %r0           / return zero
      ret

Grading - 14 points

I graded on the following scale: You got half credit for doing things halfway right (i.e. incrementing the pointer by one instead of four). If you used register r2, you had to spill it onto the stack after allocating ptr.