Register Allocation

  1. Annotate the code below with liveness information, assuming {a,r} are live at the end.
    b = 5
    a = 2
    e = a * b
    f = a * c
    r = e + f
    a = r * r
    
    Answer:
              {c}
    b = 5
              {b,c}
    a = 2
              {a,b,c}
    e = a * b
              {e,a,c}
    f = a * c
              {e,f}
    r = e + f
              {r}
    a = r * r
              {a,r}
    
  2. For the intermediate code and live sets from question 1, generate Spim code using three registers using the non-graph-coloring algorithm. Be sure to give the live register contents after the generated code, as seen for the first instruction.

    Answer:
    StatementCode Generated Register $t0 Register $t1 Register $t2
    b = 5 li $t0,5b--
    a = 2li $t1,2ba-
    e = a * bmul $t0,$t1,$t0ea-
    f = a * clw $t2,c
    mul $t2,$t1,$t2
    e-f
    r = e + fadd $t0,$t0,$t2r--
    a = r * rmul $t1,$t0,$t0ra-

    sw $t0,r
    sw $t1,a
    - - -

  3. Draw and 3-color the interference graph for the code from question 1.

    Answer:

    Graph:
    
    r ---- a --------- b
          / \         /
        /     \     /
       /        \  /
      e --------- c
       \
        \
         \
          f
    
    Can remove nodes in order: r,f,e,a,b,c (no marked spill nodes) and get colors/registers:
    (0)   (2)
    r ---- a --------- b (1)
          / \         /
        /     \     /
    (1)/        \  /
      e --------- c (0)
       \
        \
         \
          f (0)
    

  4. Using the result of question 3, generate code allocating registers as assigned.

    Answer:
    StatementCode Generated Register $t0 Register $t1 Register $t2
    b = 5 li $t1,5-b-
    a = 2li $t2,2-ba
    e = a * bmul $t1,$t2,$t1--a
    f = a * clw $t0,c
    mul $t0,$t2,$t0
    fe-
    r = e + fadd $t0,$t1,$t0r--
    a = r * rmul $t2,$t0,$t0r-a

    sw $t0,r
    sw $t2,a
    - - -