100 likes | 354 Views
Advanced Compiler Design. An Introduction to the Javali Compiler Framework. Zoltán Majó. Javali. Simple object-oriented programming language Your tasks in this lecture are: Implement an SSA-based IR Implement some compiler optimizations Come up with your own project
E N D
Advanced Compiler Design An Introduction to the Javali Compiler Framework Zoltán Majó
Javali • Simple object-oriented programming language • Your tasks in this lecture are: • Implement an SSA-based IR • Implement some compiler optimizations • Come up with your own project • ... and you have to do all this for Javali
Javali • You may build your own Javali compiler • We provide a framework that already implements • Parsing • IR • Code generation • Semantic checking • You can extend the framework
Outline • Building the Control Flow Graph (CFG) • Debugging & Testing
Example: counting # of zero/non-zero elements Program code class Main { void main() { int count, i, zeros, notZeros; count = read(); i = 0; zeros = 0; notZeros = 0; while (i < count) { input = read(); if (input == 0) { zeros++; } else { notZeros++; } i++; } write(zeros); write(notZeros); } }
Constructing the Control Flow Graph Program code Control Flow Graph class Main { void main() { int count, i, zeros, notZeros; count = read(); i = 0; zeros = 0; notZeros = 0; while (i < count) { input = read(); if (input == 0) { zeros++; } else { notZeros++; } i++; } write(zeros); write(notZeros); } } BB1 count = read(); i = 0; zeros = 0; notZeros = 0; false BB2 COND(i < count) true BB3 input = read(); COND(input == 0) true false BB4 zeros++; BB5 notZeros++; BB6 i++; BB7 write(zeros); write(notZeros);
Implementing CFG Construction Program code Abstract Syntax Tree class Main { void main() { int count, i, zeros, notZeros; count = read(); i = 0; zeros = 0; notZeros = 0; while (i < count) { input = read(); if (input == 0) { zeros++; } else { notZeros++; } i++; } write(zeros); write(notZeros); } } Assign Var::count BuiltInRead WhileLoop BinaryOp::< Seq Var::i Var::count Assign ... Var::input BuiltInRead
Implementing CFG Construction • Simple idea: for each method of the program { walk through the method’s list of AST nodes add each AST node to the current basic block } • More action required: IfElse and WhileLoop AST nodes • Create new basic blocks if necessary • Connect new basic blocks to existing ones so that connections reflect the method’s control flow • Not allowed in the CFG: IfElse and WhileLoop AST nodes • Use Visitor pattern to traverse AST: extend AstVisitor • Add all this functionality to CFGBuilder.build()
Debugging • In debug mode compiler dumps CFG into a *cfg.dot file • Use dotty from the Graphviz package to visualize CFG Testing • Example programs included in the javali_tests directory • Get reference CFG generated by our server:run TestSampleProgramsas JUnit test
Thanks! Questions? Get fragment from: https://svn.inf.ethz.ch/svn/trg/cd_students/2012ss/teams/<your_team>/CD2_A0/