1 2.3: Lab Exercise on translating nested control structures In this exercise, we’ll go through an example of how to translate nested control structures in C++ to MIPS. The thing to focus on is how mechanical this process is! It’s basically what a compiler does to translate your C++ or Java code automatically, to machine language or Java bytecodes. We start with a C++ program from a past quiz: #includeusing std::cin; using std::cout; int main() { int max, num = 4, i; max = 100; while (max > 42) { for (i=1; i < num; i++) { max = max / i; if ((max > i) || (max < 2)) { cout << max; } } cin >> max; } } 2 The first step is to identify the main blocks. It helps to draw boxes around the nested structures. For example, this helps me to see the structure of the code: int max, num = 4, i; max = 100; while (max > 42) { } (It might also be helpful to draw more boxes, say around the if block. Whatever works for you…) for (i=1; i < num; i++) { max = max / i; if ((max > i) || (max < 2)) { cout << max; } } cin >> max; 3 There are lots of ways to go about the translation. I find it easier to work at one level at a time. Let’s start with the outermost level, the while loop. Note that we can translate the while loop completely independently of what’s inside it! (Let’s make $s0 max, $s1 num, $s2 i.) li $s0, 100 # max = 100; li $s1, 4 # num = 4; ble $s0, 42, exit # while (max > 42) { while: # for (i=1; i < num; i++) { # max = max / i; # if ((max > i) || (max < 2)) { # cout << max; # } # } # cin >> max; bgt $s0, 42, loop # } 4 Next we deal with the body of the while loop. It contains two blocks: the for loop, and the cin statement. First we translate the for loop, once again leaving out the body of the for loop: li $s0, 100 # max = 100; li $s1, 4 # num = 4; ble $s0, 42, outw # while (max > 42) { while: li $s2, 1 bge $s2, $s1, maxin # for (i=1; i < num; i++) { for: # max = max / i; # if ((max > i) || (max < 2)) { # cout << max; # } add $s2, $s2, 1 blt $s2, $s1, for # } maxin: # cin >> max; bgt $s0, 42, loop # } outw: 5 Again there are several ways to proceed, but let’s start filling in the body of the for loop. We translate the divide, and then the compound if: li $s0, 100 # max = 100; li $s1, 4 # num = 4; ble $s0, 42, outw # while (max > 42) { while: li $s2, 1 bge $s2, $s1, maxin # for (i=1; i < num; i++) { for: div $s0, $s0, $s2 # max = max / i; bgt $s0, $s2, out # if ((max > i) || (max < 2)) { bge $s0, 2, inci # cout << max; # } inci: add $s2, $s2, 1 blt $s2, $s1, for # } maxin: # cin >> max; bgt $s0, 42, loop # } outw: You should be able to handle the rest. The full solution is at: http://unixlab.sfsu.edu/~whsu/csc256/QUIZ/s09q2blue In summary, keep in mind that we’re not writing code, we’re pretending to be a compiler, translating C++ code to MIPS assembly language. It’s a very mechanical procedure.