IAE Academy

GATE 2023 CS Q.41: solution and answer

GATE 2023 · CSQ.41 · 2 marks · MCQ

Consider the given C-code and its corresponding assembly code, with a few operands U1–U4 being unknown. Some useful information as well as the semantics of each unique assembly instruction is annotated as inline comments in the code. The memory is byte-addressable.

//C-code
int a[10], b[10], i;
// int is 32-bit
for (i=0; i<10;i++)
    a[i] = b[i] * 8;
;assembly-code (; indicates comments)
;r1-r5 are 32-bit integer registers
;initialize r1=0, r2=10
;initialize r3, r4 with base address of a, b
L01: jeq r1, r2, end  ;if(r1==r2) goto end
L02: lw   r5, 0(r4)   ;r5 <- Memory[r4+0]
L03: shl  r5, r5, U1  ;r5 <- r5 << U1
L04: sw   r5, 0(r3)   ;Memory[r3+0] <- r5
L05: add  r3, r3, U2  ;r3 <- r3+U2
L06: add  r4, r4, U3
L07: add  r1, r1, 1
L08: jmp  U4          ;goto U4
L09: end

Which one of the following options is a CORRECT replacement for operands in the position (U1, U2, U3, U4) in the above assembly code?

  1. (A)

    (8, 4, 1, L02)

  2. (B)

    (3, 4, 4, L01)

  3. (C)

    (8, 1, 1, L02)

  4. (D)

    (3, 1, 1, L01)

See the question in the paper

Answer and solution

ANSWER

(U1, U2, U3, U4) = (3, 4, 4, L01) — option (B).

Official answer: BSource: Official answer key, GATE 2023 CS (IIT Kanpur)

  1. The loop is for(i=0;i<10;i++) a[i]=b[i]*8; with int = 4 bytes, byte-addressable memory.

  2. L01 (jeq r1,r2,end) tests i==10; since it must run every iteration, it is the loop's back-edge target.

  3. L02 loads b[i] via base register r4.

  4. L03 must realize *8; since 8=2^3, the shift amount is U1 = 3 (not 8, which would give *256).

  5. L04 stores the result into a[i] via base register r3.

  6. L05 advances r3 (pointer into a) by one element; since int is 4 bytes and memory is byte-addressable, U2 = 4.

  7. L06 advances r4 (pointer into b) the same way: U3 = 4.

  8. L07 increments the loop counter i.

  9. L08 (jmp U4) must return to the condition test, so U4 = L01 (jumping to L02 would skip the exit check).

  10. Combining: (U1,U2,U3,U4) = (3,4,4,L01), which is option (B).

KEY IDEA

Translate the C loop into the assembly skeleton line by line: the shift amount for *8 is log2(8)=3, and pointer increments in a byte-addressable memory must equal the element size (sizeof(int) = 4 bytes here), not 1.

WATCH OUT FOR

Picking U1 = 8 (using the multiplier itself as the shift amount) instead of log2(8) = 3, or forgetting that int is 4 bytes so the byte-addressable pointer increments (U2, U3) must be 4, not 1.

From the GATE 2023 CS paper. Every question of this paper · Download the full paper · All 11 Instructions & addressing questions, with notes

More Instructions & addressing questions