|
| 1 | +# Optimiser |
| 2 | + |
| 3 | +The optimiser uses the syntax tree generated by the parser and prunes redundant |
| 4 | +parts of it. This greatly reduces the size of the program to be compiled, while achieving the |
| 5 | +same result. |
| 6 | + |
| 7 | +In this compiler, the optimisation runs before the target code generation, so the |
| 8 | +generated code is optimised. The implemented optimisations include: |
| 9 | + |
| 10 | +* Replacing constant variables with constants – this is done by checking if a variable |
| 11 | +is ever reassigned. If it is not reassigned (i.e. it is a constant), all references to the |
| 12 | +variable are replaced with the constant instead. |
| 13 | + |
| 14 | +* Replacing operations on two constants with the result – this is done by checking |
| 15 | +arithmetic expressions for having constants as both of the variables. If so, the |
| 16 | +operation gets performed during compilation-time. |
| 17 | + |
| 18 | +* Removing unused variables – this is done by checking if a variable is declared but |
| 19 | +never used. If this is the case, the declaration is removed. |
| 20 | + |
| 21 | +* Reducing the size of the tree – this is done by reducing the number of sequence |
| 22 | +nodes by merging sequence nodes with only one child. |
| 23 | + |
| 24 | +This is done by recursively optimising the syntax tree repeatedly until no more |
| 25 | +optimisations are made during a single run. As a result of this amount of heavy optimisation, |
| 26 | +all of the sample programs are compiled down to a single print statement. |
| 27 | + |
| 28 | +The optimised version of a previous example can be seen in |
| 29 | +Figure 19. |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +*Figure 19. Optimised Version of Tree in Figure 13 (A1.2. number-addition.ts)* |
| 34 | + |
| 35 | +If the target code generator is given the optimised syntax tree above, the code in |
| 36 | +Figure 20 is generated. |
| 37 | + |
| 38 | +```C |
| 39 | + #include <stdio.h> |
| 40 | + int main() { |
| 41 | + printf("%d", 3); |
| 42 | + return 0; |
| 43 | + } |
| 44 | +``` |
| 45 | +*Figure 20. Code Generated from Figure 19 (A1.2. number-addition.ts)* |
| 46 | +
|
| 47 | +Finally, running the Mocha test suite on the optimised compiler reveals that all of the |
| 48 | +tests defined in the Test Cases section pass, as seen in Figure 21. |
| 49 | +
|
| 50 | + |
| 51 | +
|
| 52 | +*Figure 21. Final Run of Mocha Test Suite (from Test Cases)* |
0 commit comments