Lecture 15-16: Intermediate Code-Generation
|
|
- Alexis Cleopatra Burke
- 6 years ago
- Views:
Transcription
1 Lecture 15-16: Intermediate Code-Generation Dr Kieran T. Herley Department of Computer Science University College Cork KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
2 Overview Simple Two-Pass Tiny Compiler Will sketch simple two-pass compiler for Tiny Pass 1: Parse source and build parse tree (modified TinyParser) Pass 2: Walk tree and generate code (TinyCompiler2) KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
3 Overview Simple Two-Pass Tiny Compiler Will sketch simple two-pass compiler for Tiny Pass 1: Parse source and build parse tree (modified TinyParser) Pass 2: Walk tree and generate code (TinyCompiler2) Variations: Could use simpler syntax tree instead of parse tree Could use jjtree/javacc to generate trees automatically Could use one-pass, parse-and-generate also possible (TinyCompiler1) KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
4 Overview Overview of Tiny Compiler TinyScanner Serves up source to parser, token by token TinyParser2 Modification to recursive descent parser that builds complete parse tree explicitly 1 TinyCompiler2 Recursive tree walk to generate three-address code 1 Can also use jjtree.javacc to generate tree. See TinyParser3 KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
5 Overview Parse Tree Parse tree nodes encode the following: Node type (TinyTreeNode) public enum NodeKind { PROGRAM, STMTSEQUENCE, STATEMENT, IFSTMT,... } Children iterator) Other info. Accessible using getchild(n) and getchildren() (returns value (NUM leaves only) varname (Relevant nodes only) KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
6 Overview Notes on TinyParser2 TinyParser2 augments recursive descent TinyParser by adding tree-building code / <Program> ::= <StmtSequence> / private TinyTreeNode buildprogram() {... TinyTreeNode child = buildstmtsequence(); // builds PT for statement seq. return new TinyTreeNode( TinyTreeNode.NodeKind.PROGRAM, child); } Notes: Parsing methods named buildprogram, buildstmtsequence etc. Method returns root of associated parse (sub)tree KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
7 Overview Notes on TinyParser2 cont d Another example: / <RepeatStmt> ::= repeat <StmtSequence> until <Exp> / private TinyTreeNode buildrepeatstmt() {... match(tinytoken.tokenkind.rw REPEAT); c1 = buildstmtsequence(); // builds PT for loop body match(tinytoken.tokenkind.rw UNTIL); c2 = buildexp(); // builds PT for loop condition } return new TinyTreeNode(TinyTreeNode.NodeKind.REPEATSTMT, c1, c2); // new node with c1 and c2 as its children KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
8 Overview Using jjtree/javacc to Generate Parse/Syntax Tree KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
9 Intermediate Code Generation Simple Code Generation Framework TinyCompiler incorporates recursive method codegen Performs traversal of parse tree, generating code as it goes Node label encodes type of construct represented by subtree rooted at that node Can generate code according to fixed pattern for that construct Can call codegen on childr3en to generate code for subconstructs KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
10 Intermediate Code Generation Parse Tree KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
11 Intermediate Code Generation Tiny and TAC read(x); # read x; t0 = 0; # if 0 < x then t1 = x; t2 = t0 < t1; if (t2!= 1) goto l0; t3 = 1; # fact := 1; fact = t3; l1: # repeat <- *** top-of-loop target t4 = fact; # fact := fact * x; t5 = x; t4 = t4 * t5; fact = t4; t6 = x; # x := x - 1 t7 = 1; t6 = t6 - t7; x = t6; t8 = x; # until x = 0; <- *** condition evaluation t9 = 0; # <- *** t10 = t8 = t9; # <- *** if (t10!= 1) goto l1; # <- *** jump back if false t11 = fact; write(t11); # write fact l0: # end KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
12 Intermediate Code Generation Aside cont d TAC is Universal/Portable Low-level but not architecture-specific TAC-to-X 2 translations more straightforward than Tiny-to-X Can use TAC to facilitate compiler adaptations to various instruction sets TAC as Intermediate representation Quality of code generated critical to success of compiler Intermediate representation such as TAC used as framework for code optimization 2 Your favourite instruction set here KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
13 Intermediate Code Generation Tree Traversal and Code Generation Method codegen traverses parse tree to generate code private String codegen(tinytreenode node) { Iterator <TinyTreeNode> children = node.getchildren(); switch (node.getkind()) { case PROGRAM:... case IFSTMT:... case SIMPLEEXP:... } } Notes: switch identifies node type and selects appropriate case most cases call codegen on each child recursively KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
14 Control Flow Statements Template for StmtSeq stmtseq statement { ; statement } Template: stmtseq Generate code for first statement (rec. call, first child) Generate code for second stateseq2 (rec. call, second child) ETC. KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
15 Control Flow Constructs Repeat Statements repeatstmt repeat stmtseq until exp Generate top-of-loop label Generate code for stmtseq Generate code for exp Generate conditional jump to top-of-loop (jump if false) KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
16 Control Flow Constructs Repeat Statement Example Example repeat x := x + 1 until x = 10 Template l0: ) top label t0 := x; ) code to execute loop body (StmtSequence) t1 := 1; ) t0 := t0 + t1; ) x := t0; ) t2 := x; ) code to evaluate condition (Exp) t3 := 10; ) t4 := t2 == t3; ) if (t4 == 0 ) goto l0; ) jump to top if condition false KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
17 Control Flow Constructs Some Code-Generating Code l0: ) top label t0 := x; ) code to execute loop body t1 := 1; ) t0 := t0 + t1; ) x := t0; ) t2 := x; ) code to evaluate condition t3 := 10; ) t4 := t2 == t3; ) if (t4 == 0 ) goto l0; ) jump to top if condition false Template: 1 Generate top-of-loop label (fresh label) 2 Call codegen on first child to generate code for loop body (recursion) 3 Call codegen on second child to generate code for loop condition (recursion) 4 Generate conditional jump to top-of-loop label (if condition false) KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
18 Control Flow Constructs More REPEATSTMT case in codegen String toplabel = newlabel(); generatelabel(toplabel); codegen(children.next ()); varname = codegen(children.next()); generatejumpfalse(varname, toplabel); // Generate top of-loop label // Generate code for loop body // Generate code for loop condition // Generate jump-back-if-false KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
19 Control Flow Constructs More REPEATSTMT case in codegen String toplabel = newlabel(); generatelabel(toplabel); codegen(children.next ()); varname = codegen(children.next()); generatejumpfalse(varname, toplabel); // Generate top of-loop label // Generate code for loop body // Generate code for loop condition // Generate jump-back-if-false Note on helper methods: newlabel generate sequence of labels (L1, L2,...) generatelabel emits TAC label instruction generatejumpfalse generate TAC instruction of form if (X == 0 ) goto L; where X and L are the specified variable and label KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
20 Control Flow Constructs If Statements Example Template if x < 10 then write 17 end TAC Template === ======== t1 := 10; ) code to evaluate condition (Exp) t0 := x < t1; ) if (t0 == 0 ) goto l0; ) jump to bottom if condition false t2 := 17; ) code to execute then clause (StmtSeque t3 := t2; ) write t3; ) l0: ) bottom label Note: Distinguish if-then from if-then-else by number of children KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
21 Control Flow Constructs If-then-else Statements Example Template if x < 10 then write 17 else write 3 end t0 := x; ) code to evaluate condition t1 := 10; ) t2 := t0 < t1; ) if (t2 == 0 ) goto l0; ) jump to else label of condition false t3 := 17; ) code to execute then clause write t3; ) goto l1; ) jump to bottom label l0: ) else label t4 := 3; ) code to execute else clause write t4; ) l1: ) bottom label KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
22 Expressions Expressions in Tiny simplexp term { addop term } addop + - term factor { mulop factor } mulop * / factor ( exp ) num id Expressions composed of subexpressions; exploit this structure to generate code KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
23 Expressions Code Generation For Expressions Each simplexp is a sequence of term s simplexp term { addop term } Idea: Generate code for each term (and return name of variable that houses term value at runtime) Embed term code-blocks with code to accmulate sum in some variable For simplicity, we generate fresh temporary variable (t1, t2, etc) to hold each subexpression result KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
24 Expressions Example }{{} 1 + }{{} 2 3 first second t1 := 1; ) Code for first term t2 := 2; ) Code for second term t3 := 3; ) t4 := t2 * t3; ) t0 := t1 + t4; ) Code to combine the two Each code for subexpressions has unique tempprray variable (here t1 and t4) to house results (at run time) KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
25 Expressions Expressions in Tiny simplexp term { addop term } addop + - term factor { mulop factor } mulop * / factor ( exp ) num id simplexp Generate code for each constituent term Use fresh temp. variable to accumulate sum 3 term Generate code for each constituent factor Use fresh temp. variable to accumulate product 4 factor id, num Generate instruction to store value in fresh temporary var. exp Generate code for exp 3 Word KH sum (16/11/17) to encompass Lecture both 15-16: additions Intermediateand Code-Generation subtractions / 39
26 Expressions Example KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
27 Expressions Key black shows parse tree for (17) blue shows TAC instructions generates inorder traversal gives sequencing: t2 := 1; t1:= t2; t0:= t1; t4 := 2; t3 := t4;... KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
28 Expressions Generating Code for SIMPLEXP Nodes case SIMPLEEXP: String sumvar = newvar(); tempvar = codegen(children.next()); // Term generatesimple(sumvar, tempvar); while ( children.hasnext()) { TinyTreeNode child = children.next (); String op = ( child.getkind() == TinyTreeNode.NodeKind.ADDOP PLUS? + : ); } tempvar = codegen(children.next()); // Term generatesimple(sumvar, sumvar, op, tempvar); return sumvar; KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
29 Expressions Generating Code for SIMPLEXP Nodes case SIMPLEEXP: String sumvar = newvar();... return sumvar; Goal Generate code that (at run time) will compute the value of the simplexp and return name of variable housing result Notes Children of node represent terms that make up this simplexp Can call codegen on each of children to generate code for constituent terms KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
30 Expressions Generating Code for SIMPLEXP Nodes case SIMPLEEXP: String sumvar = newvar();... codegen(children.next ()); // Term... while ( children.hasnext()) {... codegen(children.next ()); // Term }... return sumvar; Need to intersperse extra code to stitch together results of individual terms into single result KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
31 Expressions Generating Code for SIMPLEXP Nodes case SIMPLEEXP: String sumvar = newvar(); tempvar = codegen(children.next()); // Term generatesimple(sumvar, tempvar); while ( children.hasnext()) { TinyTreeNode child = children. next (); String op = ( child.getkind() == TinyTreeNode.NodeKind.ADDOP PLUS? + : ); } tempvar = codegen(children.next()); // Term generatesimple(sumvar, sumvar, op, tempvar); return sumvar; KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
32 Expressions A More Extensive Example read(x); # read x; t0 = 0; # if 0 < x then t1 = x; t2 = t0 < t1; if (t2!= 1) goto l0; t3 = 1; # fact := 1; fact = t3; l1: # repeat t4 = fact; # fact := fact * x; t5 = x; t4 = t4 * t5; fact = t4; t6 = x; # x := x - 1 t7 = 1; t6 = t6 - t7; x = t6; t8 = x; # until x = 0; t9 = 0; t10 = t8 = t9; if (t10!= 1) goto l1; t11 = fact; write(t11); # write fact l0: # end KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
33 One-Pass Tiny Compiler One-Pass Tiny Compiler Can merge parsing and code generation phases into single pass over source No explicit parse tree (implicit in structure of recursion) Parsing and code generation code interleaved See TinyCompiler1 Pros and Cons One-pass more efficient More difficult to understand (and develop) Some issues more difficult to tackle in one-pass framework (e.g. code optimization) KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
34 One-Pass Tiny Compiler TinyCompiler1 TinyParser Parses source: Reads through it and reconciles it with Tiny grammar rules TinyCompiler1 Parses and translates source Syntax-driven process built on top of TinyParser chassis Generates three-address code KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
35 One-Pass Tiny Compiler How TinyCompiler Works cont d Code-generating additions to parseassignstmt (renamed translateassignstmt) / / private void translateassignstmt () {... match(tinytoken.tokenkind.id); match(tinytoken.tokenkind.sym ASSIGN);... translateexp ();... } Structure of parse encodes detail of structure of source program: its constituent stataments, their sequencing and nesting and so on Interleave code-generating code with parsing code so TinyCompiler translates as it parses Parse-directed KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
36 One-Pass Tiny Compiler How TinyCompiler Works cont d Code-generating additions to parseassignstmt (renamed translateassignstmt) 1 Record name of LHS variable (say l) private void translateassignstmt () 2 translateexp { TinyToken lhs = current; // (1) generates code to String lhsvar = lhs. getspelling (); evaluate RHS match(tinytoken.tokenkind.id); match(tinytoken.tokenkind.sym ASSIGN); expression returns name of String rhsvar = translateexp (); // (2) temp. variable with emit(lhsvar+ = +rhsvar+ ; ); // (3) expr. value (say } t RHS ) Note: emit is essentially System.out.println 3 Generate code l = t RHS KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
37 One-Pass Tiny Compiler How TinyParser Works cont d private void translaterepeatstmt() { String toplabel = newlabel(); emit(toplabel+ : ); match(tinytoken.tokenkind.rw REPEAT); translatestmtsequence(); match(tinytoken.tokenkind.rw UNTIL); String varname = translateexp(); // *** gen. top of loop label // (gen. loop body code) // *** gen. condit. eval. code } emit( if ( +varname+!= 1) goto, toplabel); // *** gen. jumpback on false KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
38 One-Pass Tiny Compiler Factorial Example Revisited read(x); # read x; t0 = 0; # if 0 < x then t1 = x; t2 = t0 < t1; if (t2!= 1) goto l0; t3 = 1; # fact := 1; fact = t3; l1: # repeat <- *** top-of-loop target t4 = fact; # fact := fact * x; t5 = x; t4 = t4 * t5; fact = t4; t6 = x; # x := x - 1 t7 = 1; t6 = t6 - t7; x = t6; t8 = x; # until x = 0; <- *** condition evaluation t9 = 0; # <- *** t10 = t8 = t9; # <- *** if (t10!= 1) goto l1; # <- *** jump back if false t11 = fact; write(t11); # write fact l0: # end KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
39 One-Pass Tiny Compiler Aside Code optimization producing best code from source is vitally important aspect of production compilers We ignore this completely: no attempt to minimize number of instructions or labels TAC often used as platform for code optimization KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
40 One-Pass Tiny Compiler Aside Code optimization producing best code from source is vitally important aspect of production compilers We ignore this completely: no attempt to minimize number of instructions or labels TAC often used as platform for code optimization KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
41 Other Bits and Pieces TAC Engine TacEngine can execute three-address codegen Exercise: how to develop same? KH (16/11/17) Lecture 15-16: Intermediate Code-Generation / 39
Compilers. Intermediate representations and code generation. Yannis Smaragdakis, U. Athens (original slides by Sam
Compilers Intermediate representations and code generation Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Today Intermediate representations and code generation Scanner Parser Semantic
More informationLecture 12: Parser-Generating Tools
Lecture 12: Parser-Generating Tools Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (31/10/17) Lecture 12: Parser-Generating Tools 2017-2018 1 / 27 Summary Overview
More informationA Simple Syntax-Directed Translator
Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called
More informationLecture 8: Context Free Grammars
Lecture 8: Context Free s Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (12/10/17) Lecture 8: Context Free s 2017-2018 1 / 1 Specifying Non-Regular Languages Recall
More informationSimple Lexical Analyzer
Lecture 7: Simple Lexical Analyzer Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (03/10/17) Lecture 7: Simple Lexical Analyzer 2017-2018 1 / 1 Summary Use of jflex
More informationRecursive Descent Parsers
Recursive Descent Parsers Lecture 7 Robb T. Koether Hampden-Sydney College Wed, Jan 28, 2015 Robb T. Koether (Hampden-Sydney College) Recursive Descent Parsers Wed, Jan 28, 2015 1 / 18 1 Parsing 2 LL Parsers
More informationCSE302: Compiler Design
CSE302: Compiler Design Instructor: Dr. Liang Cheng Department of Computer Science and Engineering P.C. Rossin College of Engineering & Applied Science Lehigh University January 30, 2007 Outline Recap
More informationProject Compiler. CS031 TA Help Session November 28, 2011
Project Compiler CS031 TA Help Session November 28, 2011 Motivation Generally, it s easier to program in higher-level languages than in assembly. Our goal is to automate the conversion from a higher-level
More informationIntermediate Representations
Intermediate Representations A variety of intermediate representations are used in compilers Most common intermediate representations are: Abstract Syntax Tree Directed Acyclic Graph (DAG) Three-Address
More informationIntermediate Code Generation
Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target
More informationCIT 3136 Lecture 7. Top-Down Parsing
CIT 3136 Lecture 7 Top-Down Parsing Chapter 4: Top-down Parsing A top-down parsing algorithm parses an input string of tokens by tracing out the steps in a leftmost derivation. Such an algorithm is called
More informationSemantic actions for declarations and expressions
Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate
More informationCSc 453 Intermediate Code Generation
CSc 453 Intermediate Code Generation Saumya Debray The University of Arizona Tucson Overview Intermediate representations span the gap between the source and target languages: closer to target language;
More informationCSE P 501 Compilers. Intermediate Representations Hal Perkins Spring UW CSE P 501 Spring 2018 G-1
CSE P 501 Compilers Intermediate Representations Hal Perkins Spring 2018 UW CSE P 501 Spring 2018 G-1 Administrivia Semantics/types/symbol table project due ~2 weeks how goes it? Should be caught up on
More informationLecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions
Lecture 4: Applications CS2504/CS4092 Algorithms and Linear Data Structures Dr Kieran T. Herley Department of Computer Science University College Cork Summary. Postfix notation for arithmetic expressions.
More informationTiny Compiler: Back End
CS 301 Spring 2016 January 29 Lab Tiny Compiler: Back End Plan Source Program Lexical Analysis Syntax Analysis Semantic Analysis Intermediate Code Generation Machine- Independent Optimization Code Generation
More informationCompilers. Compiler Construction Tutorial The Front-end
Compilers Compiler Construction Tutorial The Front-end Salahaddin University College of Engineering Software Engineering Department 2011-2012 Amanj Sherwany http://www.amanj.me/wiki/doku.php?id=teaching:su:compilers
More informationIntermediate representation
Intermediate representation Goals: encode knowledge about the program facilitate analysis facilitate retargeting facilitate optimization scanning parsing HIR semantic analysis HIR intermediate code gen.
More informationFall Compiler Principles Lecture 6: Intermediate Representation. Roman Manevich Ben-Gurion University of the Negev
Fall 2015-2016 Compiler Principles Lecture 6: Intermediate Representation Roman Manevich Ben-Gurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation
More informationSemantic analysis and intermediate representations. Which methods / formalisms are used in the various phases during the analysis?
Semantic analysis and intermediate representations Which methods / formalisms are used in the various phases during the analysis? The task of this phase is to check the "static semantics" and generate
More informationIt parses an input string of tokens by tracing out the steps in a leftmost derivation.
It parses an input string of tokens by tracing out CS 4203 Compiler Theory the steps in a leftmost derivation. CHAPTER 4: TOP-DOWN PARSING Part1 And the implied traversal of the parse tree is a preorder
More informationWhy do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.
.00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do
More informationParsing II Top-down parsing. Comp 412
COMP 412 FALL 2018 Parsing II Top-down parsing Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled
More informationToday. Assignments. Lecture Notes CPSC 326 (Spring 2019) Operator Associativity & Precedence. AST Navigation. HW4 out (due next Thurs)
Today Operator Associativity & Precedence AST Navigation Assignments HW4 out (due next Thurs) S. Bowers 1 of 10 Generating Abstract Syntax Trees (ASTs) 1. The parsing step both checks syntax and builds
More informationLecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley
Lecture 11: while loops CS1068+ Introductory Programming in Python Dr Kieran T. Herley Python s while loop. Summary Department of Computer Science University College Cork 2017-2018 KH (24/10/17) Lecture
More informationWednesday, September 9, 15. Parsers
Parsers What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda
More informationSemantic actions for declarations and expressions
Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate
More informationParsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs:
What is a parser Parsers A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda
More informationChapter 3: CONTEXT-FREE GRAMMARS AND PARSING Part2 3.3 Parse Trees and Abstract Syntax Trees
Chapter 3: CONTEXT-FREE GRAMMARS AND PARSING Part2 3.3 Parse Trees and Abstract Syntax Trees 3.3.1 Parse trees 1. Derivation V.S. Structure Derivations do not uniquely represent the structure of the strings
More informationCIT Lecture 5 Context-Free Grammars and Parsing 4/2/2003 1
CIT3136 - Lecture 5 Context-Free Grammars and Parsing 4/2/2003 1 Definition of a Context-free Grammar: An alphabet or set of basic symbols (like regular expressions, only now the symbols are whole tokens,
More informationSemantic actions for declarations and expressions. Monday, September 28, 15
Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate
More informationLecture 5: Regular Expression and Finite Automata
Lecture 5: Regular Expression and Finite Automata Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (28/09/17) Lecture 5: Regular Expression and Finite Automata 2017-2018
More informationContext-Free Grammar. Concepts Introduced in Chapter 2. Parse Trees. Example Grammar and Derivation
Concepts Introduced in Chapter 2 A more detailed overview of the compilation process. Parsing Scanning Semantic Analysis Syntax-Directed Translation Intermediate Code Generation Context-Free Grammar A
More informationLecture 3 Local Optimizations, Intro to SSA
Lecture 3 Local Optimizations, Intro to SSA I. Basic blocks & Flow graphs II. Abstraction 1: DAG III. Abstraction 2: Value numbering IV. Intro to SSA ALSU 8.4-8.5, 6.2.4 Phillip B. Gibbons 15-745: Local
More informationIntermediate Code & Local Optimizations. Lecture 20
Intermediate Code & Local Optimizations Lecture 20 Lecture Outline Intermediate code Local optimizations Next time: global optimizations 2 Code Generation Summary We have discussed Runtime organization
More informationCPS 506 Comparative Programming Languages. Syntax Specification
CPS 506 Comparative Programming Languages Syntax Specification Compiling Process Steps Program Lexical Analysis Convert characters into a stream of tokens Lexical Analysis Syntactic Analysis Send tokens
More informationCOMP 181. Prelude. Intermediate representations. Today. High-level IR. Types of IRs. Intermediate representations and code generation
Prelude COMP 181 Lecture 14 Intermediate representations and code generation October 19, 2006 Who is Seth Lloyd? Professor of mechanical engineering at MIT, pioneer in quantum computing Article in Nature:
More informationMore On Syntax Directed Translation
More On Syntax Directed Translation 1 Types of Attributes We have productions of the form: A X 1 X 2 X 3... X n with semantic rules of the form: b:= f(c 1, c 2, c 3,..., c n ) where b and the c s are attributes
More informationChapter 3. Describing Syntax and Semantics ISBN
Chapter 3 Describing Syntax and Semantics ISBN 0-321-49362-1 Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Copyright 2009 Addison-Wesley. All
More informationAlternatives for semantic processing
Semantic Processing Copyright c 2000 by Antony L. Hosking. Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies
More informationModule 9: Binary trees
Module 9: Binary trees Readings: HtDP, Section 14 We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples.
More information3. Context-free grammars & parsing
3. Context-free grammars & parsing The parsing process sequences of tokens parse tree or syntax tree a / [ / index / ]/= / 4 / + / 2 The parsing process sequences of tokens parse tree or syntax tree a
More informationCS 314 Principles of Programming Languages. Lecture 9
CS 314 Principles of Programming Languages Lecture 9 Zheng Zhang Department of Computer Science Rutgers University Wednesday 5 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Homework
More informationReview main idea syntax-directed evaluation and translation. Recall syntax-directed interpretation in recursive descent parsers
Plan for Today Review main idea syntax-directed evaluation and translation Recall syntax-directed interpretation in recursive descent parsers Syntax-directed evaluation and translation in shift-reduce
More informationParsing III. (Top-down parsing: recursive descent & LL(1) )
Parsing III (Top-down parsing: recursive descent & LL(1) ) Roadmap (Where are we?) Previously We set out to study parsing Specifying syntax Context-free grammars Ambiguity Top-down parsers Algorithm &
More informationLecture 8: Simple Calculator Application
Lecture 8: Simple Calculator Application Postfix Calculator Dr Kieran T. Herley Department of Computer Science University College Cork 2016/17 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17
More informationCSE 401/M501 Compilers
CSE 401/M501 Compilers Intermediate Representations Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 G-1 Agenda Survey of Intermediate Representations Graphical Concrete/Abstract Syntax Trees (ASTs)
More informationCPSC 411, 2015W Term 2 Midterm Exam Date: February 25, 2016; Instructor: Ron Garcia
CPSC 411, 2015W Term 2 Midterm Exam Date: February 25, 2016; Instructor: Ron Garcia This is a closed book exam; no notes; no calculators. Answer in the space provided. There are 8 questions on 14 pages,
More informationCompiler Principle and Technology. Prof. Dongming LU April 15th, 2019
Compiler Principle and Technology Prof. Dongming LU April 15th, 2019 PART TWO 6. Semantic Analysis Contents Part One 6.1 Attributes and Attribute Grammars Part Two 6.2 Algorithms for Attribute Computation
More informationIntroduction to Parsing. Lecture 5
Introduction to Parsing Lecture 5 1 Outline Regular languages revisited Parser overview Context-free grammars (CFG s) Derivations Ambiguity 2 Languages and Automata Formal languages are very important
More informationThe Parsing Problem (cont d) Recursive-Descent Parsing. Recursive-Descent Parsing (cont d) ICOM 4036 Programming Languages. The Complexity of Parsing
ICOM 4036 Programming Languages Lexical and Syntax Analysis Lexical Analysis The Parsing Problem Recursive-Descent Parsing Bottom-Up Parsing This lecture covers review questions 14-27 This lecture covers
More informationIntermediate Code & Local Optimizations
Lecture Outline Intermediate Code & Local Optimizations Intermediate code Local optimizations Compiler Design I (2011) 2 Code Generation Summary We have so far discussed Runtime organization Simple stack
More informationParsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468
Parsers Xiaokang Qiu Purdue University ECE 468 August 31, 2018 What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure
More informationsyntax tree - * * * - * * * * * 2 1 * * 2 * (2 * 1) - (1 + 0)
0//7 xpression rees rom last time: we can draw a syntax tree for the Java expression ( 0). 0 ASS, GRAMMARS, PARSING, R RAVRSALS Lecture 3 CS0 all 07 Preorder, Postorder, and Inorder Preorder, Postorder,
More informationCSE P 501 Compilers. Parsing & Context-Free Grammars Hal Perkins Winter /15/ Hal Perkins & UW CSE C-1
CSE P 501 Compilers Parsing & Context-Free Grammars Hal Perkins Winter 2008 1/15/2008 2002-08 Hal Perkins & UW CSE C-1 Agenda for Today Parsing overview Context free grammars Ambiguous grammars Reading:
More informationCSE 401/M501 Compilers
CSE 401/M501 Compilers x86-64, Running MiniJava, Basic Code Generation and Bootstrapping Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 M-1 Running MiniJava Programs To run a MiniJava program Space
More informationSemantic Analysis and Intermediate Code Generation
DDD55 Compilers and Interpreters DDB44 Compiler Construction Semantic Analysis and Intermediate Code Generation Semantic Analysis and Intermediate Code Generation able management source program Lexical
More informationThere are many other applications like constructing the expression tree from the postorder expression. I leave you with an idea as how to do it.
Programming, Data Structures and Algorithms Prof. Hema Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 49 Module 09 Other applications: expression tree
More informationFall Compiler Principles Lecture 5: Intermediate Representation. Roman Manevich Ben-Gurion University of the Negev
Fall 2016-2017 Compiler Principles Lecture 5: Intermediate Representation Roman Manevich Ben-Gurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation
More informationComp 411 Principles of Programming Languages Lecture 3 Parsing. Corky Cartwright January 11, 2019
Comp 411 Principles of Programming Languages Lecture 3 Parsing Corky Cartwright January 11, 2019 Top Down Parsing What is a context-free grammar (CFG)? A recursive definition of a set of strings; it is
More informationLecture Outline. Intermediate code Intermediate Code & Local Optimizations. Local optimizations. Lecture 14. Next time: global optimizations
Lecture Outline Intermediate code Intermediate Code & Local Optimizations Lecture 14 Local optimizations Next time: global optimizations Prof. Aiken CS 143 Lecture 14 1 Prof. Aiken CS 143 Lecture 14 2
More informationChapter 4 :: Semantic Analysis
Chapter 4 :: Semantic Analysis Programming Language Pragmatics, Fourth Edition Michael L. Scott Copyright 2016 Elsevier 1 Chapter04_Semantic_Analysis_4e - Tue November 21, 2017 Role of Semantic Analysis
More informationCS 406/534 Compiler Construction Parsing Part I
CS 406/534 Compiler Construction Parsing Part I Prof. Li Xu Dept. of Computer Science UMass Lowell Fall 2004 Part of the course lecture notes are based on Prof. Keith Cooper, Prof. Ken Kennedy and Dr.
More informationSyntax-Directed Translation Part II
Syntax-Directed Translation Part II Chapter 5 Slides adapted from : Robert van Engelen, Florida State University Alessandro Artale, Free University of Bolzano Syntax-Directed Translation Schemes Syntax-directed
More informationA language is a subset of the set of all strings over some alphabet. string: a sequence of symbols alphabet: a set of symbols
The current topic:! Introduction! Object-oriented programming: Python! Functional programming: Scheme! Python GUI programming (Tkinter)! Types and values! Logic programming: Prolog! Introduction! Rules,
More informationDr. D.M. Akbar Hussain
Syntax Analysis Parsing Syntax Or Structure Given By Determines Grammar Rules Context Free Grammar 1 Context Free Grammars (CFG) Provides the syntactic structure: A grammar is quadruple (V T, V N, S, R)
More informationMIT Top-Down Parsing. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology
MIT 6.035 Top-Down Parsing Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Orientation Language specification Lexical structure regular expressions Syntactic structure
More informationLexical and Syntax Analysis. Top-Down Parsing
Lexical and Syntax Analysis Top-Down Parsing Easy for humans to write and understand String of characters Lexemes identified String of tokens Easy for programs to transform Data structure Syntax A syntax
More informationParsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones
Parsing III (Top-down parsing: recursive descent & LL(1) ) (Bottom-up parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,
More informationSemantic actions for expressions
Semantic actions for expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate representations
More informationWe ve written these as a grammar, but the grammar also stands for an abstract syntax tree representation of the IR.
CS 4120 Lecture 14 Syntax-directed translation 26 September 2011 Lecturer: Andrew Myers We want to translate from a high-level programming into an intermediate representation (IR). This lecture introduces
More informationCOP5621 Exam 3 - Spring 2005
COP5621 Exam 3 - Spring 2005 Name: (Please print) Put the answers on these sheets. Use additional sheets when necessary. Show how you derived your answer when applicable (this is required for full cred
More informationSyntax-Directed Translation. Lecture 14
Syntax-Directed Translation Lecture 14 (adapted from slides by R. Bodik) 9/27/2006 Prof. Hilfinger, Lecture 14 1 Motivation: parser as a translator syntax-directed translation stream of tokens parser ASTs,
More informationProgramming Languages
Programming Languages Tevfik Koşar Lecture - IX February 14 th, 2006 1 Roadmap Semantic Analysis Role of Semantic Analysis Static vs Dynamic Analysis Attribute Grammars Evaluating Attributes Decoration
More informationLanguages and Compiler Design II IR Code Generation I
Languages and Compiler Design II IR Code Generation I Material provided by Prof. Jingke Li Stolen with pride and modified by Herb Mayer PSU Spring 2010 rev.: 4/16/2010 PSU CS322 HM 1 Agenda Grammar G1
More informationCSE 12 Abstract Syntax Trees
CSE 12 Abstract Syntax Trees Compilers and Interpreters Parse Trees and Abstract Syntax Trees (AST's) Creating and Evaluating AST's The Table ADT and Symbol Tables 16 Using Algorithms and Data Structures
More informationChapter 20: Binary Trees
Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other
More informationA programming language requires two major definitions A simple one pass compiler
A programming language requires two major definitions A simple one pass compiler [Syntax: what the language looks like A context-free grammar written in BNF (Backus-Naur Form) usually suffices. [Semantics:
More informationCS 315 Programming Languages Syntax. Parser. (Alternatively hand-built) (Alternatively hand-built)
Programming languages must be precise Remember instructions This is unlike natural languages CS 315 Programming Languages Syntax Precision is required for syntax think of this as the format of the language
More informationCS143 - Written Assignment 4 Reference Solutions
CS143 - Written Assignment 4 Reference Solutions 1. Consider the following program in Cool, representing a slightly over-engineered implementation which calculates the factorial of 3 using an operator
More informationA simple syntax-directed
Syntax-directed is a grammaroriented compiling technique Programming languages: Syntax: what its programs look like? Semantic: what its programs mean? 1 A simple syntax-directed Lexical Syntax Character
More informationWriting Evaluators MIF08. Laure Gonnord
Writing Evaluators MIF08 Laure Gonnord Laure.Gonnord@univ-lyon1.fr Evaluators, what for? Outline 1 Evaluators, what for? 2 Implementation Laure Gonnord (Lyon1/FST) Writing Evaluators 2 / 21 Evaluators,
More informationParsing. Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP 412 at Rice.
Parsing Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP 412 at Rice. Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students
More informationExercise 1: Balanced Parentheses
Exercise 1: Balanced Parentheses Show that the following balanced parentheses grammar is ambiguous (by finding two parse trees for some input sequence) and find unambiguous grammar for the same language.
More informationFaculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology
Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4020 July 5, 2007 14.00-15.30 This exam (8 pages) consists of 60 True/False
More informationLast time. What are compilers? Phases of a compiler. Scanner. Parser. Semantic Routines. Optimizer. Code Generation. Sunday, August 29, 2010
Last time Source code Scanner Tokens Parser What are compilers? Phases of a compiler Syntax tree Semantic Routines IR Optimizer IR Code Generation Executable Extra: Front-end vs. Back-end Scanner + Parser
More informationChapter 4. Lexical and Syntax Analysis
Chapter 4 Lexical and Syntax Analysis Chapter 4 Topics Introduction Lexical Analysis The Parsing Problem Recursive-Descent Parsing Bottom-Up Parsing Copyright 2012 Addison-Wesley. All rights reserved.
More informationModule 8: Binary trees
Module 8: Binary trees Readings: HtDP, Section 14 We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples.
More informationLL(k) Compiler Construction. Choice points in EBNF grammar. Left recursive grammar
LL(k) Compiler Construction More LL parsing Abstract syntax trees Lennart Andersson Revision 2012 01 31 2012 Related names top-down the parse tree is constructed top-down recursive descent if it is implemented
More informationChapter 1. Fundamentals of Higher Order Programming
Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme
More informationCSCI312 Principles of Programming Languages
Copyright 2006 The McGraw-Hill Companies, Inc. CSCI312 Principles of Programming Languages! LL Parsing!! Xu Liu Derived from Keith Cooper s COMP 412 at Rice University Recap Copyright 2006 The McGraw-Hill
More informationLL(k) Compiler Construction. Top-down Parsing. LL(1) parsing engine. LL engine ID, $ S 0 E 1 T 2 3
LL(k) Compiler Construction More LL parsing Abstract syntax trees Lennart Andersson Revision 2011 01 31 2010 Related names top-down the parse tree is constructed top-down recursive descent if it is implemented
More informationPrograms as data Parsing cont d; first-order functional language, type checking
Programs as data Parsing cont d; first-order functional language, type checking Peter Sestoft Monday 2009-09-14 Plan for today Exercises week 2 Parsing: LR versus LL How does an LR parser work Hand-writing
More informationRecap: Functions as first-class values
Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse
More informationCOMPILER DESIGN. Intermediate representations Introduction to code generation. COMP 442/6421 Compiler Design
1 COMPILER DESIGN Intermediate representations Introduction to code generation Concordia University Introduction to code generation 2 Front end: Lexical Analysis Syntactic Analysis Intermediate Code/Representation
More informationSyntax Intro and Overview. Syntax
Syntax Intro and Overview CS331 Syntax Syntax defines what is grammatically valid in a programming language Set of grammatical rules E.g. in English, a sentence cannot begin with a period Must be formal
More informationSyntax Analysis, III Comp 412
COMP 412 FALL 2017 Syntax Analysis, III Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp
More informationCompiler Design Concepts. Syntax Analysis
Compiler Design Concepts Syntax Analysis Introduction First task is to break up the text into meaningful words called tokens. newval=oldval+12 id = id + num Token Stream Lexical Analysis Source Code (High
More informationFaculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology
Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4303 April 9, 2010 14.00-15.30 This exam (6 pages) consists of 52 True/False
More informationIntermediate Code Generation
Intermediate Code Generation Front-end intermediate code generation source program Lexical Analyzer Syntax Analyzer Semantic Analyzer Int. Code Generator intermediate representation Symbol Table Advantages
More information