A3_47_Practical6
A3_47_Practical6
PRACTICAL No. 6
Topic: Code Optimization
Aim: Write a code to implement local optimization techniques until no further optimization is
possible for the given three address code.
Input: Three Address Code (non-optimized)
0: t0 = 4
1: t1 = 2
2: t2 = 4
3: t0 = 3 + t4
4: t1 = 3 - t2
5: t1 = 4 - 2
6: t0 = t2
7: t2 = 5 + t3
8: t3 = 9 / t4
9: t2 = 7 * 8
10: t0 = 3 / 4
11: t1 = t4 / 9
12: t0 = 2 / 9
13: t3 = 10 * 2
14: t4 = t3
Implementation: Identify and apply local optimization techniques to optimize the TAC
Copy Propagation
Constant propagation
Constant Folding
Common Subexpression Elimination
Dead code elimination
Code:
import random
import re
class ThreeAddressCode:
def __init__(self):
self.statements = []
self.statements.append(statement)
var = variables[i]
const = random.choice(constants)
self.add_statement(f"{var} = {const}")
result = random.choice(variables)
op = random.choice(operations)
source = random.choice(variables)
self.add_statement(f"{result} = {source}")
return self.statements
def analyze_code(self):
self.variable_map = {}
self.constant_map = {}
self.expression_map = {}
self.used_variables = set()
self.defined_variables = set()
if len(parts) == 2:
target = parts[0].strip()
self.defined_variables.add(target)
continue
if re.match(r'^\w+$', expression):
self.variable_map[target] = expression
if re.match(r'^\d+$', expression):
self.constant_map[target] = int(expression)
self.expression_map[expr_key] = target
def copy_propagation(self):
modified = False
continue
if new_expr != expression:
modified = True
expression = new_expr
return modified
def constant_propagation(self):
modified = False
continue
target, expression = [part.strip() for part in stmt.split('=', 1)]
if new_expr != expression:
modified = True
expression = new_expr
return modified
def constant_folding(self):
modified = False
continue
if match:
operand1 = int(match.group(1))
operator = match.group(2)
operand2 = int(match.group(3))
result = None
if operator == '+':
if new_expr.isdigit():
self.constant_map[target] = int(new_expr)
modified = True
return modified
def common_subexpression_elimination(self):
continue
modified = True
self.variable_map[target] = self.expression_map[expr_key]
else:
self.expression_map[expr_key] = target
return modified
def dead_code_elimination(self):
modified = False
self.analyze_code()
# Find variables that are defined but never used
i=0
stmt = self.statements[i]
if '=' in stmt:
target = stmt.split('=')[0].strip()
self.statements.pop(i)
modified = True
continue
i += 1
return modified
def optimize(self):
self.print_code()
iteration = 1
while True:
self.analyze_code()
const_prop_mod = self.constant_propagation()
const_fold_mod = self.constant_folding()
cse_mod = self.common_subexpression_elimination()
dce_mod = self.dead_code_elimination()
self.print_code()
iteration += 1
else:
break
self.print_code()
def print_code(self):
print(f"{i}: {stmt}")
def main():
tac = ThreeAddressCode()
tac.generate_random_code(num_statements=15, num_variables=5)
tac.add_statement("a = 3")
tac.add_statement("b = 4")
tac.add_statement("c = a + b") # c = 7
"""
# Apply optimizations
tac.optimize()
if __name__ == "__main__":
main()
After Iteration 1:
0: t0 = 4
1: t0 = 3 + t3
2: t0 = 4
3: t3 = 9 / t3
4: t0 = 0
5: t0 = 0
6: t3 = 20
After Iteration 2:
0: t3 = 9 / t3
1: t3 = 20
0: t3 = 9 / t3
1: t3 = 20