Following are additional examples of syntax-directed definitions and translations.
Generate the three-address code for the following C program:
main() { int i = 1; int a[10]; while(i <= 10) a[i] = ; }
The three-address code for the above C program is:
i = 1
if i <= 10 goto(4)
goto(8)
t 1 = i * width
t 2 = addr( a ) ˆ’ width
t 2[ t 1] = 0
goto(2)
where width is the number of bytes required for each element.
Generate the three-address code for the following program fragment:
while (A < C and B > D) do if A = 1 then C = C+1 else while A <= D do A = A + 3
The three-address code is:
if a < c goto(3)
goto(16)
if b > d goto(5)
goto(16)
if a = 1 goto(7)
goto(10)
t 1 = c +1
c = t 1
goto(1)
if a <= d goto
goto(1)
t 2 = a +3
a = t 2
goto(10)
goto(1)
Generate the three-address code for the following program fragment, where a and b are arrays of size 20 — 20, and there are four bytes per word.
begin add = 0; i = 1; j = 1; do begin add = add + a[i,j] * b[j,i] i = i + 1; j = j + 1; end while i <= 20 and j <= 20; end
The three-address code is:
add = 0
i = 1
j = 1
t 1 = i * 20
t 1 = t 1 + j
t 1 = t 1 * 4
t 2 = addr( a ) ˆ’ 84
t 3 = t 2[ t 1]
t 4 = j * 20
t 4 = t 4 + i
t 4 = t 4 * 4
t 5 = addr( b ) ˆ’ 84
t 6 = t 5[ t 4]
t 7 = t 3 * t 6
t 7 = add + t 7
t 8 = i + 1
i = t 8
t 9 = j + 1
j = t 9
if i <= 20 goto(22)
goto NEXT
if j <= 20 goto(4)
goto NEXT
Consider the program fragment:
sum = 0 for(i = 1; i<= 20; i++) sum = sum + a[i] + b[i];
and generate the three-address code for it. There are four bytes per word.
The three address code is:
sum = 0
i = 1
if i <= 20 goto(8)
goto NEXT
t 1 = i +1
i = t 1
goto(3)
t 2 = i * 4
t 3 = addr( a ) ˆ’ 4
t 4 = t 3[ t 2]
t 5 = i * 4
t 6 = addr( b ) ˆ’ 4
t 7 = t 6[ t 5]
t 8 = sum + t 4
t 8 = t 8 + t 7
sum = t8
goto(5)