Abstract Syntax Trees & Compiler Optimizations & Three-address Codes

profiletegus23
JHU_SP20_CompOrg_Module9_Assignment1.pdf

Abstract Syntax Trees

Using the grammar below, construct the resulting abstract syntax tree from the code below. You may

find the following tool helpful: https://app.diagrams.net/

squared = 0

sum = 0

FOR J = 1 to 40 DO

BEGIN

squared:= J * J

sum = sum + squared

END

WRITE sum

<stmt-list> ::= <stmt> { ; <stmt> }

<stmt> ::= <assign> | <read> | <write> | <for>

<assign> ::= id = <exp>

<exp> ::= <term> { + <term> | - <term> }

<term> ::= <factor> { * <factor> | DIV <factor> }

<factor> ::= id | int | ( <exp> )

<id-list> ::= id { , id }

<for> ::= FOR <index-exp> DO <body>

<index-exp> ::= id = <exp> TO <exp>

<write> ::= WRITE ( <id-list> )

<body> ::= <stmt> | BEGIN <stmt-list> END

Compiler Optimizations & Three-address Codes

For the following piece of C code, examine each line and determine whether or not a compiler

optimization can be applied. If an optimization can be used, write the name of the optimization you would

apply if you were the compiler and, in 2-3 sentences, describe how it makes the program more efficient.

Once you’ve simplified the code, provide a list of three-address codes for the lines of source code

remaining (focus only on the relevant lines, you do not need to provide three-address codes for things

like ‘#include’ and ‘return 0’).

#include <stdio.h>

int main(void) {

bool debug = false;

int a = 0;

int b = 5;

int c = b + b;

int d = 15;

int e = b * c;

if(debug)

{

printf("Running in debug mode.");

// debug code

// debug code

// debug code

// debug code

}

a = b * c + d;

a = a * 1;

for(int i = 0; i < b; i++)

printf("i = %d\n", i+0);

for(int i = 0; i < 5; i++)

printf("%d\n", i*1);

int j = 0;

return 0;

}

  • Abstract Syntax Trees
  • Compiler Optimizations & Three-address Codes